SemaExpr.cpp 450 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787
  1. //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
  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 semantic analysis for expressions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "clang/Sema/DelayedDiagnostic.h"
  15. #include "clang/Sema/Initialization.h"
  16. #include "clang/Sema/Lookup.h"
  17. #include "clang/Sema/ScopeInfo.h"
  18. #include "clang/Sema/AnalysisBasedWarnings.h"
  19. #include "clang/AST/ASTContext.h"
  20. #include "clang/AST/ASTConsumer.h"
  21. #include "clang/AST/ASTMutationListener.h"
  22. #include "clang/AST/CXXInheritance.h"
  23. #include "clang/AST/DeclObjC.h"
  24. #include "clang/AST/DeclTemplate.h"
  25. #include "clang/AST/EvaluatedExprVisitor.h"
  26. #include "clang/AST/Expr.h"
  27. #include "clang/AST/ExprCXX.h"
  28. #include "clang/AST/ExprObjC.h"
  29. #include "clang/AST/RecursiveASTVisitor.h"
  30. #include "clang/AST/TypeLoc.h"
  31. #include "clang/Basic/PartialDiagnostic.h"
  32. #include "clang/Basic/SourceManager.h"
  33. #include "clang/Basic/TargetInfo.h"
  34. #include "clang/Lex/LiteralSupport.h"
  35. #include "clang/Lex/Preprocessor.h"
  36. #include "clang/Sema/DeclSpec.h"
  37. #include "clang/Sema/Designator.h"
  38. #include "clang/Sema/Scope.h"
  39. #include "clang/Sema/ScopeInfo.h"
  40. #include "clang/Sema/ParsedTemplate.h"
  41. #include "clang/Sema/SemaFixItUtils.h"
  42. #include "clang/Sema/Template.h"
  43. #include "TreeTransform.h"
  44. using namespace clang;
  45. using namespace sema;
  46. /// \brief Determine whether the use of this declaration is valid, without
  47. /// emitting diagnostics.
  48. bool Sema::CanUseDecl(NamedDecl *D) {
  49. // See if this is an auto-typed variable whose initializer we are parsing.
  50. if (ParsingInitForAutoVars.count(D))
  51. return false;
  52. // See if this is a deleted function.
  53. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  54. if (FD->isDeleted())
  55. return false;
  56. }
  57. // See if this function is unavailable.
  58. if (D->getAvailability() == AR_Unavailable &&
  59. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  60. return false;
  61. return true;
  62. }
  63. static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
  64. NamedDecl *D, SourceLocation Loc,
  65. const ObjCInterfaceDecl *UnknownObjCClass) {
  66. // See if this declaration is unavailable or deprecated.
  67. std::string Message;
  68. AvailabilityResult Result = D->getAvailability(&Message);
  69. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
  70. if (Result == AR_Available) {
  71. const DeclContext *DC = ECD->getDeclContext();
  72. if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
  73. Result = TheEnumDecl->getAvailability(&Message);
  74. }
  75. switch (Result) {
  76. case AR_Available:
  77. case AR_NotYetIntroduced:
  78. break;
  79. case AR_Deprecated:
  80. S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
  81. break;
  82. case AR_Unavailable:
  83. if (S.getCurContextAvailability() != AR_Unavailable) {
  84. if (Message.empty()) {
  85. if (!UnknownObjCClass)
  86. S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
  87. else
  88. S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
  89. << D->getDeclName();
  90. }
  91. else
  92. S.Diag(Loc, diag::err_unavailable_message)
  93. << D->getDeclName() << Message;
  94. S.Diag(D->getLocation(), diag::note_unavailable_here)
  95. << isa<FunctionDecl>(D) << false;
  96. }
  97. break;
  98. }
  99. return Result;
  100. }
  101. /// \brief Emit a note explaining that this function is deleted or unavailable.
  102. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  103. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
  104. if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
  105. // If the method was explicitly defaulted, point at that declaration.
  106. if (!Method->isImplicit())
  107. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  108. // Try to diagnose why this special member function was implicitly
  109. // deleted. This might fail, if that reason no longer applies.
  110. CXXSpecialMember CSM = getSpecialMember(Method);
  111. if (CSM != CXXInvalid)
  112. ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
  113. return;
  114. }
  115. Diag(Decl->getLocation(), diag::note_unavailable_here)
  116. << 1 << Decl->isDeleted();
  117. }
  118. /// \brief Determine whether a FunctionDecl was ever declared with an
  119. /// explicit storage class.
  120. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  121. for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
  122. E = D->redecls_end();
  123. I != E; ++I) {
  124. if (I->getStorageClassAsWritten() != SC_None)
  125. return true;
  126. }
  127. return false;
  128. }
  129. /// \brief Check whether we're in an extern inline function and referring to a
  130. /// variable or function with internal linkage (C11 6.7.4p3).
  131. ///
  132. /// This is only a warning because we used to silently accept this code, but
  133. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  134. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  135. /// and so while there may still be user mistakes, most of the time we can't
  136. /// prove that there are errors.
  137. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  138. const NamedDecl *D,
  139. SourceLocation Loc) {
  140. // This is disabled under C++; there are too many ways for this to fire in
  141. // contexts where the warning is a false positive, or where it is technically
  142. // correct but benign.
  143. if (S.getLangOpts().CPlusPlus)
  144. return;
  145. // Check if this is an inlined function or method.
  146. FunctionDecl *Current = S.getCurFunctionDecl();
  147. if (!Current)
  148. return;
  149. if (!Current->isInlined())
  150. return;
  151. if (Current->getLinkage() != ExternalLinkage)
  152. return;
  153. // Check if the decl has internal linkage.
  154. if (D->getLinkage() != InternalLinkage)
  155. return;
  156. // Downgrade from ExtWarn to Extension if
  157. // (1) the supposedly external inline function is in the main file,
  158. // and probably won't be included anywhere else.
  159. // (2) the thing we're referencing is a pure function.
  160. // (3) the thing we're referencing is another inline function.
  161. // This last can give us false negatives, but it's better than warning on
  162. // wrappers for simple C library functions.
  163. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  164. bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
  165. if (!DowngradeWarning && UsedFn)
  166. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  167. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
  168. : diag::warn_internal_in_extern_inline)
  169. << /*IsVar=*/!UsedFn << D;
  170. // Suggest "static" on the inline function, if possible.
  171. if (!hasAnyExplicitStorageClass(Current)) {
  172. const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
  173. SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
  174. S.Diag(DeclBegin, diag::note_convert_inline_to_static)
  175. << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
  176. }
  177. S.Diag(D->getCanonicalDecl()->getLocation(),
  178. diag::note_internal_decl_declared_here)
  179. << D;
  180. }
  181. /// \brief Determine whether the use of this declaration is valid, and
  182. /// emit any corresponding diagnostics.
  183. ///
  184. /// This routine diagnoses various problems with referencing
  185. /// declarations that can occur when using a declaration. For example,
  186. /// it might warn if a deprecated or unavailable declaration is being
  187. /// used, or produce an error (and return true) if a C++0x deleted
  188. /// function is being used.
  189. ///
  190. /// \returns true if there was an error (this declaration cannot be
  191. /// referenced), false otherwise.
  192. ///
  193. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
  194. const ObjCInterfaceDecl *UnknownObjCClass) {
  195. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  196. // If there were any diagnostics suppressed by template argument deduction,
  197. // emit them now.
  198. llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
  199. Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  200. if (Pos != SuppressedDiagnostics.end()) {
  201. SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
  202. for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
  203. Diag(Suppressed[I].first, Suppressed[I].second);
  204. // Clear out the list of suppressed diagnostics, so that we don't emit
  205. // them again for this specialization. However, we don't obsolete this
  206. // entry from the table, because we want to avoid ever emitting these
  207. // diagnostics again.
  208. Suppressed.clear();
  209. }
  210. }
  211. // See if this is an auto-typed variable whose initializer we are parsing.
  212. if (ParsingInitForAutoVars.count(D)) {
  213. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  214. << D->getDeclName();
  215. return true;
  216. }
  217. // See if this is a deleted function.
  218. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  219. if (FD->isDeleted()) {
  220. Diag(Loc, diag::err_deleted_function_use);
  221. NoteDeletedFunction(FD);
  222. return true;
  223. }
  224. }
  225. DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
  226. // Warn if this is used but marked unused.
  227. if (D->hasAttr<UnusedAttr>())
  228. Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
  229. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  230. return false;
  231. }
  232. /// \brief Retrieve the message suffix that should be added to a
  233. /// diagnostic complaining about the given function being deleted or
  234. /// unavailable.
  235. std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
  236. // FIXME: C++0x implicitly-deleted special member functions could be
  237. // detected here so that we could improve diagnostics to say, e.g.,
  238. // "base class 'A' had a deleted copy constructor".
  239. if (FD->isDeleted())
  240. return std::string();
  241. std::string Message;
  242. if (FD->getAvailability(&Message))
  243. return ": " + Message;
  244. return std::string();
  245. }
  246. /// DiagnoseSentinelCalls - This routine checks whether a call or
  247. /// message-send is to a declaration with the sentinel attribute, and
  248. /// if so, it checks that the requirements of the sentinel are
  249. /// satisfied.
  250. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  251. Expr **args, unsigned numArgs) {
  252. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  253. if (!attr)
  254. return;
  255. // The number of formal parameters of the declaration.
  256. unsigned numFormalParams;
  257. // The kind of declaration. This is also an index into a %select in
  258. // the diagnostic.
  259. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  260. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  261. numFormalParams = MD->param_size();
  262. calleeType = CT_Method;
  263. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  264. numFormalParams = FD->param_size();
  265. calleeType = CT_Function;
  266. } else if (isa<VarDecl>(D)) {
  267. QualType type = cast<ValueDecl>(D)->getType();
  268. const FunctionType *fn = 0;
  269. if (const PointerType *ptr = type->getAs<PointerType>()) {
  270. fn = ptr->getPointeeType()->getAs<FunctionType>();
  271. if (!fn) return;
  272. calleeType = CT_Function;
  273. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  274. fn = ptr->getPointeeType()->castAs<FunctionType>();
  275. calleeType = CT_Block;
  276. } else {
  277. return;
  278. }
  279. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  280. numFormalParams = proto->getNumArgs();
  281. } else {
  282. numFormalParams = 0;
  283. }
  284. } else {
  285. return;
  286. }
  287. // "nullPos" is the number of formal parameters at the end which
  288. // effectively count as part of the variadic arguments. This is
  289. // useful if you would prefer to not have *any* formal parameters,
  290. // but the language forces you to have at least one.
  291. unsigned nullPos = attr->getNullPos();
  292. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  293. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  294. // The number of arguments which should follow the sentinel.
  295. unsigned numArgsAfterSentinel = attr->getSentinel();
  296. // If there aren't enough arguments for all the formal parameters,
  297. // the sentinel, and the args after the sentinel, complain.
  298. if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
  299. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  300. Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
  301. return;
  302. }
  303. // Otherwise, find the sentinel expression.
  304. Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
  305. if (!sentinelExpr) return;
  306. if (sentinelExpr->isValueDependent()) return;
  307. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  308. // Pick a reasonable string to insert. Optimistically use 'nil' or
  309. // 'NULL' if those are actually defined in the context. Only use
  310. // 'nil' for ObjC methods, where it's much more likely that the
  311. // variadic arguments form a list of object pointers.
  312. SourceLocation MissingNilLoc
  313. = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
  314. std::string NullValue;
  315. if (calleeType == CT_Method &&
  316. PP.getIdentifierInfo("nil")->hasMacroDefinition())
  317. NullValue = "nil";
  318. else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
  319. NullValue = "NULL";
  320. else
  321. NullValue = "(void*) 0";
  322. if (MissingNilLoc.isInvalid())
  323. Diag(Loc, diag::warn_missing_sentinel) << calleeType;
  324. else
  325. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  326. << calleeType
  327. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  328. Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
  329. }
  330. SourceRange Sema::getExprRange(Expr *E) const {
  331. return E ? E->getSourceRange() : SourceRange();
  332. }
  333. //===----------------------------------------------------------------------===//
  334. // Standard Promotions and Conversions
  335. //===----------------------------------------------------------------------===//
  336. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  337. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
  338. // Handle any placeholder expressions which made it here.
  339. if (E->getType()->isPlaceholderType()) {
  340. ExprResult result = CheckPlaceholderExpr(E);
  341. if (result.isInvalid()) return ExprError();
  342. E = result.take();
  343. }
  344. QualType Ty = E->getType();
  345. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  346. if (Ty->isFunctionType())
  347. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  348. CK_FunctionToPointerDecay).take();
  349. else if (Ty->isArrayType()) {
  350. // In C90 mode, arrays only promote to pointers if the array expression is
  351. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  352. // type 'array of type' is converted to an expression that has type 'pointer
  353. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  354. // that has type 'array of type' ...". The relevant change is "an lvalue"
  355. // (C90) to "an expression" (C99).
  356. //
  357. // C++ 4.2p1:
  358. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  359. // T" can be converted to an rvalue of type "pointer to T".
  360. //
  361. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
  362. E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  363. CK_ArrayToPointerDecay).take();
  364. }
  365. return Owned(E);
  366. }
  367. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  368. // Check to see if we are dereferencing a null pointer. If so,
  369. // and if not volatile-qualified, this is undefined behavior that the
  370. // optimizer will delete, so warn about it. People sometimes try to use this
  371. // to get a deterministic trap and are surprised by clang's behavior. This
  372. // only handles the pattern "*null", which is a very syntactic check.
  373. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  374. if (UO->getOpcode() == UO_Deref &&
  375. UO->getSubExpr()->IgnoreParenCasts()->
  376. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  377. !UO->getType().isVolatileQualified()) {
  378. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  379. S.PDiag(diag::warn_indirection_through_null)
  380. << UO->getSubExpr()->getSourceRange());
  381. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  382. S.PDiag(diag::note_indirection_through_null));
  383. }
  384. }
  385. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  386. // Handle any placeholder expressions which made it here.
  387. if (E->getType()->isPlaceholderType()) {
  388. ExprResult result = CheckPlaceholderExpr(E);
  389. if (result.isInvalid()) return ExprError();
  390. E = result.take();
  391. }
  392. // C++ [conv.lval]p1:
  393. // A glvalue of a non-function, non-array type T can be
  394. // converted to a prvalue.
  395. if (!E->isGLValue()) return Owned(E);
  396. QualType T = E->getType();
  397. assert(!T.isNull() && "r-value conversion on typeless expression?");
  398. // We don't want to throw lvalue-to-rvalue casts on top of
  399. // expressions of certain types in C++.
  400. if (getLangOpts().CPlusPlus &&
  401. (E->getType() == Context.OverloadTy ||
  402. T->isDependentType() ||
  403. T->isRecordType()))
  404. return Owned(E);
  405. // The C standard is actually really unclear on this point, and
  406. // DR106 tells us what the result should be but not why. It's
  407. // generally best to say that void types just doesn't undergo
  408. // lvalue-to-rvalue at all. Note that expressions of unqualified
  409. // 'void' type are never l-values, but qualified void can be.
  410. if (T->isVoidType())
  411. return Owned(E);
  412. CheckForNullPointerDereference(*this, E);
  413. // C++ [conv.lval]p1:
  414. // [...] If T is a non-class type, the type of the prvalue is the
  415. // cv-unqualified version of T. Otherwise, the type of the
  416. // rvalue is T.
  417. //
  418. // C99 6.3.2.1p2:
  419. // If the lvalue has qualified type, the value has the unqualified
  420. // version of the type of the lvalue; otherwise, the value has the
  421. // type of the lvalue.
  422. if (T.hasQualifiers())
  423. T = T.getUnqualifiedType();
  424. UpdateMarkingForLValueToRValue(E);
  425. ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
  426. E, 0, VK_RValue));
  427. // C11 6.3.2.1p2:
  428. // ... if the lvalue has atomic type, the value has the non-atomic version
  429. // of the type of the lvalue ...
  430. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  431. T = Atomic->getValueType().getUnqualifiedType();
  432. Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
  433. Res.get(), 0, VK_RValue));
  434. }
  435. return Res;
  436. }
  437. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
  438. ExprResult Res = DefaultFunctionArrayConversion(E);
  439. if (Res.isInvalid())
  440. return ExprError();
  441. Res = DefaultLvalueConversion(Res.take());
  442. if (Res.isInvalid())
  443. return ExprError();
  444. return Res;
  445. }
  446. /// UsualUnaryConversions - Performs various conversions that are common to most
  447. /// operators (C99 6.3). The conversions of array and function types are
  448. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  449. /// apply if the array is an argument to the sizeof or address (&) operators.
  450. /// In these instances, this routine should *not* be called.
  451. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  452. // First, convert to an r-value.
  453. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  454. if (Res.isInvalid())
  455. return Owned(E);
  456. E = Res.take();
  457. QualType Ty = E->getType();
  458. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  459. // Half FP is a bit different: it's a storage-only type, meaning that any
  460. // "use" of it should be promoted to float.
  461. if (Ty->isHalfType())
  462. return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
  463. // Try to perform integral promotions if the object has a theoretically
  464. // promotable type.
  465. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  466. // C99 6.3.1.1p2:
  467. //
  468. // The following may be used in an expression wherever an int or
  469. // unsigned int may be used:
  470. // - an object or expression with an integer type whose integer
  471. // conversion rank is less than or equal to the rank of int
  472. // and unsigned int.
  473. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  474. //
  475. // If an int can represent all values of the original type, the
  476. // value is converted to an int; otherwise, it is converted to an
  477. // unsigned int. These are called the integer promotions. All
  478. // other types are unchanged by the integer promotions.
  479. QualType PTy = Context.isPromotableBitField(E);
  480. if (!PTy.isNull()) {
  481. E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
  482. return Owned(E);
  483. }
  484. if (Ty->isPromotableIntegerType()) {
  485. QualType PT = Context.getPromotedIntegerType(Ty);
  486. E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
  487. return Owned(E);
  488. }
  489. }
  490. return Owned(E);
  491. }
  492. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  493. /// do not have a prototype. Arguments that have type float are promoted to
  494. /// double. All other argument types are converted by UsualUnaryConversions().
  495. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  496. QualType Ty = E->getType();
  497. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  498. ExprResult Res = UsualUnaryConversions(E);
  499. if (Res.isInvalid())
  500. return Owned(E);
  501. E = Res.take();
  502. // If this is a 'float' (CVR qualified or typedef) promote to double.
  503. if (Ty->isSpecificBuiltinType(BuiltinType::Float))
  504. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
  505. // C++ performs lvalue-to-rvalue conversion as a default argument
  506. // promotion, even on class types, but note:
  507. // C++11 [conv.lval]p2:
  508. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  509. // operand or a subexpression thereof the value contained in the
  510. // referenced object is not accessed. Otherwise, if the glvalue
  511. // has a class type, the conversion copy-initializes a temporary
  512. // of type T from the glvalue and the result of the conversion
  513. // is a prvalue for the temporary.
  514. // FIXME: add some way to gate this entire thing for correctness in
  515. // potentially potentially evaluated contexts.
  516. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  517. ExprResult Temp = PerformCopyInitialization(
  518. InitializedEntity::InitializeTemporary(E->getType()),
  519. E->getExprLoc(),
  520. Owned(E));
  521. if (Temp.isInvalid())
  522. return ExprError();
  523. E = Temp.get();
  524. }
  525. return Owned(E);
  526. }
  527. /// Determine the degree of POD-ness for an expression.
  528. /// Incomplete types are considered POD, since this check can be performed
  529. /// when we're in an unevaluated context.
  530. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  531. if (Ty->isIncompleteType()) {
  532. if (Ty->isObjCObjectType())
  533. return VAK_Invalid;
  534. return VAK_Valid;
  535. }
  536. if (Ty.isCXX98PODType(Context))
  537. return VAK_Valid;
  538. // C++0x [expr.call]p7:
  539. // Passing a potentially-evaluated argument of class type (Clause 9)
  540. // having a non-trivial copy constructor, a non-trivial move constructor,
  541. // or a non-trivial destructor, with no corresponding parameter,
  542. // is conditionally-supported with implementation-defined semantics.
  543. if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
  544. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  545. if (Record->hasTrivialCopyConstructor() &&
  546. Record->hasTrivialMoveConstructor() &&
  547. Record->hasTrivialDestructor())
  548. return VAK_ValidInCXX11;
  549. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  550. return VAK_Valid;
  551. return VAK_Invalid;
  552. }
  553. bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
  554. // Don't allow one to pass an Objective-C interface to a vararg.
  555. const QualType & Ty = E->getType();
  556. // Complain about passing non-POD types through varargs.
  557. switch (isValidVarArgType(Ty)) {
  558. case VAK_Valid:
  559. break;
  560. case VAK_ValidInCXX11:
  561. DiagRuntimeBehavior(E->getLocStart(), 0,
  562. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
  563. << E->getType() << CT);
  564. break;
  565. case VAK_Invalid: {
  566. if (Ty->isObjCObjectType())
  567. return DiagRuntimeBehavior(E->getLocStart(), 0,
  568. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  569. << Ty << CT);
  570. return DiagRuntimeBehavior(E->getLocStart(), 0,
  571. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  572. << getLangOpts().CPlusPlus0x << Ty << CT);
  573. }
  574. }
  575. // c++ rules are enforced elsewhere.
  576. return false;
  577. }
  578. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  579. /// will create a trap if the resulting type is not a POD type.
  580. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  581. FunctionDecl *FDecl) {
  582. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  583. // Strip the unbridged-cast placeholder expression off, if applicable.
  584. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  585. (CT == VariadicMethod ||
  586. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  587. E = stripARCUnbridgedCast(E);
  588. // Otherwise, do normal placeholder checking.
  589. } else {
  590. ExprResult ExprRes = CheckPlaceholderExpr(E);
  591. if (ExprRes.isInvalid())
  592. return ExprError();
  593. E = ExprRes.take();
  594. }
  595. }
  596. ExprResult ExprRes = DefaultArgumentPromotion(E);
  597. if (ExprRes.isInvalid())
  598. return ExprError();
  599. E = ExprRes.take();
  600. // Diagnostics regarding non-POD argument types are
  601. // emitted along with format string checking in Sema::CheckFunctionCall().
  602. if (isValidVarArgType(E->getType()) == VAK_Invalid) {
  603. // Turn this into a trap.
  604. CXXScopeSpec SS;
  605. SourceLocation TemplateKWLoc;
  606. UnqualifiedId Name;
  607. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  608. E->getLocStart());
  609. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
  610. Name, true, false);
  611. if (TrapFn.isInvalid())
  612. return ExprError();
  613. ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
  614. E->getLocStart(), MultiExprArg(),
  615. E->getLocEnd());
  616. if (Call.isInvalid())
  617. return ExprError();
  618. ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
  619. Call.get(), E);
  620. if (Comma.isInvalid())
  621. return ExprError();
  622. return Comma.get();
  623. }
  624. if (!getLangOpts().CPlusPlus &&
  625. RequireCompleteType(E->getExprLoc(), E->getType(),
  626. diag::err_call_incomplete_argument))
  627. return ExprError();
  628. return Owned(E);
  629. }
  630. /// \brief Converts an integer to complex float type. Helper function of
  631. /// UsualArithmeticConversions()
  632. ///
  633. /// \return false if the integer expression is an integer type and is
  634. /// successfully converted to the complex type.
  635. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  636. ExprResult &ComplexExpr,
  637. QualType IntTy,
  638. QualType ComplexTy,
  639. bool SkipCast) {
  640. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  641. if (SkipCast) return false;
  642. if (IntTy->isIntegerType()) {
  643. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  644. IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
  645. IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
  646. CK_FloatingRealToComplex);
  647. } else {
  648. assert(IntTy->isComplexIntegerType());
  649. IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
  650. CK_IntegralComplexToFloatingComplex);
  651. }
  652. return false;
  653. }
  654. /// \brief Takes two complex float types and converts them to the same type.
  655. /// Helper function of UsualArithmeticConversions()
  656. static QualType
  657. handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
  658. ExprResult &RHS, QualType LHSType,
  659. QualType RHSType,
  660. bool IsCompAssign) {
  661. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  662. if (order < 0) {
  663. // _Complex float -> _Complex double
  664. if (!IsCompAssign)
  665. LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
  666. return RHSType;
  667. }
  668. if (order > 0)
  669. // _Complex float -> _Complex double
  670. RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
  671. return LHSType;
  672. }
  673. /// \brief Converts otherExpr to complex float and promotes complexExpr if
  674. /// necessary. Helper function of UsualArithmeticConversions()
  675. static QualType handleOtherComplexFloatConversion(Sema &S,
  676. ExprResult &ComplexExpr,
  677. ExprResult &OtherExpr,
  678. QualType ComplexTy,
  679. QualType OtherTy,
  680. bool ConvertComplexExpr,
  681. bool ConvertOtherExpr) {
  682. int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
  683. // If just the complexExpr is complex, the otherExpr needs to be converted,
  684. // and the complexExpr might need to be promoted.
  685. if (order > 0) { // complexExpr is wider
  686. // float -> _Complex double
  687. if (ConvertOtherExpr) {
  688. QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
  689. OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
  690. OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
  691. CK_FloatingRealToComplex);
  692. }
  693. return ComplexTy;
  694. }
  695. // otherTy is at least as wide. Find its corresponding complex type.
  696. QualType result = (order == 0 ? ComplexTy :
  697. S.Context.getComplexType(OtherTy));
  698. // double -> _Complex double
  699. if (ConvertOtherExpr)
  700. OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
  701. CK_FloatingRealToComplex);
  702. // _Complex float -> _Complex double
  703. if (ConvertComplexExpr && order < 0)
  704. ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
  705. CK_FloatingComplexCast);
  706. return result;
  707. }
  708. /// \brief Handle arithmetic conversion with complex types. Helper function of
  709. /// UsualArithmeticConversions()
  710. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  711. ExprResult &RHS, QualType LHSType,
  712. QualType RHSType,
  713. bool IsCompAssign) {
  714. // if we have an integer operand, the result is the complex type.
  715. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  716. /*skipCast*/false))
  717. return LHSType;
  718. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  719. /*skipCast*/IsCompAssign))
  720. return RHSType;
  721. // This handles complex/complex, complex/float, or float/complex.
  722. // When both operands are complex, the shorter operand is converted to the
  723. // type of the longer, and that is the type of the result. This corresponds
  724. // to what is done when combining two real floating-point operands.
  725. // The fun begins when size promotion occur across type domains.
  726. // From H&S 6.3.4: When one operand is complex and the other is a real
  727. // floating-point type, the less precise type is converted, within it's
  728. // real or complex domain, to the precision of the other type. For example,
  729. // when combining a "long double" with a "double _Complex", the
  730. // "double _Complex" is promoted to "long double _Complex".
  731. bool LHSComplexFloat = LHSType->isComplexType();
  732. bool RHSComplexFloat = RHSType->isComplexType();
  733. // If both are complex, just cast to the more precise type.
  734. if (LHSComplexFloat && RHSComplexFloat)
  735. return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
  736. LHSType, RHSType,
  737. IsCompAssign);
  738. // If only one operand is complex, promote it if necessary and convert the
  739. // other operand to complex.
  740. if (LHSComplexFloat)
  741. return handleOtherComplexFloatConversion(
  742. S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
  743. /*convertOtherExpr*/ true);
  744. assert(RHSComplexFloat);
  745. return handleOtherComplexFloatConversion(
  746. S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
  747. /*convertOtherExpr*/ !IsCompAssign);
  748. }
  749. /// \brief Hande arithmetic conversion from integer to float. Helper function
  750. /// of UsualArithmeticConversions()
  751. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  752. ExprResult &IntExpr,
  753. QualType FloatTy, QualType IntTy,
  754. bool ConvertFloat, bool ConvertInt) {
  755. if (IntTy->isIntegerType()) {
  756. if (ConvertInt)
  757. // Convert intExpr to the lhs floating point type.
  758. IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
  759. CK_IntegralToFloating);
  760. return FloatTy;
  761. }
  762. // Convert both sides to the appropriate complex float.
  763. assert(IntTy->isComplexIntegerType());
  764. QualType result = S.Context.getComplexType(FloatTy);
  765. // _Complex int -> _Complex float
  766. if (ConvertInt)
  767. IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
  768. CK_IntegralComplexToFloatingComplex);
  769. // float -> _Complex float
  770. if (ConvertFloat)
  771. FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
  772. CK_FloatingRealToComplex);
  773. return result;
  774. }
  775. /// \brief Handle arithmethic conversion with floating point types. Helper
  776. /// function of UsualArithmeticConversions()
  777. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  778. ExprResult &RHS, QualType LHSType,
  779. QualType RHSType, bool IsCompAssign) {
  780. bool LHSFloat = LHSType->isRealFloatingType();
  781. bool RHSFloat = RHSType->isRealFloatingType();
  782. // If we have two real floating types, convert the smaller operand
  783. // to the bigger result.
  784. if (LHSFloat && RHSFloat) {
  785. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  786. if (order > 0) {
  787. RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
  788. return LHSType;
  789. }
  790. assert(order < 0 && "illegal float comparison");
  791. if (!IsCompAssign)
  792. LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
  793. return RHSType;
  794. }
  795. if (LHSFloat)
  796. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  797. /*convertFloat=*/!IsCompAssign,
  798. /*convertInt=*/ true);
  799. assert(RHSFloat);
  800. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  801. /*convertInt=*/ true,
  802. /*convertFloat=*/!IsCompAssign);
  803. }
  804. /// \brief Handle conversions with GCC complex int extension. Helper function
  805. /// of UsualArithmeticConversions()
  806. // FIXME: if the operands are (int, _Complex long), we currently
  807. // don't promote the complex. Also, signedness?
  808. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  809. ExprResult &RHS, QualType LHSType,
  810. QualType RHSType,
  811. bool IsCompAssign) {
  812. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  813. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  814. if (LHSComplexInt && RHSComplexInt) {
  815. int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
  816. RHSComplexInt->getElementType());
  817. assert(order && "inequal types with equal element ordering");
  818. if (order > 0) {
  819. // _Complex int -> _Complex long
  820. RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
  821. return LHSType;
  822. }
  823. if (!IsCompAssign)
  824. LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
  825. return RHSType;
  826. }
  827. if (LHSComplexInt) {
  828. // int -> _Complex int
  829. // FIXME: This needs to take integer ranks into account
  830. RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
  831. CK_IntegralCast);
  832. RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
  833. return LHSType;
  834. }
  835. assert(RHSComplexInt);
  836. // int -> _Complex int
  837. // FIXME: This needs to take integer ranks into account
  838. if (!IsCompAssign) {
  839. LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
  840. CK_IntegralCast);
  841. LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
  842. }
  843. return RHSType;
  844. }
  845. /// \brief Handle integer arithmetic conversions. Helper function of
  846. /// UsualArithmeticConversions()
  847. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  848. ExprResult &RHS, QualType LHSType,
  849. QualType RHSType, bool IsCompAssign) {
  850. // The rules for this case are in C99 6.3.1.8
  851. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  852. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  853. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  854. if (LHSSigned == RHSSigned) {
  855. // Same signedness; use the higher-ranked type
  856. if (order >= 0) {
  857. RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
  858. return LHSType;
  859. } else if (!IsCompAssign)
  860. LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
  861. return RHSType;
  862. } else if (order != (LHSSigned ? 1 : -1)) {
  863. // The unsigned type has greater than or equal rank to the
  864. // signed type, so use the unsigned type
  865. if (RHSSigned) {
  866. RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
  867. return LHSType;
  868. } else if (!IsCompAssign)
  869. LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
  870. return RHSType;
  871. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  872. // The two types are different widths; if we are here, that
  873. // means the signed type is larger than the unsigned type, so
  874. // use the signed type.
  875. if (LHSSigned) {
  876. RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
  877. return LHSType;
  878. } else if (!IsCompAssign)
  879. LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
  880. return RHSType;
  881. } else {
  882. // The signed type is higher-ranked than the unsigned type,
  883. // but isn't actually any bigger (like unsigned int and long
  884. // on most 32-bit systems). Use the unsigned type corresponding
  885. // to the signed type.
  886. QualType result =
  887. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  888. RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
  889. if (!IsCompAssign)
  890. LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
  891. return result;
  892. }
  893. }
  894. /// UsualArithmeticConversions - Performs various conversions that are common to
  895. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  896. /// routine returns the first non-arithmetic type found. The client is
  897. /// responsible for emitting appropriate error diagnostics.
  898. /// FIXME: verify the conversion rules for "complex int" are consistent with
  899. /// GCC.
  900. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  901. bool IsCompAssign) {
  902. if (!IsCompAssign) {
  903. LHS = UsualUnaryConversions(LHS.take());
  904. if (LHS.isInvalid())
  905. return QualType();
  906. }
  907. RHS = UsualUnaryConversions(RHS.take());
  908. if (RHS.isInvalid())
  909. return QualType();
  910. // For conversion purposes, we ignore any qualifiers.
  911. // For example, "const float" and "float" are equivalent.
  912. QualType LHSType =
  913. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  914. QualType RHSType =
  915. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  916. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  917. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  918. LHSType = AtomicLHS->getValueType();
  919. // If both types are identical, no conversion is needed.
  920. if (LHSType == RHSType)
  921. return LHSType;
  922. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  923. // The caller can deal with this (e.g. pointer + int).
  924. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  925. return QualType();
  926. // Apply unary and bitfield promotions to the LHS's type.
  927. QualType LHSUnpromotedType = LHSType;
  928. if (LHSType->isPromotableIntegerType())
  929. LHSType = Context.getPromotedIntegerType(LHSType);
  930. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  931. if (!LHSBitfieldPromoteTy.isNull())
  932. LHSType = LHSBitfieldPromoteTy;
  933. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  934. LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
  935. // If both types are identical, no conversion is needed.
  936. if (LHSType == RHSType)
  937. return LHSType;
  938. // At this point, we have two different arithmetic types.
  939. // Handle complex types first (C99 6.3.1.8p1).
  940. if (LHSType->isComplexType() || RHSType->isComplexType())
  941. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  942. IsCompAssign);
  943. // Now handle "real" floating types (i.e. float, double, long double).
  944. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  945. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  946. IsCompAssign);
  947. // Handle GCC complex int extension.
  948. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  949. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  950. IsCompAssign);
  951. // Finally, we have two differing integer types.
  952. return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
  953. IsCompAssign);
  954. }
  955. //===----------------------------------------------------------------------===//
  956. // Semantic Analysis for various Expression Types
  957. //===----------------------------------------------------------------------===//
  958. ExprResult
  959. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  960. SourceLocation DefaultLoc,
  961. SourceLocation RParenLoc,
  962. Expr *ControllingExpr,
  963. MultiTypeArg ArgTypes,
  964. MultiExprArg ArgExprs) {
  965. unsigned NumAssocs = ArgTypes.size();
  966. assert(NumAssocs == ArgExprs.size());
  967. ParsedType *ParsedTypes = ArgTypes.get();
  968. Expr **Exprs = ArgExprs.get();
  969. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  970. for (unsigned i = 0; i < NumAssocs; ++i) {
  971. if (ParsedTypes[i])
  972. (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
  973. else
  974. Types[i] = 0;
  975. }
  976. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  977. ControllingExpr, Types, Exprs,
  978. NumAssocs);
  979. delete [] Types;
  980. return ER;
  981. }
  982. ExprResult
  983. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  984. SourceLocation DefaultLoc,
  985. SourceLocation RParenLoc,
  986. Expr *ControllingExpr,
  987. TypeSourceInfo **Types,
  988. Expr **Exprs,
  989. unsigned NumAssocs) {
  990. bool TypeErrorFound = false,
  991. IsResultDependent = ControllingExpr->isTypeDependent(),
  992. ContainsUnexpandedParameterPack
  993. = ControllingExpr->containsUnexpandedParameterPack();
  994. for (unsigned i = 0; i < NumAssocs; ++i) {
  995. if (Exprs[i]->containsUnexpandedParameterPack())
  996. ContainsUnexpandedParameterPack = true;
  997. if (Types[i]) {
  998. if (Types[i]->getType()->containsUnexpandedParameterPack())
  999. ContainsUnexpandedParameterPack = true;
  1000. if (Types[i]->getType()->isDependentType()) {
  1001. IsResultDependent = true;
  1002. } else {
  1003. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1004. // complete object type other than a variably modified type."
  1005. unsigned D = 0;
  1006. if (Types[i]->getType()->isIncompleteType())
  1007. D = diag::err_assoc_type_incomplete;
  1008. else if (!Types[i]->getType()->isObjectType())
  1009. D = diag::err_assoc_type_nonobject;
  1010. else if (Types[i]->getType()->isVariablyModifiedType())
  1011. D = diag::err_assoc_type_variably_modified;
  1012. if (D != 0) {
  1013. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1014. << Types[i]->getTypeLoc().getSourceRange()
  1015. << Types[i]->getType();
  1016. TypeErrorFound = true;
  1017. }
  1018. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1019. // selection shall specify compatible types."
  1020. for (unsigned j = i+1; j < NumAssocs; ++j)
  1021. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1022. Context.typesAreCompatible(Types[i]->getType(),
  1023. Types[j]->getType())) {
  1024. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1025. diag::err_assoc_compatible_types)
  1026. << Types[j]->getTypeLoc().getSourceRange()
  1027. << Types[j]->getType()
  1028. << Types[i]->getType();
  1029. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1030. diag::note_compat_assoc)
  1031. << Types[i]->getTypeLoc().getSourceRange()
  1032. << Types[i]->getType();
  1033. TypeErrorFound = true;
  1034. }
  1035. }
  1036. }
  1037. }
  1038. if (TypeErrorFound)
  1039. return ExprError();
  1040. // If we determined that the generic selection is result-dependent, don't
  1041. // try to compute the result expression.
  1042. if (IsResultDependent)
  1043. return Owned(new (Context) GenericSelectionExpr(
  1044. Context, KeyLoc, ControllingExpr,
  1045. Types, Exprs, NumAssocs, DefaultLoc,
  1046. RParenLoc, ContainsUnexpandedParameterPack));
  1047. SmallVector<unsigned, 1> CompatIndices;
  1048. unsigned DefaultIndex = -1U;
  1049. for (unsigned i = 0; i < NumAssocs; ++i) {
  1050. if (!Types[i])
  1051. DefaultIndex = i;
  1052. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1053. Types[i]->getType()))
  1054. CompatIndices.push_back(i);
  1055. }
  1056. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1057. // type compatible with at most one of the types named in its generic
  1058. // association list."
  1059. if (CompatIndices.size() > 1) {
  1060. // We strip parens here because the controlling expression is typically
  1061. // parenthesized in macro definitions.
  1062. ControllingExpr = ControllingExpr->IgnoreParens();
  1063. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
  1064. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1065. << (unsigned) CompatIndices.size();
  1066. for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
  1067. E = CompatIndices.end(); I != E; ++I) {
  1068. Diag(Types[*I]->getTypeLoc().getBeginLoc(),
  1069. diag::note_compat_assoc)
  1070. << Types[*I]->getTypeLoc().getSourceRange()
  1071. << Types[*I]->getType();
  1072. }
  1073. return ExprError();
  1074. }
  1075. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1076. // its controlling expression shall have type compatible with exactly one of
  1077. // the types named in its generic association list."
  1078. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1079. // We strip parens here because the controlling expression is typically
  1080. // parenthesized in macro definitions.
  1081. ControllingExpr = ControllingExpr->IgnoreParens();
  1082. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
  1083. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1084. return ExprError();
  1085. }
  1086. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1087. // type name that is compatible with the type of the controlling expression,
  1088. // then the result expression of the generic selection is the expression
  1089. // in that generic association. Otherwise, the result expression of the
  1090. // generic selection is the expression in the default generic association."
  1091. unsigned ResultIndex =
  1092. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1093. return Owned(new (Context) GenericSelectionExpr(
  1094. Context, KeyLoc, ControllingExpr,
  1095. Types, Exprs, NumAssocs, DefaultLoc,
  1096. RParenLoc, ContainsUnexpandedParameterPack,
  1097. ResultIndex));
  1098. }
  1099. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1100. /// location of the token and the offset of the ud-suffix within it.
  1101. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1102. unsigned Offset) {
  1103. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1104. S.getLangOpts());
  1105. }
  1106. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1107. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1108. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1109. IdentifierInfo *UDSuffix,
  1110. SourceLocation UDSuffixLoc,
  1111. ArrayRef<Expr*> Args,
  1112. SourceLocation LitEndLoc) {
  1113. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1114. QualType ArgTy[2];
  1115. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1116. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1117. if (ArgTy[ArgIdx]->isArrayType())
  1118. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1119. }
  1120. DeclarationName OpName =
  1121. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1122. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1123. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1124. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1125. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1126. /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
  1127. return ExprError();
  1128. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1129. }
  1130. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1131. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1132. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1133. /// multiple tokens. However, the common case is that StringToks points to one
  1134. /// string.
  1135. ///
  1136. ExprResult
  1137. Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
  1138. Scope *UDLScope) {
  1139. assert(NumStringToks && "Must have at least one string!");
  1140. StringLiteralParser Literal(StringToks, NumStringToks, PP);
  1141. if (Literal.hadError)
  1142. return ExprError();
  1143. SmallVector<SourceLocation, 4> StringTokLocs;
  1144. for (unsigned i = 0; i != NumStringToks; ++i)
  1145. StringTokLocs.push_back(StringToks[i].getLocation());
  1146. QualType StrTy = Context.CharTy;
  1147. if (Literal.isWide())
  1148. StrTy = Context.getWCharType();
  1149. else if (Literal.isUTF16())
  1150. StrTy = Context.Char16Ty;
  1151. else if (Literal.isUTF32())
  1152. StrTy = Context.Char32Ty;
  1153. else if (Literal.isPascal())
  1154. StrTy = Context.UnsignedCharTy;
  1155. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1156. if (Literal.isWide())
  1157. Kind = StringLiteral::Wide;
  1158. else if (Literal.isUTF8())
  1159. Kind = StringLiteral::UTF8;
  1160. else if (Literal.isUTF16())
  1161. Kind = StringLiteral::UTF16;
  1162. else if (Literal.isUTF32())
  1163. Kind = StringLiteral::UTF32;
  1164. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  1165. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  1166. StrTy.addConst();
  1167. // Get an array type for the string, according to C99 6.4.5. This includes
  1168. // the nul terminator character as well as the string length for pascal
  1169. // strings.
  1170. StrTy = Context.getConstantArrayType(StrTy,
  1171. llvm::APInt(32, Literal.GetNumStringChars()+1),
  1172. ArrayType::Normal, 0);
  1173. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1174. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1175. Kind, Literal.Pascal, StrTy,
  1176. &StringTokLocs[0],
  1177. StringTokLocs.size());
  1178. if (Literal.getUDSuffix().empty())
  1179. return Owned(Lit);
  1180. // We're building a user-defined literal.
  1181. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1182. SourceLocation UDSuffixLoc =
  1183. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1184. Literal.getUDSuffixOffset());
  1185. // Make sure we're allowed user-defined literals here.
  1186. if (!UDLScope)
  1187. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1188. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1189. // operator "" X (str, len)
  1190. QualType SizeType = Context.getSizeType();
  1191. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1192. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1193. StringTokLocs[0]);
  1194. Expr *Args[] = { Lit, LenArg };
  1195. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  1196. Args, StringTokLocs.back());
  1197. }
  1198. ExprResult
  1199. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1200. SourceLocation Loc,
  1201. const CXXScopeSpec *SS) {
  1202. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1203. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1204. }
  1205. /// BuildDeclRefExpr - Build an expression that references a
  1206. /// declaration that does not require a closure capture.
  1207. ExprResult
  1208. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1209. const DeclarationNameInfo &NameInfo,
  1210. const CXXScopeSpec *SS) {
  1211. if (getLangOpts().CUDA)
  1212. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  1213. if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
  1214. CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
  1215. CalleeTarget = IdentifyCUDATarget(Callee);
  1216. if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
  1217. Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
  1218. << CalleeTarget << D->getIdentifier() << CallerTarget;
  1219. Diag(D->getLocation(), diag::note_previous_decl)
  1220. << D->getIdentifier();
  1221. return ExprError();
  1222. }
  1223. }
  1224. bool refersToEnclosingScope =
  1225. (CurContext != D->getDeclContext() &&
  1226. D->getDeclContext()->isFunctionOrMethod());
  1227. DeclRefExpr *E = DeclRefExpr::Create(Context,
  1228. SS ? SS->getWithLocInContext(Context)
  1229. : NestedNameSpecifierLoc(),
  1230. SourceLocation(),
  1231. D, refersToEnclosingScope,
  1232. NameInfo, Ty, VK);
  1233. MarkDeclRefReferenced(E);
  1234. // Just in case we're building an illegal pointer-to-member.
  1235. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1236. if (FD && FD->isBitField())
  1237. E->setObjectKind(OK_BitField);
  1238. return Owned(E);
  1239. }
  1240. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1241. /// possibly a list of template arguments.
  1242. ///
  1243. /// If this produces template arguments, it is permitted to call
  1244. /// DecomposeTemplateName.
  1245. ///
  1246. /// This actually loses a lot of source location information for
  1247. /// non-standard name kinds; we should consider preserving that in
  1248. /// some way.
  1249. void
  1250. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1251. TemplateArgumentListInfo &Buffer,
  1252. DeclarationNameInfo &NameInfo,
  1253. const TemplateArgumentListInfo *&TemplateArgs) {
  1254. if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
  1255. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1256. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1257. ASTTemplateArgsPtr TemplateArgsPtr(*this,
  1258. Id.TemplateId->getTemplateArgs(),
  1259. Id.TemplateId->NumArgs);
  1260. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1261. TemplateName TName = Id.TemplateId->Template.get();
  1262. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1263. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1264. TemplateArgs = &Buffer;
  1265. } else {
  1266. NameInfo = GetNameFromUnqualifiedId(Id);
  1267. TemplateArgs = 0;
  1268. }
  1269. }
  1270. /// Diagnose an empty lookup.
  1271. ///
  1272. /// \return false if new lookup candidates were found
  1273. bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1274. CorrectionCandidateCallback &CCC,
  1275. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1276. llvm::ArrayRef<Expr *> Args) {
  1277. DeclarationName Name = R.getLookupName();
  1278. unsigned diagnostic = diag::err_undeclared_var_use;
  1279. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1280. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1281. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1282. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1283. diagnostic = diag::err_undeclared_use;
  1284. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1285. }
  1286. // If the original lookup was an unqualified lookup, fake an
  1287. // unqualified lookup. This is useful when (for example) the
  1288. // original lookup would not have found something because it was a
  1289. // dependent name.
  1290. DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
  1291. ? CurContext : 0;
  1292. while (DC) {
  1293. if (isa<CXXRecordDecl>(DC)) {
  1294. LookupQualifiedName(R, DC);
  1295. if (!R.empty()) {
  1296. // Don't give errors about ambiguities in this lookup.
  1297. R.suppressDiagnostics();
  1298. // During a default argument instantiation the CurContext points
  1299. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1300. // function parameter list, hence add an explicit check.
  1301. bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
  1302. ActiveTemplateInstantiations.back().Kind ==
  1303. ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
  1304. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1305. bool isInstance = CurMethod &&
  1306. CurMethod->isInstance() &&
  1307. DC == CurMethod->getParent() && !isDefaultArgument;
  1308. // Give a code modification hint to insert 'this->'.
  1309. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1310. // Actually quite difficult!
  1311. if (getLangOpts().MicrosoftMode)
  1312. diagnostic = diag::warn_found_via_dependent_bases_lookup;
  1313. if (isInstance) {
  1314. Diag(R.getNameLoc(), diagnostic) << Name
  1315. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1316. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
  1317. CallsUndergoingInstantiation.back()->getCallee());
  1318. CXXMethodDecl *DepMethod;
  1319. if (CurMethod->getTemplatedKind() ==
  1320. FunctionDecl::TK_FunctionTemplateSpecialization)
  1321. DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
  1322. getInstantiatedFromMemberTemplate()->getTemplatedDecl());
  1323. else
  1324. DepMethod = cast<CXXMethodDecl>(
  1325. CurMethod->getInstantiatedFromMemberFunction());
  1326. assert(DepMethod && "No template pattern found");
  1327. QualType DepThisType = DepMethod->getThisType(Context);
  1328. CheckCXXThisCapture(R.getNameLoc());
  1329. CXXThisExpr *DepThis = new (Context) CXXThisExpr(
  1330. R.getNameLoc(), DepThisType, false);
  1331. TemplateArgumentListInfo TList;
  1332. if (ULE->hasExplicitTemplateArgs())
  1333. ULE->copyTemplateArgumentsInto(TList);
  1334. CXXScopeSpec SS;
  1335. SS.Adopt(ULE->getQualifierLoc());
  1336. CXXDependentScopeMemberExpr *DepExpr =
  1337. CXXDependentScopeMemberExpr::Create(
  1338. Context, DepThis, DepThisType, true, SourceLocation(),
  1339. SS.getWithLocInContext(Context),
  1340. ULE->getTemplateKeywordLoc(), 0,
  1341. R.getLookupNameInfo(),
  1342. ULE->hasExplicitTemplateArgs() ? &TList : 0);
  1343. CallsUndergoingInstantiation.back()->setCallee(DepExpr);
  1344. } else {
  1345. Diag(R.getNameLoc(), diagnostic) << Name;
  1346. }
  1347. // Do we really want to note all of these?
  1348. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  1349. Diag((*I)->getLocation(), diag::note_dependent_var_use);
  1350. // Return true if we are inside a default argument instantiation
  1351. // and the found name refers to an instance member function, otherwise
  1352. // the function calling DiagnoseEmptyLookup will try to create an
  1353. // implicit member call and this is wrong for default argument.
  1354. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1355. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1356. return true;
  1357. }
  1358. // Tell the callee to try to recover.
  1359. return false;
  1360. }
  1361. R.clear();
  1362. }
  1363. // In Microsoft mode, if we are performing lookup from within a friend
  1364. // function definition declared at class scope then we must set
  1365. // DC to the lexical parent to be able to search into the parent
  1366. // class.
  1367. if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
  1368. cast<FunctionDecl>(DC)->getFriendObjectKind() &&
  1369. DC->getLexicalParent()->isRecord())
  1370. DC = DC->getLexicalParent();
  1371. else
  1372. DC = DC->getParent();
  1373. }
  1374. // We didn't find anything, so try to correct for a typo.
  1375. TypoCorrection Corrected;
  1376. if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
  1377. S, &SS, CCC))) {
  1378. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1379. std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
  1380. R.setLookupName(Corrected.getCorrection());
  1381. if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
  1382. if (Corrected.isOverloaded()) {
  1383. OverloadCandidateSet OCS(R.getNameLoc());
  1384. OverloadCandidateSet::iterator Best;
  1385. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  1386. CDEnd = Corrected.end();
  1387. CD != CDEnd; ++CD) {
  1388. if (FunctionTemplateDecl *FTD =
  1389. dyn_cast<FunctionTemplateDecl>(*CD))
  1390. AddTemplateOverloadCandidate(
  1391. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1392. Args, OCS);
  1393. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  1394. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1395. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1396. Args, OCS);
  1397. }
  1398. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1399. case OR_Success:
  1400. ND = Best->Function;
  1401. break;
  1402. default:
  1403. break;
  1404. }
  1405. }
  1406. R.addDecl(ND);
  1407. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
  1408. if (SS.isEmpty())
  1409. Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
  1410. << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
  1411. else
  1412. Diag(R.getNameLoc(), diag::err_no_member_suggest)
  1413. << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
  1414. << SS.getRange()
  1415. << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
  1416. if (ND)
  1417. Diag(ND->getLocation(), diag::note_previous_decl)
  1418. << CorrectedQuotedStr;
  1419. // Tell the callee to try to recover.
  1420. return false;
  1421. }
  1422. if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
  1423. // FIXME: If we ended up with a typo for a type name or
  1424. // Objective-C class name, we're in trouble because the parser
  1425. // is in the wrong place to recover. Suggest the typo
  1426. // correction, but don't make it a fix-it since we're not going
  1427. // to recover well anyway.
  1428. if (SS.isEmpty())
  1429. Diag(R.getNameLoc(), diagnostic_suggest)
  1430. << Name << CorrectedQuotedStr;
  1431. else
  1432. Diag(R.getNameLoc(), diag::err_no_member_suggest)
  1433. << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
  1434. << SS.getRange();
  1435. // Don't try to recover; it won't work.
  1436. return true;
  1437. }
  1438. } else {
  1439. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1440. // because we aren't able to recover.
  1441. if (SS.isEmpty())
  1442. Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
  1443. else
  1444. Diag(R.getNameLoc(), diag::err_no_member_suggest)
  1445. << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
  1446. << SS.getRange();
  1447. return true;
  1448. }
  1449. }
  1450. R.clear();
  1451. // Emit a special diagnostic for failed member lookups.
  1452. // FIXME: computing the declaration context might fail here (?)
  1453. if (!SS.isEmpty()) {
  1454. Diag(R.getNameLoc(), diag::err_no_member)
  1455. << Name << computeDeclContext(SS, false)
  1456. << SS.getRange();
  1457. return true;
  1458. }
  1459. // Give up, we can't recover.
  1460. Diag(R.getNameLoc(), diagnostic) << Name;
  1461. return true;
  1462. }
  1463. ExprResult Sema::ActOnIdExpression(Scope *S,
  1464. CXXScopeSpec &SS,
  1465. SourceLocation TemplateKWLoc,
  1466. UnqualifiedId &Id,
  1467. bool HasTrailingLParen,
  1468. bool IsAddressOfOperand,
  1469. CorrectionCandidateCallback *CCC) {
  1470. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1471. "cannot be direct & operand and have a trailing lparen");
  1472. if (SS.isInvalid())
  1473. return ExprError();
  1474. TemplateArgumentListInfo TemplateArgsBuffer;
  1475. // Decompose the UnqualifiedId into the following data.
  1476. DeclarationNameInfo NameInfo;
  1477. const TemplateArgumentListInfo *TemplateArgs;
  1478. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1479. DeclarationName Name = NameInfo.getName();
  1480. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1481. SourceLocation NameLoc = NameInfo.getLoc();
  1482. // C++ [temp.dep.expr]p3:
  1483. // An id-expression is type-dependent if it contains:
  1484. // -- an identifier that was declared with a dependent type,
  1485. // (note: handled after lookup)
  1486. // -- a template-id that is dependent,
  1487. // (note: handled in BuildTemplateIdExpr)
  1488. // -- a conversion-function-id that specifies a dependent type,
  1489. // -- a nested-name-specifier that contains a class-name that
  1490. // names a dependent type.
  1491. // Determine whether this is a member of an unknown specialization;
  1492. // we need to handle these differently.
  1493. bool DependentID = false;
  1494. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1495. Name.getCXXNameType()->isDependentType()) {
  1496. DependentID = true;
  1497. } else if (SS.isSet()) {
  1498. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1499. if (RequireCompleteDeclContext(SS, DC))
  1500. return ExprError();
  1501. } else {
  1502. DependentID = true;
  1503. }
  1504. }
  1505. if (DependentID)
  1506. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1507. IsAddressOfOperand, TemplateArgs);
  1508. // Perform the required lookup.
  1509. LookupResult R(*this, NameInfo,
  1510. (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
  1511. ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
  1512. if (TemplateArgs) {
  1513. // Lookup the template name again to correctly establish the context in
  1514. // which it was found. This is really unfortunate as we already did the
  1515. // lookup to determine that it was a template name in the first place. If
  1516. // this becomes a performance hit, we can work harder to preserve those
  1517. // results until we get here but it's likely not worth it.
  1518. bool MemberOfUnknownSpecialization;
  1519. LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1520. MemberOfUnknownSpecialization);
  1521. if (MemberOfUnknownSpecialization ||
  1522. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1523. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1524. IsAddressOfOperand, TemplateArgs);
  1525. } else {
  1526. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1527. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1528. // If the result might be in a dependent base class, this is a dependent
  1529. // id-expression.
  1530. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1531. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1532. IsAddressOfOperand, TemplateArgs);
  1533. // If this reference is in an Objective-C method, then we need to do
  1534. // some special Objective-C lookup, too.
  1535. if (IvarLookupFollowUp) {
  1536. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1537. if (E.isInvalid())
  1538. return ExprError();
  1539. if (Expr *Ex = E.takeAs<Expr>())
  1540. return Owned(Ex);
  1541. }
  1542. }
  1543. if (R.isAmbiguous())
  1544. return ExprError();
  1545. // Determine whether this name might be a candidate for
  1546. // argument-dependent lookup.
  1547. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  1548. if (R.empty() && !ADL) {
  1549. // Otherwise, this could be an implicitly declared function reference (legal
  1550. // in C90, extension in C99, forbidden in C++).
  1551. if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  1552. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  1553. if (D) R.addDecl(D);
  1554. }
  1555. // If this name wasn't predeclared and if this is not a function
  1556. // call, diagnose the problem.
  1557. if (R.empty()) {
  1558. // In Microsoft mode, if we are inside a template class member function
  1559. // and we can't resolve an identifier then assume the identifier is type
  1560. // dependent. The goal is to postpone name lookup to instantiation time
  1561. // to be able to search into type dependent base classes.
  1562. if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
  1563. isa<CXXMethodDecl>(CurContext))
  1564. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1565. IsAddressOfOperand, TemplateArgs);
  1566. CorrectionCandidateCallback DefaultValidator;
  1567. if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
  1568. return ExprError();
  1569. assert(!R.empty() &&
  1570. "DiagnoseEmptyLookup returned false but added no results");
  1571. // If we found an Objective-C instance variable, let
  1572. // LookupInObjCMethod build the appropriate expression to
  1573. // reference the ivar.
  1574. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  1575. R.clear();
  1576. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  1577. // In a hopelessly buggy code, Objective-C instance variable
  1578. // lookup fails and no expression will be built to reference it.
  1579. if (!E.isInvalid() && !E.get())
  1580. return ExprError();
  1581. return E;
  1582. }
  1583. }
  1584. }
  1585. // This is guaranteed from this point on.
  1586. assert(!R.empty() || ADL);
  1587. // Check whether this might be a C++ implicit instance member access.
  1588. // C++ [class.mfct.non-static]p3:
  1589. // When an id-expression that is not part of a class member access
  1590. // syntax and not used to form a pointer to member is used in the
  1591. // body of a non-static member function of class X, if name lookup
  1592. // resolves the name in the id-expression to a non-static non-type
  1593. // member of some class C, the id-expression is transformed into a
  1594. // class member access expression using (*this) as the
  1595. // postfix-expression to the left of the . operator.
  1596. //
  1597. // But we don't actually need to do this for '&' operands if R
  1598. // resolved to a function or overloaded function set, because the
  1599. // expression is ill-formed if it actually works out to be a
  1600. // non-static member function:
  1601. //
  1602. // C++ [expr.ref]p4:
  1603. // Otherwise, if E1.E2 refers to a non-static member function. . .
  1604. // [t]he expression can be used only as the left-hand operand of a
  1605. // member function call.
  1606. //
  1607. // There are other safeguards against such uses, but it's important
  1608. // to get this right here so that we don't end up making a
  1609. // spuriously dependent expression if we're inside a dependent
  1610. // instance method.
  1611. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  1612. bool MightBeImplicitMember;
  1613. if (!IsAddressOfOperand)
  1614. MightBeImplicitMember = true;
  1615. else if (!SS.isEmpty())
  1616. MightBeImplicitMember = false;
  1617. else if (R.isOverloadedResult())
  1618. MightBeImplicitMember = false;
  1619. else if (R.isUnresolvableResult())
  1620. MightBeImplicitMember = true;
  1621. else
  1622. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  1623. isa<IndirectFieldDecl>(R.getFoundDecl());
  1624. if (MightBeImplicitMember)
  1625. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  1626. R, TemplateArgs);
  1627. }
  1628. if (TemplateArgs || TemplateKWLoc.isValid())
  1629. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  1630. return BuildDeclarationNameExpr(SS, R, ADL);
  1631. }
  1632. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  1633. /// declaration name, generally during template instantiation.
  1634. /// There's a large number of things which don't need to be done along
  1635. /// this path.
  1636. ExprResult
  1637. Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
  1638. const DeclarationNameInfo &NameInfo) {
  1639. DeclContext *DC;
  1640. if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
  1641. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  1642. NameInfo, /*TemplateArgs=*/0);
  1643. if (RequireCompleteDeclContext(SS, DC))
  1644. return ExprError();
  1645. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  1646. LookupQualifiedName(R, DC);
  1647. if (R.isAmbiguous())
  1648. return ExprError();
  1649. if (R.empty()) {
  1650. Diag(NameInfo.getLoc(), diag::err_no_member)
  1651. << NameInfo.getName() << DC << SS.getRange();
  1652. return ExprError();
  1653. }
  1654. return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
  1655. }
  1656. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  1657. /// detected that we're currently inside an ObjC method. Perform some
  1658. /// additional lookup.
  1659. ///
  1660. /// Ideally, most of this would be done by lookup, but there's
  1661. /// actually quite a lot of extra work involved.
  1662. ///
  1663. /// Returns a null sentinel to indicate trivial success.
  1664. ExprResult
  1665. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  1666. IdentifierInfo *II, bool AllowBuiltinCreation) {
  1667. SourceLocation Loc = Lookup.getNameLoc();
  1668. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  1669. // There are two cases to handle here. 1) scoped lookup could have failed,
  1670. // in which case we should look for an ivar. 2) scoped lookup could have
  1671. // found a decl, but that decl is outside the current instance method (i.e.
  1672. // a global variable). In these two cases, we do a lookup for an ivar with
  1673. // this name, if the lookup sucedes, we replace it our current decl.
  1674. // If we're in a class method, we don't normally want to look for
  1675. // ivars. But if we don't find anything else, and there's an
  1676. // ivar, that's an error.
  1677. bool IsClassMethod = CurMethod->isClassMethod();
  1678. bool LookForIvars;
  1679. if (Lookup.empty())
  1680. LookForIvars = true;
  1681. else if (IsClassMethod)
  1682. LookForIvars = false;
  1683. else
  1684. LookForIvars = (Lookup.isSingleResult() &&
  1685. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  1686. ObjCInterfaceDecl *IFace = 0;
  1687. if (LookForIvars) {
  1688. IFace = CurMethod->getClassInterface();
  1689. ObjCInterfaceDecl *ClassDeclared;
  1690. ObjCIvarDecl *IV = 0;
  1691. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  1692. // Diagnose using an ivar in a class method.
  1693. if (IsClassMethod)
  1694. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  1695. << IV->getDeclName());
  1696. // If we're referencing an invalid decl, just return this as a silent
  1697. // error node. The error diagnostic was already emitted on the decl.
  1698. if (IV->isInvalidDecl())
  1699. return ExprError();
  1700. // Check if referencing a field with __attribute__((deprecated)).
  1701. if (DiagnoseUseOfDecl(IV, Loc))
  1702. return ExprError();
  1703. // Diagnose the use of an ivar outside of the declaring class.
  1704. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  1705. !declaresSameEntity(ClassDeclared, IFace) &&
  1706. !getLangOpts().DebuggerSupport)
  1707. Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
  1708. // FIXME: This should use a new expr for a direct reference, don't
  1709. // turn this into Self->ivar, just return a BareIVarExpr or something.
  1710. IdentifierInfo &II = Context.Idents.get("self");
  1711. UnqualifiedId SelfName;
  1712. SelfName.setIdentifier(&II, SourceLocation());
  1713. SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
  1714. CXXScopeSpec SelfScopeSpec;
  1715. SourceLocation TemplateKWLoc;
  1716. ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
  1717. SelfName, false, false);
  1718. if (SelfExpr.isInvalid())
  1719. return ExprError();
  1720. SelfExpr = DefaultLvalueConversion(SelfExpr.take());
  1721. if (SelfExpr.isInvalid())
  1722. return ExprError();
  1723. MarkAnyDeclReferenced(Loc, IV);
  1724. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  1725. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
  1726. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  1727. return Owned(new (Context)
  1728. ObjCIvarRefExpr(IV, IV->getType(), Loc,
  1729. SelfExpr.take(), true, true));
  1730. }
  1731. } else if (CurMethod->isInstanceMethod()) {
  1732. // We should warn if a local variable hides an ivar.
  1733. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  1734. ObjCInterfaceDecl *ClassDeclared;
  1735. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  1736. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  1737. declaresSameEntity(IFace, ClassDeclared))
  1738. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  1739. }
  1740. }
  1741. } else if (Lookup.isSingleResult() &&
  1742. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  1743. // If accessing a stand-alone ivar in a class method, this is an error.
  1744. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  1745. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  1746. << IV->getDeclName());
  1747. }
  1748. if (Lookup.empty() && II && AllowBuiltinCreation) {
  1749. // FIXME. Consolidate this with similar code in LookupName.
  1750. if (unsigned BuiltinID = II->getBuiltinID()) {
  1751. if (!(getLangOpts().CPlusPlus &&
  1752. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  1753. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  1754. S, Lookup.isForRedeclaration(),
  1755. Lookup.getNameLoc());
  1756. if (D) Lookup.addDecl(D);
  1757. }
  1758. }
  1759. }
  1760. // Sentinel value saying that we didn't do anything special.
  1761. return Owned((Expr*) 0);
  1762. }
  1763. /// \brief Cast a base object to a member's actual type.
  1764. ///
  1765. /// Logically this happens in three phases:
  1766. ///
  1767. /// * First we cast from the base type to the naming class.
  1768. /// The naming class is the class into which we were looking
  1769. /// when we found the member; it's the qualifier type if a
  1770. /// qualifier was provided, and otherwise it's the base type.
  1771. ///
  1772. /// * Next we cast from the naming class to the declaring class.
  1773. /// If the member we found was brought into a class's scope by
  1774. /// a using declaration, this is that class; otherwise it's
  1775. /// the class declaring the member.
  1776. ///
  1777. /// * Finally we cast from the declaring class to the "true"
  1778. /// declaring class of the member. This conversion does not
  1779. /// obey access control.
  1780. ExprResult
  1781. Sema::PerformObjectMemberConversion(Expr *From,
  1782. NestedNameSpecifier *Qualifier,
  1783. NamedDecl *FoundDecl,
  1784. NamedDecl *Member) {
  1785. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  1786. if (!RD)
  1787. return Owned(From);
  1788. QualType DestRecordType;
  1789. QualType DestType;
  1790. QualType FromRecordType;
  1791. QualType FromType = From->getType();
  1792. bool PointerConversions = false;
  1793. if (isa<FieldDecl>(Member)) {
  1794. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  1795. if (FromType->getAs<PointerType>()) {
  1796. DestType = Context.getPointerType(DestRecordType);
  1797. FromRecordType = FromType->getPointeeType();
  1798. PointerConversions = true;
  1799. } else {
  1800. DestType = DestRecordType;
  1801. FromRecordType = FromType;
  1802. }
  1803. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  1804. if (Method->isStatic())
  1805. return Owned(From);
  1806. DestType = Method->getThisType(Context);
  1807. DestRecordType = DestType->getPointeeType();
  1808. if (FromType->getAs<PointerType>()) {
  1809. FromRecordType = FromType->getPointeeType();
  1810. PointerConversions = true;
  1811. } else {
  1812. FromRecordType = FromType;
  1813. DestType = DestRecordType;
  1814. }
  1815. } else {
  1816. // No conversion necessary.
  1817. return Owned(From);
  1818. }
  1819. if (DestType->isDependentType() || FromType->isDependentType())
  1820. return Owned(From);
  1821. // If the unqualified types are the same, no conversion is necessary.
  1822. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  1823. return Owned(From);
  1824. SourceRange FromRange = From->getSourceRange();
  1825. SourceLocation FromLoc = FromRange.getBegin();
  1826. ExprValueKind VK = From->getValueKind();
  1827. // C++ [class.member.lookup]p8:
  1828. // [...] Ambiguities can often be resolved by qualifying a name with its
  1829. // class name.
  1830. //
  1831. // If the member was a qualified name and the qualified referred to a
  1832. // specific base subobject type, we'll cast to that intermediate type
  1833. // first and then to the object in which the member is declared. That allows
  1834. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  1835. //
  1836. // class Base { public: int x; };
  1837. // class Derived1 : public Base { };
  1838. // class Derived2 : public Base { };
  1839. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  1840. //
  1841. // void VeryDerived::f() {
  1842. // x = 17; // error: ambiguous base subobjects
  1843. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  1844. // }
  1845. if (Qualifier) {
  1846. QualType QType = QualType(Qualifier->getAsType(), 0);
  1847. assert(!QType.isNull() && "lookup done with dependent qualifier?");
  1848. assert(QType->isRecordType() && "lookup done with non-record type");
  1849. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  1850. // In C++98, the qualifier type doesn't actually have to be a base
  1851. // type of the object type, in which case we just ignore it.
  1852. // Otherwise build the appropriate casts.
  1853. if (IsDerivedFrom(FromRecordType, QRecordType)) {
  1854. CXXCastPath BasePath;
  1855. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  1856. FromLoc, FromRange, &BasePath))
  1857. return ExprError();
  1858. if (PointerConversions)
  1859. QType = Context.getPointerType(QType);
  1860. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  1861. VK, &BasePath).take();
  1862. FromType = QType;
  1863. FromRecordType = QRecordType;
  1864. // If the qualifier type was the same as the destination type,
  1865. // we're done.
  1866. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  1867. return Owned(From);
  1868. }
  1869. }
  1870. bool IgnoreAccess = false;
  1871. // If we actually found the member through a using declaration, cast
  1872. // down to the using declaration's type.
  1873. //
  1874. // Pointer equality is fine here because only one declaration of a
  1875. // class ever has member declarations.
  1876. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  1877. assert(isa<UsingShadowDecl>(FoundDecl));
  1878. QualType URecordType = Context.getTypeDeclType(
  1879. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  1880. // We only need to do this if the naming-class to declaring-class
  1881. // conversion is non-trivial.
  1882. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  1883. assert(IsDerivedFrom(FromRecordType, URecordType));
  1884. CXXCastPath BasePath;
  1885. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  1886. FromLoc, FromRange, &BasePath))
  1887. return ExprError();
  1888. QualType UType = URecordType;
  1889. if (PointerConversions)
  1890. UType = Context.getPointerType(UType);
  1891. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  1892. VK, &BasePath).take();
  1893. FromType = UType;
  1894. FromRecordType = URecordType;
  1895. }
  1896. // We don't do access control for the conversion from the
  1897. // declaring class to the true declaring class.
  1898. IgnoreAccess = true;
  1899. }
  1900. CXXCastPath BasePath;
  1901. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  1902. FromLoc, FromRange, &BasePath,
  1903. IgnoreAccess))
  1904. return ExprError();
  1905. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  1906. VK, &BasePath);
  1907. }
  1908. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  1909. const LookupResult &R,
  1910. bool HasTrailingLParen) {
  1911. // Only when used directly as the postfix-expression of a call.
  1912. if (!HasTrailingLParen)
  1913. return false;
  1914. // Never if a scope specifier was provided.
  1915. if (SS.isSet())
  1916. return false;
  1917. // Only in C++ or ObjC++.
  1918. if (!getLangOpts().CPlusPlus)
  1919. return false;
  1920. // Turn off ADL when we find certain kinds of declarations during
  1921. // normal lookup:
  1922. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  1923. NamedDecl *D = *I;
  1924. // C++0x [basic.lookup.argdep]p3:
  1925. // -- a declaration of a class member
  1926. // Since using decls preserve this property, we check this on the
  1927. // original decl.
  1928. if (D->isCXXClassMember())
  1929. return false;
  1930. // C++0x [basic.lookup.argdep]p3:
  1931. // -- a block-scope function declaration that is not a
  1932. // using-declaration
  1933. // NOTE: we also trigger this for function templates (in fact, we
  1934. // don't check the decl type at all, since all other decl types
  1935. // turn off ADL anyway).
  1936. if (isa<UsingShadowDecl>(D))
  1937. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  1938. else if (D->getDeclContext()->isFunctionOrMethod())
  1939. return false;
  1940. // C++0x [basic.lookup.argdep]p3:
  1941. // -- a declaration that is neither a function or a function
  1942. // template
  1943. // And also for builtin functions.
  1944. if (isa<FunctionDecl>(D)) {
  1945. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  1946. // But also builtin functions.
  1947. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  1948. return false;
  1949. } else if (!isa<FunctionTemplateDecl>(D))
  1950. return false;
  1951. }
  1952. return true;
  1953. }
  1954. /// Diagnoses obvious problems with the use of the given declaration
  1955. /// as an expression. This is only actually called for lookups that
  1956. /// were not overloaded, and it doesn't promise that the declaration
  1957. /// will in fact be used.
  1958. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  1959. if (isa<TypedefNameDecl>(D)) {
  1960. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  1961. return true;
  1962. }
  1963. if (isa<ObjCInterfaceDecl>(D)) {
  1964. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  1965. return true;
  1966. }
  1967. if (isa<NamespaceDecl>(D)) {
  1968. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  1969. return true;
  1970. }
  1971. return false;
  1972. }
  1973. ExprResult
  1974. Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  1975. LookupResult &R,
  1976. bool NeedsADL) {
  1977. // If this is a single, fully-resolved result and we don't need ADL,
  1978. // just build an ordinary singleton decl ref.
  1979. if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
  1980. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
  1981. R.getFoundDecl());
  1982. // We only need to check the declaration if there's exactly one
  1983. // result, because in the overloaded case the results can only be
  1984. // functions and function templates.
  1985. if (R.isSingleResult() &&
  1986. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  1987. return ExprError();
  1988. // Otherwise, just build an unresolved lookup expression. Suppress
  1989. // any lookup-related diagnostics; we'll hash these out later, when
  1990. // we've picked a target.
  1991. R.suppressDiagnostics();
  1992. UnresolvedLookupExpr *ULE
  1993. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  1994. SS.getWithLocInContext(Context),
  1995. R.getLookupNameInfo(),
  1996. NeedsADL, R.isOverloadedResult(),
  1997. R.begin(), R.end());
  1998. return Owned(ULE);
  1999. }
  2000. /// \brief Complete semantic analysis for a reference to the given declaration.
  2001. ExprResult
  2002. Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2003. const DeclarationNameInfo &NameInfo,
  2004. NamedDecl *D) {
  2005. assert(D && "Cannot refer to a NULL declaration");
  2006. assert(!isa<FunctionTemplateDecl>(D) &&
  2007. "Cannot refer unambiguously to a function template");
  2008. SourceLocation Loc = NameInfo.getLoc();
  2009. if (CheckDeclInExpr(*this, Loc, D))
  2010. return ExprError();
  2011. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2012. // Specifically diagnose references to class templates that are missing
  2013. // a template argument list.
  2014. Diag(Loc, diag::err_template_decl_ref)
  2015. << Template << SS.getRange();
  2016. Diag(Template->getLocation(), diag::note_template_decl_here);
  2017. return ExprError();
  2018. }
  2019. // Make sure that we're referring to a value.
  2020. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2021. if (!VD) {
  2022. Diag(Loc, diag::err_ref_non_value)
  2023. << D << SS.getRange();
  2024. Diag(D->getLocation(), diag::note_declared_at);
  2025. return ExprError();
  2026. }
  2027. // Check whether this declaration can be used. Note that we suppress
  2028. // this check when we're going to perform argument-dependent lookup
  2029. // on this function name, because this might not be the function
  2030. // that overload resolution actually selects.
  2031. if (DiagnoseUseOfDecl(VD, Loc))
  2032. return ExprError();
  2033. // Only create DeclRefExpr's for valid Decl's.
  2034. if (VD->isInvalidDecl())
  2035. return ExprError();
  2036. // Handle members of anonymous structs and unions. If we got here,
  2037. // and the reference is to a class member indirect field, then this
  2038. // must be the subject of a pointer-to-member expression.
  2039. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2040. if (!indirectField->isCXXClassMember())
  2041. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2042. indirectField);
  2043. {
  2044. QualType type = VD->getType();
  2045. ExprValueKind valueKind = VK_RValue;
  2046. switch (D->getKind()) {
  2047. // Ignore all the non-ValueDecl kinds.
  2048. #define ABSTRACT_DECL(kind)
  2049. #define VALUE(type, base)
  2050. #define DECL(type, base) \
  2051. case Decl::type:
  2052. #include "clang/AST/DeclNodes.inc"
  2053. llvm_unreachable("invalid value decl kind");
  2054. // These shouldn't make it here.
  2055. case Decl::ObjCAtDefsField:
  2056. case Decl::ObjCIvar:
  2057. llvm_unreachable("forming non-member reference to ivar?");
  2058. // Enum constants are always r-values and never references.
  2059. // Unresolved using declarations are dependent.
  2060. case Decl::EnumConstant:
  2061. case Decl::UnresolvedUsingValue:
  2062. valueKind = VK_RValue;
  2063. break;
  2064. // Fields and indirect fields that got here must be for
  2065. // pointer-to-member expressions; we just call them l-values for
  2066. // internal consistency, because this subexpression doesn't really
  2067. // exist in the high-level semantics.
  2068. case Decl::Field:
  2069. case Decl::IndirectField:
  2070. assert(getLangOpts().CPlusPlus &&
  2071. "building reference to field in C?");
  2072. // These can't have reference type in well-formed programs, but
  2073. // for internal consistency we do this anyway.
  2074. type = type.getNonReferenceType();
  2075. valueKind = VK_LValue;
  2076. break;
  2077. // Non-type template parameters are either l-values or r-values
  2078. // depending on the type.
  2079. case Decl::NonTypeTemplateParm: {
  2080. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2081. type = reftype->getPointeeType();
  2082. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2083. break;
  2084. }
  2085. // For non-references, we need to strip qualifiers just in case
  2086. // the template parameter was declared as 'const int' or whatever.
  2087. valueKind = VK_RValue;
  2088. type = type.getUnqualifiedType();
  2089. break;
  2090. }
  2091. case Decl::Var:
  2092. // In C, "extern void blah;" is valid and is an r-value.
  2093. if (!getLangOpts().CPlusPlus &&
  2094. !type.hasQualifiers() &&
  2095. type->isVoidType()) {
  2096. valueKind = VK_RValue;
  2097. break;
  2098. }
  2099. // fallthrough
  2100. case Decl::ImplicitParam:
  2101. case Decl::ParmVar: {
  2102. // These are always l-values.
  2103. valueKind = VK_LValue;
  2104. type = type.getNonReferenceType();
  2105. // FIXME: Does the addition of const really only apply in
  2106. // potentially-evaluated contexts? Since the variable isn't actually
  2107. // captured in an unevaluated context, it seems that the answer is no.
  2108. if (!isUnevaluatedContext()) {
  2109. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2110. if (!CapturedType.isNull())
  2111. type = CapturedType;
  2112. }
  2113. break;
  2114. }
  2115. case Decl::Function: {
  2116. const FunctionType *fty = type->castAs<FunctionType>();
  2117. // If we're referring to a function with an __unknown_anytype
  2118. // result type, make the entire expression __unknown_anytype.
  2119. if (fty->getResultType() == Context.UnknownAnyTy) {
  2120. type = Context.UnknownAnyTy;
  2121. valueKind = VK_RValue;
  2122. break;
  2123. }
  2124. // Functions are l-values in C++.
  2125. if (getLangOpts().CPlusPlus) {
  2126. valueKind = VK_LValue;
  2127. break;
  2128. }
  2129. // C99 DR 316 says that, if a function type comes from a
  2130. // function definition (without a prototype), that type is only
  2131. // used for checking compatibility. Therefore, when referencing
  2132. // the function, we pretend that we don't have the full function
  2133. // type.
  2134. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2135. isa<FunctionProtoType>(fty))
  2136. type = Context.getFunctionNoProtoType(fty->getResultType(),
  2137. fty->getExtInfo());
  2138. // Functions are r-values in C.
  2139. valueKind = VK_RValue;
  2140. break;
  2141. }
  2142. case Decl::CXXMethod:
  2143. // If we're referring to a method with an __unknown_anytype
  2144. // result type, make the entire expression __unknown_anytype.
  2145. // This should only be possible with a type written directly.
  2146. if (const FunctionProtoType *proto
  2147. = dyn_cast<FunctionProtoType>(VD->getType()))
  2148. if (proto->getResultType() == Context.UnknownAnyTy) {
  2149. type = Context.UnknownAnyTy;
  2150. valueKind = VK_RValue;
  2151. break;
  2152. }
  2153. // C++ methods are l-values if static, r-values if non-static.
  2154. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2155. valueKind = VK_LValue;
  2156. break;
  2157. }
  2158. // fallthrough
  2159. case Decl::CXXConversion:
  2160. case Decl::CXXDestructor:
  2161. case Decl::CXXConstructor:
  2162. valueKind = VK_RValue;
  2163. break;
  2164. }
  2165. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
  2166. }
  2167. }
  2168. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2169. PredefinedExpr::IdentType IT;
  2170. switch (Kind) {
  2171. default: llvm_unreachable("Unknown simple primary expr!");
  2172. case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2173. case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
  2174. case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
  2175. case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
  2176. }
  2177. // Pre-defined identifiers are of type char[x], where x is the length of the
  2178. // string.
  2179. Decl *currentDecl = getCurFunctionOrMethodDecl();
  2180. if (!currentDecl && getCurBlock())
  2181. currentDecl = getCurBlock()->TheDecl;
  2182. if (!currentDecl) {
  2183. Diag(Loc, diag::ext_predef_outside_function);
  2184. currentDecl = Context.getTranslationUnitDecl();
  2185. }
  2186. QualType ResTy;
  2187. if (cast<DeclContext>(currentDecl)->isDependentContext()) {
  2188. ResTy = Context.DependentTy;
  2189. } else {
  2190. unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
  2191. llvm::APInt LengthI(32, Length + 1);
  2192. if (IT == PredefinedExpr::LFunction)
  2193. ResTy = Context.WCharTy.withConst();
  2194. else
  2195. ResTy = Context.CharTy.withConst();
  2196. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
  2197. }
  2198. return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
  2199. }
  2200. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2201. SmallString<16> CharBuffer;
  2202. bool Invalid = false;
  2203. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2204. if (Invalid)
  2205. return ExprError();
  2206. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2207. PP, Tok.getKind());
  2208. if (Literal.hadError())
  2209. return ExprError();
  2210. QualType Ty;
  2211. if (Literal.isWide())
  2212. Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
  2213. else if (Literal.isUTF16())
  2214. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2215. else if (Literal.isUTF32())
  2216. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2217. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2218. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2219. else
  2220. Ty = Context.CharTy; // 'x' -> char in C++
  2221. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2222. if (Literal.isWide())
  2223. Kind = CharacterLiteral::Wide;
  2224. else if (Literal.isUTF16())
  2225. Kind = CharacterLiteral::UTF16;
  2226. else if (Literal.isUTF32())
  2227. Kind = CharacterLiteral::UTF32;
  2228. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2229. Tok.getLocation());
  2230. if (Literal.getUDSuffix().empty())
  2231. return Owned(Lit);
  2232. // We're building a user-defined literal.
  2233. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2234. SourceLocation UDSuffixLoc =
  2235. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2236. // Make sure we're allowed user-defined literals here.
  2237. if (!UDLScope)
  2238. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2239. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2240. // operator "" X (ch)
  2241. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2242. llvm::makeArrayRef(&Lit, 1),
  2243. Tok.getLocation());
  2244. }
  2245. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2246. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2247. return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2248. Context.IntTy, Loc));
  2249. }
  2250. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2251. QualType Ty, SourceLocation Loc) {
  2252. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2253. using llvm::APFloat;
  2254. APFloat Val(Format);
  2255. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2256. // Overflow is always an error, but underflow is only an error if
  2257. // we underflowed to zero (APFloat reports denormals as underflow).
  2258. if ((result & APFloat::opOverflow) ||
  2259. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2260. unsigned diagnostic;
  2261. SmallString<20> buffer;
  2262. if (result & APFloat::opOverflow) {
  2263. diagnostic = diag::warn_float_overflow;
  2264. APFloat::getLargest(Format).toString(buffer);
  2265. } else {
  2266. diagnostic = diag::warn_float_underflow;
  2267. APFloat::getSmallest(Format).toString(buffer);
  2268. }
  2269. S.Diag(Loc, diagnostic)
  2270. << Ty
  2271. << StringRef(buffer.data(), buffer.size());
  2272. }
  2273. bool isExact = (result == APFloat::opOK);
  2274. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2275. }
  2276. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2277. // Fast path for a single digit (which is quite common). A single digit
  2278. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2279. if (Tok.getLength() == 1) {
  2280. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2281. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2282. }
  2283. SmallString<512> IntegerBuffer;
  2284. // Add padding so that NumericLiteralParser can overread by one character.
  2285. IntegerBuffer.resize(Tok.getLength()+1);
  2286. const char *ThisTokBegin = &IntegerBuffer[0];
  2287. // Get the spelling of the token, which eliminates trigraphs, etc.
  2288. bool Invalid = false;
  2289. unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
  2290. if (Invalid)
  2291. return ExprError();
  2292. NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
  2293. Tok.getLocation(), PP);
  2294. if (Literal.hadError)
  2295. return ExprError();
  2296. if (Literal.hasUDSuffix()) {
  2297. // We're building a user-defined literal.
  2298. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2299. SourceLocation UDSuffixLoc =
  2300. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2301. // Make sure we're allowed user-defined literals here.
  2302. if (!UDLScope)
  2303. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2304. QualType CookedTy;
  2305. if (Literal.isFloatingLiteral()) {
  2306. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2307. // long double, the literal is treated as a call of the form
  2308. // operator "" X (f L)
  2309. CookedTy = Context.LongDoubleTy;
  2310. } else {
  2311. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2312. // unsigned long long, the literal is treated as a call of the form
  2313. // operator "" X (n ULL)
  2314. CookedTy = Context.UnsignedLongLongTy;
  2315. }
  2316. DeclarationName OpName =
  2317. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  2318. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  2319. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  2320. // Perform literal operator lookup to determine if we're building a raw
  2321. // literal or a cooked one.
  2322. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  2323. switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
  2324. /*AllowRawAndTemplate*/true)) {
  2325. case LOLR_Error:
  2326. return ExprError();
  2327. case LOLR_Cooked: {
  2328. Expr *Lit;
  2329. if (Literal.isFloatingLiteral()) {
  2330. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  2331. } else {
  2332. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  2333. if (Literal.GetIntegerValue(ResultVal))
  2334. Diag(Tok.getLocation(), diag::warn_integer_too_large);
  2335. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  2336. Tok.getLocation());
  2337. }
  2338. return BuildLiteralOperatorCall(R, OpNameInfo,
  2339. llvm::makeArrayRef(&Lit, 1),
  2340. Tok.getLocation());
  2341. }
  2342. case LOLR_Raw: {
  2343. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  2344. // literal is treated as a call of the form
  2345. // operator "" X ("n")
  2346. SourceLocation TokLoc = Tok.getLocation();
  2347. unsigned Length = Literal.getUDSuffixOffset();
  2348. QualType StrTy = Context.getConstantArrayType(
  2349. Context.CharTy, llvm::APInt(32, Length + 1),
  2350. ArrayType::Normal, 0);
  2351. Expr *Lit = StringLiteral::Create(
  2352. Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
  2353. /*Pascal*/false, StrTy, &TokLoc, 1);
  2354. return BuildLiteralOperatorCall(R, OpNameInfo,
  2355. llvm::makeArrayRef(&Lit, 1), TokLoc);
  2356. }
  2357. case LOLR_Template:
  2358. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  2359. // template), L is treated as a call fo the form
  2360. // operator "" X <'c1', 'c2', ... 'ck'>()
  2361. // where n is the source character sequence c1 c2 ... ck.
  2362. TemplateArgumentListInfo ExplicitArgs;
  2363. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  2364. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  2365. llvm::APSInt Value(CharBits, CharIsUnsigned);
  2366. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  2367. Value = ThisTokBegin[I];
  2368. TemplateArgument Arg(Context, Value, Context.CharTy);
  2369. TemplateArgumentLocInfo ArgInfo;
  2370. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  2371. }
  2372. return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
  2373. Tok.getLocation(), &ExplicitArgs);
  2374. }
  2375. llvm_unreachable("unexpected literal operator lookup result");
  2376. }
  2377. Expr *Res;
  2378. if (Literal.isFloatingLiteral()) {
  2379. QualType Ty;
  2380. if (Literal.isFloat)
  2381. Ty = Context.FloatTy;
  2382. else if (!Literal.isLong)
  2383. Ty = Context.DoubleTy;
  2384. else
  2385. Ty = Context.LongDoubleTy;
  2386. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  2387. if (Ty == Context.DoubleTy) {
  2388. if (getLangOpts().SinglePrecisionConstants) {
  2389. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
  2390. } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
  2391. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  2392. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
  2393. }
  2394. }
  2395. } else if (!Literal.isIntegerLiteral()) {
  2396. return ExprError();
  2397. } else {
  2398. QualType Ty;
  2399. // long long is a C99 feature.
  2400. if (!getLangOpts().C99 && Literal.isLongLong)
  2401. Diag(Tok.getLocation(),
  2402. getLangOpts().CPlusPlus0x ?
  2403. diag::warn_cxx98_compat_longlong : diag::ext_longlong);
  2404. // Get the value in the widest-possible width.
  2405. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  2406. // The microsoft literal suffix extensions support 128-bit literals, which
  2407. // may be wider than [u]intmax_t.
  2408. if (Literal.isMicrosoftInteger && MaxWidth < 128)
  2409. MaxWidth = 128;
  2410. llvm::APInt ResultVal(MaxWidth, 0);
  2411. if (Literal.GetIntegerValue(ResultVal)) {
  2412. // If this value didn't fit into uintmax_t, warn and force to ull.
  2413. Diag(Tok.getLocation(), diag::warn_integer_too_large);
  2414. Ty = Context.UnsignedLongLongTy;
  2415. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  2416. "long long is not intmax_t?");
  2417. } else {
  2418. // If this value fits into a ULL, try to figure out what else it fits into
  2419. // according to the rules of C99 6.4.4.1p5.
  2420. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  2421. // be an unsigned int.
  2422. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  2423. // Check from smallest to largest, picking the smallest type we can.
  2424. unsigned Width = 0;
  2425. if (!Literal.isLong && !Literal.isLongLong) {
  2426. // Are int/unsigned possibilities?
  2427. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2428. // Does it fit in a unsigned int?
  2429. if (ResultVal.isIntN(IntSize)) {
  2430. // Does it fit in a signed int?
  2431. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  2432. Ty = Context.IntTy;
  2433. else if (AllowUnsigned)
  2434. Ty = Context.UnsignedIntTy;
  2435. Width = IntSize;
  2436. }
  2437. }
  2438. // Are long/unsigned long possibilities?
  2439. if (Ty.isNull() && !Literal.isLongLong) {
  2440. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  2441. // Does it fit in a unsigned long?
  2442. if (ResultVal.isIntN(LongSize)) {
  2443. // Does it fit in a signed long?
  2444. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  2445. Ty = Context.LongTy;
  2446. else if (AllowUnsigned)
  2447. Ty = Context.UnsignedLongTy;
  2448. Width = LongSize;
  2449. }
  2450. }
  2451. // Check long long if needed.
  2452. if (Ty.isNull()) {
  2453. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  2454. // Does it fit in a unsigned long long?
  2455. if (ResultVal.isIntN(LongLongSize)) {
  2456. // Does it fit in a signed long long?
  2457. // To be compatible with MSVC, hex integer literals ending with the
  2458. // LL or i64 suffix are always signed in Microsoft mode.
  2459. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  2460. (getLangOpts().MicrosoftExt && Literal.isLongLong)))
  2461. Ty = Context.LongLongTy;
  2462. else if (AllowUnsigned)
  2463. Ty = Context.UnsignedLongLongTy;
  2464. Width = LongLongSize;
  2465. }
  2466. }
  2467. // If it doesn't fit in unsigned long long, and we're using Microsoft
  2468. // extensions, then its a 128-bit integer literal.
  2469. if (Ty.isNull() && Literal.isMicrosoftInteger) {
  2470. if (Literal.isUnsigned)
  2471. Ty = Context.UnsignedInt128Ty;
  2472. else
  2473. Ty = Context.Int128Ty;
  2474. Width = 128;
  2475. }
  2476. // If we still couldn't decide a type, we probably have something that
  2477. // does not fit in a signed long long, but has no U suffix.
  2478. if (Ty.isNull()) {
  2479. Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
  2480. Ty = Context.UnsignedLongLongTy;
  2481. Width = Context.getTargetInfo().getLongLongWidth();
  2482. }
  2483. if (ResultVal.getBitWidth() != Width)
  2484. ResultVal = ResultVal.trunc(Width);
  2485. }
  2486. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  2487. }
  2488. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  2489. if (Literal.isImaginary)
  2490. Res = new (Context) ImaginaryLiteral(Res,
  2491. Context.getComplexType(Res->getType()));
  2492. return Owned(Res);
  2493. }
  2494. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  2495. assert((E != 0) && "ActOnParenExpr() missing expr");
  2496. return Owned(new (Context) ParenExpr(L, R, E));
  2497. }
  2498. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  2499. SourceLocation Loc,
  2500. SourceRange ArgRange) {
  2501. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  2502. // scalar or vector data type argument..."
  2503. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  2504. // type (C99 6.2.5p18) or void.
  2505. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  2506. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  2507. << T << ArgRange;
  2508. return true;
  2509. }
  2510. assert((T->isVoidType() || !T->isIncompleteType()) &&
  2511. "Scalar types should always be complete");
  2512. return false;
  2513. }
  2514. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  2515. SourceLocation Loc,
  2516. SourceRange ArgRange,
  2517. UnaryExprOrTypeTrait TraitKind) {
  2518. // C99 6.5.3.4p1:
  2519. if (T->isFunctionType()) {
  2520. // alignof(function) is allowed as an extension.
  2521. if (TraitKind == UETT_SizeOf)
  2522. S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
  2523. return false;
  2524. }
  2525. // Allow sizeof(void)/alignof(void) as an extension.
  2526. if (T->isVoidType()) {
  2527. S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
  2528. return false;
  2529. }
  2530. return true;
  2531. }
  2532. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  2533. SourceLocation Loc,
  2534. SourceRange ArgRange,
  2535. UnaryExprOrTypeTrait TraitKind) {
  2536. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  2537. // runtime doesn't allow it.
  2538. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  2539. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  2540. << T << (TraitKind == UETT_SizeOf)
  2541. << ArgRange;
  2542. return true;
  2543. }
  2544. return false;
  2545. }
  2546. /// \brief Check the constrains on expression operands to unary type expression
  2547. /// and type traits.
  2548. ///
  2549. /// Completes any types necessary and validates the constraints on the operand
  2550. /// expression. The logic mostly mirrors the type-based overload, but may modify
  2551. /// the expression as it completes the type for that expression through template
  2552. /// instantiation, etc.
  2553. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  2554. UnaryExprOrTypeTrait ExprKind) {
  2555. QualType ExprTy = E->getType();
  2556. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  2557. // the result is the size of the referenced type."
  2558. // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
  2559. // result shall be the alignment of the referenced type."
  2560. if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
  2561. ExprTy = Ref->getPointeeType();
  2562. if (ExprKind == UETT_VecStep)
  2563. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  2564. E->getSourceRange());
  2565. // Whitelist some types as extensions
  2566. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  2567. E->getSourceRange(), ExprKind))
  2568. return false;
  2569. if (RequireCompleteExprType(E,
  2570. diag::err_sizeof_alignof_incomplete_type,
  2571. ExprKind, E->getSourceRange()))
  2572. return true;
  2573. // Completeing the expression's type may have changed it.
  2574. ExprTy = E->getType();
  2575. if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
  2576. ExprTy = Ref->getPointeeType();
  2577. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  2578. E->getSourceRange(), ExprKind))
  2579. return true;
  2580. if (ExprKind == UETT_SizeOf) {
  2581. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  2582. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  2583. QualType OType = PVD->getOriginalType();
  2584. QualType Type = PVD->getType();
  2585. if (Type->isPointerType() && OType->isArrayType()) {
  2586. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  2587. << Type << OType;
  2588. Diag(PVD->getLocation(), diag::note_declared_at);
  2589. }
  2590. }
  2591. }
  2592. }
  2593. return false;
  2594. }
  2595. /// \brief Check the constraints on operands to unary expression and type
  2596. /// traits.
  2597. ///
  2598. /// This will complete any types necessary, and validate the various constraints
  2599. /// on those operands.
  2600. ///
  2601. /// The UsualUnaryConversions() function is *not* called by this routine.
  2602. /// C99 6.3.2.1p[2-4] all state:
  2603. /// Except when it is the operand of the sizeof operator ...
  2604. ///
  2605. /// C++ [expr.sizeof]p4
  2606. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  2607. /// standard conversions are not applied to the operand of sizeof.
  2608. ///
  2609. /// This policy is followed for all of the unary trait expressions.
  2610. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  2611. SourceLocation OpLoc,
  2612. SourceRange ExprRange,
  2613. UnaryExprOrTypeTrait ExprKind) {
  2614. if (ExprType->isDependentType())
  2615. return false;
  2616. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  2617. // the result is the size of the referenced type."
  2618. // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
  2619. // result shall be the alignment of the referenced type."
  2620. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  2621. ExprType = Ref->getPointeeType();
  2622. if (ExprKind == UETT_VecStep)
  2623. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  2624. // Whitelist some types as extensions
  2625. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  2626. ExprKind))
  2627. return false;
  2628. if (RequireCompleteType(OpLoc, ExprType,
  2629. diag::err_sizeof_alignof_incomplete_type,
  2630. ExprKind, ExprRange))
  2631. return true;
  2632. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  2633. ExprKind))
  2634. return true;
  2635. return false;
  2636. }
  2637. static bool CheckAlignOfExpr(Sema &S, Expr *E) {
  2638. E = E->IgnoreParens();
  2639. // alignof decl is always ok.
  2640. if (isa<DeclRefExpr>(E))
  2641. return false;
  2642. // Cannot know anything else if the expression is dependent.
  2643. if (E->isTypeDependent())
  2644. return false;
  2645. if (E->getBitField()) {
  2646. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
  2647. << 1 << E->getSourceRange();
  2648. return true;
  2649. }
  2650. // Alignment of a field access is always okay, so long as it isn't a
  2651. // bit-field.
  2652. if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
  2653. if (isa<FieldDecl>(ME->getMemberDecl()))
  2654. return false;
  2655. return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
  2656. }
  2657. bool Sema::CheckVecStepExpr(Expr *E) {
  2658. E = E->IgnoreParens();
  2659. // Cannot know anything else if the expression is dependent.
  2660. if (E->isTypeDependent())
  2661. return false;
  2662. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  2663. }
  2664. /// \brief Build a sizeof or alignof expression given a type operand.
  2665. ExprResult
  2666. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  2667. SourceLocation OpLoc,
  2668. UnaryExprOrTypeTrait ExprKind,
  2669. SourceRange R) {
  2670. if (!TInfo)
  2671. return ExprError();
  2672. QualType T = TInfo->getType();
  2673. if (!T->isDependentType() &&
  2674. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  2675. return ExprError();
  2676. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  2677. return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
  2678. Context.getSizeType(),
  2679. OpLoc, R.getEnd()));
  2680. }
  2681. /// \brief Build a sizeof or alignof expression given an expression
  2682. /// operand.
  2683. ExprResult
  2684. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  2685. UnaryExprOrTypeTrait ExprKind) {
  2686. ExprResult PE = CheckPlaceholderExpr(E);
  2687. if (PE.isInvalid())
  2688. return ExprError();
  2689. E = PE.get();
  2690. // Verify that the operand is valid.
  2691. bool isInvalid = false;
  2692. if (E->isTypeDependent()) {
  2693. // Delay type-checking for type-dependent expressions.
  2694. } else if (ExprKind == UETT_AlignOf) {
  2695. isInvalid = CheckAlignOfExpr(*this, E);
  2696. } else if (ExprKind == UETT_VecStep) {
  2697. isInvalid = CheckVecStepExpr(E);
  2698. } else if (E->getBitField()) { // C99 6.5.3.4p1.
  2699. Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
  2700. isInvalid = true;
  2701. } else {
  2702. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  2703. }
  2704. if (isInvalid)
  2705. return ExprError();
  2706. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  2707. PE = TranformToPotentiallyEvaluated(E);
  2708. if (PE.isInvalid()) return ExprError();
  2709. E = PE.take();
  2710. }
  2711. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  2712. return Owned(new (Context) UnaryExprOrTypeTraitExpr(
  2713. ExprKind, E, Context.getSizeType(), OpLoc,
  2714. E->getSourceRange().getEnd()));
  2715. }
  2716. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  2717. /// expr and the same for @c alignof and @c __alignof
  2718. /// Note that the ArgRange is invalid if isType is false.
  2719. ExprResult
  2720. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  2721. UnaryExprOrTypeTrait ExprKind, bool IsType,
  2722. void *TyOrEx, const SourceRange &ArgRange) {
  2723. // If error parsing type, ignore.
  2724. if (TyOrEx == 0) return ExprError();
  2725. if (IsType) {
  2726. TypeSourceInfo *TInfo;
  2727. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  2728. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  2729. }
  2730. Expr *ArgEx = (Expr *)TyOrEx;
  2731. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  2732. return Result;
  2733. }
  2734. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  2735. bool IsReal) {
  2736. if (V.get()->isTypeDependent())
  2737. return S.Context.DependentTy;
  2738. // _Real and _Imag are only l-values for normal l-values.
  2739. if (V.get()->getObjectKind() != OK_Ordinary) {
  2740. V = S.DefaultLvalueConversion(V.take());
  2741. if (V.isInvalid())
  2742. return QualType();
  2743. }
  2744. // These operators return the element type of a complex type.
  2745. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  2746. return CT->getElementType();
  2747. // Otherwise they pass through real integer and floating point types here.
  2748. if (V.get()->getType()->isArithmeticType())
  2749. return V.get()->getType();
  2750. // Test for placeholders.
  2751. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  2752. if (PR.isInvalid()) return QualType();
  2753. if (PR.get() != V.get()) {
  2754. V = PR;
  2755. return CheckRealImagOperand(S, V, Loc, IsReal);
  2756. }
  2757. // Reject anything else.
  2758. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  2759. << (IsReal ? "__real" : "__imag");
  2760. return QualType();
  2761. }
  2762. ExprResult
  2763. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  2764. tok::TokenKind Kind, Expr *Input) {
  2765. UnaryOperatorKind Opc;
  2766. switch (Kind) {
  2767. default: llvm_unreachable("Unknown unary op!");
  2768. case tok::plusplus: Opc = UO_PostInc; break;
  2769. case tok::minusminus: Opc = UO_PostDec; break;
  2770. }
  2771. // Since this might is a postfix expression, get rid of ParenListExprs.
  2772. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  2773. if (Result.isInvalid()) return ExprError();
  2774. Input = Result.take();
  2775. return BuildUnaryOp(S, OpLoc, Opc, Input);
  2776. }
  2777. /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
  2778. ///
  2779. /// \return true on error
  2780. static bool checkArithmeticOnObjCPointer(Sema &S,
  2781. SourceLocation opLoc,
  2782. Expr *op) {
  2783. assert(op->getType()->isObjCObjectPointerType());
  2784. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
  2785. return false;
  2786. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  2787. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  2788. << op->getSourceRange();
  2789. return true;
  2790. }
  2791. ExprResult
  2792. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
  2793. Expr *Idx, SourceLocation RLoc) {
  2794. // Since this might be a postfix expression, get rid of ParenListExprs.
  2795. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
  2796. if (Result.isInvalid()) return ExprError();
  2797. Base = Result.take();
  2798. Expr *LHSExp = Base, *RHSExp = Idx;
  2799. if (getLangOpts().CPlusPlus &&
  2800. (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
  2801. return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
  2802. Context.DependentTy,
  2803. VK_LValue, OK_Ordinary,
  2804. RLoc));
  2805. }
  2806. if (getLangOpts().CPlusPlus &&
  2807. (LHSExp->getType()->isRecordType() ||
  2808. LHSExp->getType()->isEnumeralType() ||
  2809. RHSExp->getType()->isRecordType() ||
  2810. RHSExp->getType()->isEnumeralType()) &&
  2811. !LHSExp->getType()->isObjCObjectPointerType()) {
  2812. return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
  2813. }
  2814. return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
  2815. }
  2816. ExprResult
  2817. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  2818. Expr *Idx, SourceLocation RLoc) {
  2819. Expr *LHSExp = Base;
  2820. Expr *RHSExp = Idx;
  2821. // Perform default conversions.
  2822. if (!LHSExp->getType()->getAs<VectorType>()) {
  2823. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  2824. if (Result.isInvalid())
  2825. return ExprError();
  2826. LHSExp = Result.take();
  2827. }
  2828. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  2829. if (Result.isInvalid())
  2830. return ExprError();
  2831. RHSExp = Result.take();
  2832. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  2833. ExprValueKind VK = VK_LValue;
  2834. ExprObjectKind OK = OK_Ordinary;
  2835. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  2836. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  2837. // in the subscript position. As a result, we need to derive the array base
  2838. // and index from the expression types.
  2839. Expr *BaseExpr, *IndexExpr;
  2840. QualType ResultType;
  2841. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  2842. BaseExpr = LHSExp;
  2843. IndexExpr = RHSExp;
  2844. ResultType = Context.DependentTy;
  2845. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  2846. BaseExpr = LHSExp;
  2847. IndexExpr = RHSExp;
  2848. ResultType = PTy->getPointeeType();
  2849. } else if (const ObjCObjectPointerType *PTy =
  2850. LHSTy->getAs<ObjCObjectPointerType>()) {
  2851. BaseExpr = LHSExp;
  2852. IndexExpr = RHSExp;
  2853. // Use custom logic if this should be the pseudo-object subscript
  2854. // expression.
  2855. if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
  2856. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
  2857. ResultType = PTy->getPointeeType();
  2858. if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
  2859. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  2860. << ResultType << BaseExpr->getSourceRange();
  2861. return ExprError();
  2862. }
  2863. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  2864. // Handle the uncommon case of "123[Ptr]".
  2865. BaseExpr = RHSExp;
  2866. IndexExpr = LHSExp;
  2867. ResultType = PTy->getPointeeType();
  2868. } else if (const ObjCObjectPointerType *PTy =
  2869. RHSTy->getAs<ObjCObjectPointerType>()) {
  2870. // Handle the uncommon case of "123[Ptr]".
  2871. BaseExpr = RHSExp;
  2872. IndexExpr = LHSExp;
  2873. ResultType = PTy->getPointeeType();
  2874. if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
  2875. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  2876. << ResultType << BaseExpr->getSourceRange();
  2877. return ExprError();
  2878. }
  2879. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  2880. BaseExpr = LHSExp; // vectors: V[123]
  2881. IndexExpr = RHSExp;
  2882. VK = LHSExp->getValueKind();
  2883. if (VK != VK_RValue)
  2884. OK = OK_VectorComponent;
  2885. // FIXME: need to deal with const...
  2886. ResultType = VTy->getElementType();
  2887. } else if (LHSTy->isArrayType()) {
  2888. // If we see an array that wasn't promoted by
  2889. // DefaultFunctionArrayLvalueConversion, it must be an array that
  2890. // wasn't promoted because of the C90 rule that doesn't
  2891. // allow promoting non-lvalue arrays. Warn, then
  2892. // force the promotion here.
  2893. Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  2894. LHSExp->getSourceRange();
  2895. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  2896. CK_ArrayToPointerDecay).take();
  2897. LHSTy = LHSExp->getType();
  2898. BaseExpr = LHSExp;
  2899. IndexExpr = RHSExp;
  2900. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  2901. } else if (RHSTy->isArrayType()) {
  2902. // Same as previous, except for 123[f().a] case
  2903. Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  2904. RHSExp->getSourceRange();
  2905. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  2906. CK_ArrayToPointerDecay).take();
  2907. RHSTy = RHSExp->getType();
  2908. BaseExpr = RHSExp;
  2909. IndexExpr = LHSExp;
  2910. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  2911. } else {
  2912. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  2913. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  2914. }
  2915. // C99 6.5.2.1p1
  2916. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  2917. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  2918. << IndexExpr->getSourceRange());
  2919. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  2920. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  2921. && !IndexExpr->isTypeDependent())
  2922. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  2923. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  2924. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  2925. // type. Note that Functions are not objects, and that (in C99 parlance)
  2926. // incomplete types are not object types.
  2927. if (ResultType->isFunctionType()) {
  2928. Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
  2929. << ResultType << BaseExpr->getSourceRange();
  2930. return ExprError();
  2931. }
  2932. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  2933. // GNU extension: subscripting on pointer to void
  2934. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  2935. << BaseExpr->getSourceRange();
  2936. // C forbids expressions of unqualified void type from being l-values.
  2937. // See IsCForbiddenLValueType.
  2938. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  2939. } else if (!ResultType->isDependentType() &&
  2940. RequireCompleteType(LLoc, ResultType,
  2941. diag::err_subscript_incomplete_type, BaseExpr))
  2942. return ExprError();
  2943. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  2944. !ResultType.isCForbiddenLValueType());
  2945. return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
  2946. ResultType, VK, OK, RLoc));
  2947. }
  2948. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  2949. FunctionDecl *FD,
  2950. ParmVarDecl *Param) {
  2951. if (Param->hasUnparsedDefaultArg()) {
  2952. Diag(CallLoc,
  2953. diag::err_use_of_default_argument_to_function_declared_later) <<
  2954. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  2955. Diag(UnparsedDefaultArgLocs[Param],
  2956. diag::note_default_argument_declared_here);
  2957. return ExprError();
  2958. }
  2959. if (Param->hasUninstantiatedDefaultArg()) {
  2960. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  2961. EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
  2962. Param);
  2963. // Instantiate the expression.
  2964. MultiLevelTemplateArgumentList ArgList
  2965. = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
  2966. std::pair<const TemplateArgument *, unsigned> Innermost
  2967. = ArgList.getInnermost();
  2968. InstantiatingTemplate Inst(*this, CallLoc, Param,
  2969. ArrayRef<TemplateArgument>(Innermost.first,
  2970. Innermost.second));
  2971. if (Inst)
  2972. return ExprError();
  2973. ExprResult Result;
  2974. {
  2975. // C++ [dcl.fct.default]p5:
  2976. // The names in the [default argument] expression are bound, and
  2977. // the semantic constraints are checked, at the point where the
  2978. // default argument expression appears.
  2979. ContextRAII SavedContext(*this, FD);
  2980. LocalInstantiationScope Local(*this);
  2981. Result = SubstExpr(UninstExpr, ArgList);
  2982. }
  2983. if (Result.isInvalid())
  2984. return ExprError();
  2985. // Check the expression as an initializer for the parameter.
  2986. InitializedEntity Entity
  2987. = InitializedEntity::InitializeParameter(Context, Param);
  2988. InitializationKind Kind
  2989. = InitializationKind::CreateCopy(Param->getLocation(),
  2990. /*FIXME:EqualLoc*/UninstExpr->getLocStart());
  2991. Expr *ResultE = Result.takeAs<Expr>();
  2992. InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
  2993. Result = InitSeq.Perform(*this, Entity, Kind,
  2994. MultiExprArg(*this, &ResultE, 1));
  2995. if (Result.isInvalid())
  2996. return ExprError();
  2997. Expr *Arg = Result.takeAs<Expr>();
  2998. CheckImplicitConversions(Arg, Param->getOuterLocStart());
  2999. // Build the default argument expression.
  3000. return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
  3001. }
  3002. // If the default expression creates temporaries, we need to
  3003. // push them to the current stack of expression temporaries so they'll
  3004. // be properly destroyed.
  3005. // FIXME: We should really be rebuilding the default argument with new
  3006. // bound temporaries; see the comment in PR5810.
  3007. // We don't need to do that with block decls, though, because
  3008. // blocks in default argument expression can never capture anything.
  3009. if (isa<ExprWithCleanups>(Param->getInit())) {
  3010. // Set the "needs cleanups" bit regardless of whether there are
  3011. // any explicit objects.
  3012. ExprNeedsCleanups = true;
  3013. // Append all the objects to the cleanup list. Right now, this
  3014. // should always be a no-op, because blocks in default argument
  3015. // expressions should never be able to capture anything.
  3016. assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
  3017. "default argument expression has capturing blocks?");
  3018. }
  3019. // We already type-checked the argument, so we know it works.
  3020. // Just mark all of the declarations in this potentially-evaluated expression
  3021. // as being "referenced".
  3022. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  3023. /*SkipLocalVariables=*/true);
  3024. return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
  3025. }
  3026. Sema::VariadicCallType
  3027. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  3028. Expr *Fn) {
  3029. if (Proto && Proto->isVariadic()) {
  3030. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  3031. return VariadicConstructor;
  3032. else if (Fn && Fn->getType()->isBlockPointerType())
  3033. return VariadicBlock;
  3034. else if (FDecl) {
  3035. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  3036. if (Method->isInstance())
  3037. return VariadicMethod;
  3038. }
  3039. return VariadicFunction;
  3040. }
  3041. return VariadicDoesNotApply;
  3042. }
  3043. /// ConvertArgumentsForCall - Converts the arguments specified in
  3044. /// Args/NumArgs to the parameter types of the function FDecl with
  3045. /// function prototype Proto. Call is the call expression itself, and
  3046. /// Fn is the function expression. For a C++ member function, this
  3047. /// routine does not attempt to convert the object argument. Returns
  3048. /// true if the call is ill-formed.
  3049. bool
  3050. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  3051. FunctionDecl *FDecl,
  3052. const FunctionProtoType *Proto,
  3053. Expr **Args, unsigned NumArgs,
  3054. SourceLocation RParenLoc,
  3055. bool IsExecConfig) {
  3056. // Bail out early if calling a builtin with custom typechecking.
  3057. // We don't need to do this in the
  3058. if (FDecl)
  3059. if (unsigned ID = FDecl->getBuiltinID())
  3060. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  3061. return false;
  3062. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  3063. // assignment, to the types of the corresponding parameter, ...
  3064. unsigned NumArgsInProto = Proto->getNumArgs();
  3065. bool Invalid = false;
  3066. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
  3067. unsigned FnKind = Fn->getType()->isBlockPointerType()
  3068. ? 1 /* block */
  3069. : (IsExecConfig ? 3 /* kernel function (exec config) */
  3070. : 0 /* function */);
  3071. // If too few arguments are available (and we don't have default
  3072. // arguments for the remaining parameters), don't make the call.
  3073. if (NumArgs < NumArgsInProto) {
  3074. if (NumArgs < MinArgs) {
  3075. if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  3076. Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
  3077. ? diag::err_typecheck_call_too_few_args_one
  3078. : diag::err_typecheck_call_too_few_args_at_least_one)
  3079. << FnKind
  3080. << FDecl->getParamDecl(0) << Fn->getSourceRange();
  3081. else
  3082. Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
  3083. ? diag::err_typecheck_call_too_few_args
  3084. : diag::err_typecheck_call_too_few_args_at_least)
  3085. << FnKind
  3086. << MinArgs << NumArgs << Fn->getSourceRange();
  3087. // Emit the location of the prototype.
  3088. if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3089. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3090. << FDecl;
  3091. return true;
  3092. }
  3093. Call->setNumArgs(Context, NumArgsInProto);
  3094. }
  3095. // If too many are passed and not variadic, error on the extras and drop
  3096. // them.
  3097. if (NumArgs > NumArgsInProto) {
  3098. if (!Proto->isVariadic()) {
  3099. if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  3100. Diag(Args[NumArgsInProto]->getLocStart(),
  3101. MinArgs == NumArgsInProto
  3102. ? diag::err_typecheck_call_too_many_args_one
  3103. : diag::err_typecheck_call_too_many_args_at_most_one)
  3104. << FnKind
  3105. << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
  3106. << SourceRange(Args[NumArgsInProto]->getLocStart(),
  3107. Args[NumArgs-1]->getLocEnd());
  3108. else
  3109. Diag(Args[NumArgsInProto]->getLocStart(),
  3110. MinArgs == NumArgsInProto
  3111. ? diag::err_typecheck_call_too_many_args
  3112. : diag::err_typecheck_call_too_many_args_at_most)
  3113. << FnKind
  3114. << NumArgsInProto << NumArgs << Fn->getSourceRange()
  3115. << SourceRange(Args[NumArgsInProto]->getLocStart(),
  3116. Args[NumArgs-1]->getLocEnd());
  3117. // Emit the location of the prototype.
  3118. if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3119. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3120. << FDecl;
  3121. // This deletes the extra arguments.
  3122. Call->setNumArgs(Context, NumArgsInProto);
  3123. return true;
  3124. }
  3125. }
  3126. SmallVector<Expr *, 8> AllArgs;
  3127. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  3128. Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
  3129. Proto, 0, Args, NumArgs, AllArgs, CallType);
  3130. if (Invalid)
  3131. return true;
  3132. unsigned TotalNumArgs = AllArgs.size();
  3133. for (unsigned i = 0; i < TotalNumArgs; ++i)
  3134. Call->setArg(i, AllArgs[i]);
  3135. return false;
  3136. }
  3137. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
  3138. FunctionDecl *FDecl,
  3139. const FunctionProtoType *Proto,
  3140. unsigned FirstProtoArg,
  3141. Expr **Args, unsigned NumArgs,
  3142. SmallVector<Expr *, 8> &AllArgs,
  3143. VariadicCallType CallType,
  3144. bool AllowExplicit) {
  3145. unsigned NumArgsInProto = Proto->getNumArgs();
  3146. unsigned NumArgsToCheck = NumArgs;
  3147. bool Invalid = false;
  3148. if (NumArgs != NumArgsInProto)
  3149. // Use default arguments for missing arguments
  3150. NumArgsToCheck = NumArgsInProto;
  3151. unsigned ArgIx = 0;
  3152. // Continue to check argument types (even if we have too few/many args).
  3153. for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
  3154. QualType ProtoArgType = Proto->getArgType(i);
  3155. Expr *Arg;
  3156. ParmVarDecl *Param;
  3157. if (ArgIx < NumArgs) {
  3158. Arg = Args[ArgIx++];
  3159. if (RequireCompleteType(Arg->getLocStart(),
  3160. ProtoArgType,
  3161. diag::err_call_incomplete_argument, Arg))
  3162. return true;
  3163. // Pass the argument
  3164. Param = 0;
  3165. if (FDecl && i < FDecl->getNumParams())
  3166. Param = FDecl->getParamDecl(i);
  3167. // Strip the unbridged-cast placeholder expression off, if applicable.
  3168. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  3169. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  3170. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  3171. Arg = stripARCUnbridgedCast(Arg);
  3172. InitializedEntity Entity =
  3173. Param? InitializedEntity::InitializeParameter(Context, Param)
  3174. : InitializedEntity::InitializeParameter(Context, ProtoArgType,
  3175. Proto->isArgConsumed(i));
  3176. ExprResult ArgE = PerformCopyInitialization(Entity,
  3177. SourceLocation(),
  3178. Owned(Arg),
  3179. /*TopLevelOfInitList=*/false,
  3180. AllowExplicit);
  3181. if (ArgE.isInvalid())
  3182. return true;
  3183. Arg = ArgE.takeAs<Expr>();
  3184. } else {
  3185. Param = FDecl->getParamDecl(i);
  3186. ExprResult ArgExpr =
  3187. BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  3188. if (ArgExpr.isInvalid())
  3189. return true;
  3190. Arg = ArgExpr.takeAs<Expr>();
  3191. }
  3192. // Check for array bounds violations for each argument to the call. This
  3193. // check only triggers warnings when the argument isn't a more complex Expr
  3194. // with its own checking, such as a BinaryOperator.
  3195. CheckArrayAccess(Arg);
  3196. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  3197. CheckStaticArrayArgument(CallLoc, Param, Arg);
  3198. AllArgs.push_back(Arg);
  3199. }
  3200. // If this is a variadic call, handle args passed through "...".
  3201. if (CallType != VariadicDoesNotApply) {
  3202. // Assume that extern "C" functions with variadic arguments that
  3203. // return __unknown_anytype aren't *really* variadic.
  3204. if (Proto->getResultType() == Context.UnknownAnyTy &&
  3205. FDecl && FDecl->isExternC()) {
  3206. for (unsigned i = ArgIx; i != NumArgs; ++i) {
  3207. ExprResult arg;
  3208. if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
  3209. arg = DefaultFunctionArrayLvalueConversion(Args[i]);
  3210. else
  3211. arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
  3212. Invalid |= arg.isInvalid();
  3213. AllArgs.push_back(arg.take());
  3214. }
  3215. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  3216. } else {
  3217. for (unsigned i = ArgIx; i != NumArgs; ++i) {
  3218. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
  3219. FDecl);
  3220. Invalid |= Arg.isInvalid();
  3221. AllArgs.push_back(Arg.take());
  3222. }
  3223. }
  3224. // Check for array bounds violations.
  3225. for (unsigned i = ArgIx; i != NumArgs; ++i)
  3226. CheckArrayAccess(Args[i]);
  3227. }
  3228. return Invalid;
  3229. }
  3230. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  3231. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  3232. if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
  3233. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  3234. << ATL->getLocalSourceRange();
  3235. }
  3236. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  3237. /// array parameter, check that it is non-null, and that if it is formed by
  3238. /// array-to-pointer decay, the underlying array is sufficiently large.
  3239. ///
  3240. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  3241. /// array type derivation, then for each call to the function, the value of the
  3242. /// corresponding actual argument shall provide access to the first element of
  3243. /// an array with at least as many elements as specified by the size expression.
  3244. void
  3245. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  3246. ParmVarDecl *Param,
  3247. const Expr *ArgExpr) {
  3248. // Static array parameters are not supported in C++.
  3249. if (!Param || getLangOpts().CPlusPlus)
  3250. return;
  3251. QualType OrigTy = Param->getOriginalType();
  3252. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  3253. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  3254. return;
  3255. if (ArgExpr->isNullPointerConstant(Context,
  3256. Expr::NPC_NeverValueDependent)) {
  3257. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  3258. DiagnoseCalleeStaticArrayParam(*this, Param);
  3259. return;
  3260. }
  3261. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  3262. if (!CAT)
  3263. return;
  3264. const ConstantArrayType *ArgCAT =
  3265. Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
  3266. if (!ArgCAT)
  3267. return;
  3268. if (ArgCAT->getSize().ult(CAT->getSize())) {
  3269. Diag(CallLoc, diag::warn_static_array_too_small)
  3270. << ArgExpr->getSourceRange()
  3271. << (unsigned) ArgCAT->getSize().getZExtValue()
  3272. << (unsigned) CAT->getSize().getZExtValue();
  3273. DiagnoseCalleeStaticArrayParam(*this, Param);
  3274. }
  3275. }
  3276. /// Given a function expression of unknown-any type, try to rebuild it
  3277. /// to have a function type.
  3278. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  3279. /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
  3280. /// This provides the location of the left/right parens and a list of comma
  3281. /// locations.
  3282. ExprResult
  3283. Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
  3284. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  3285. Expr *ExecConfig, bool IsExecConfig) {
  3286. unsigned NumArgs = ArgExprs.size();
  3287. // Since this might be a postfix expression, get rid of ParenListExprs.
  3288. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
  3289. if (Result.isInvalid()) return ExprError();
  3290. Fn = Result.take();
  3291. Expr **Args = ArgExprs.get();
  3292. if (getLangOpts().CPlusPlus) {
  3293. // If this is a pseudo-destructor expression, build the call immediately.
  3294. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  3295. if (NumArgs > 0) {
  3296. // Pseudo-destructor calls should not have any arguments.
  3297. Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
  3298. << FixItHint::CreateRemoval(
  3299. SourceRange(Args[0]->getLocStart(),
  3300. Args[NumArgs-1]->getLocEnd()));
  3301. }
  3302. return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
  3303. VK_RValue, RParenLoc));
  3304. }
  3305. // Determine whether this is a dependent call inside a C++ template,
  3306. // in which case we won't do any semantic analysis now.
  3307. // FIXME: Will need to cache the results of name lookup (including ADL) in
  3308. // Fn.
  3309. bool Dependent = false;
  3310. if (Fn->isTypeDependent())
  3311. Dependent = true;
  3312. else if (Expr::hasAnyTypeDependentArguments(
  3313. llvm::makeArrayRef(Args, NumArgs)))
  3314. Dependent = true;
  3315. if (Dependent) {
  3316. if (ExecConfig) {
  3317. return Owned(new (Context) CUDAKernelCallExpr(
  3318. Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
  3319. Context.DependentTy, VK_RValue, RParenLoc));
  3320. } else {
  3321. return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
  3322. Context.DependentTy, VK_RValue,
  3323. RParenLoc));
  3324. }
  3325. }
  3326. // Determine whether this is a call to an object (C++ [over.call.object]).
  3327. if (Fn->getType()->isRecordType())
  3328. return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
  3329. RParenLoc));
  3330. if (Fn->getType() == Context.UnknownAnyTy) {
  3331. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  3332. if (result.isInvalid()) return ExprError();
  3333. Fn = result.take();
  3334. }
  3335. if (Fn->getType() == Context.BoundMemberTy) {
  3336. return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
  3337. RParenLoc);
  3338. }
  3339. }
  3340. // Check for overloaded calls. This can happen even in C due to extensions.
  3341. if (Fn->getType() == Context.OverloadTy) {
  3342. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  3343. // We aren't supposed to apply this logic for if there's an '&' involved.
  3344. if (!find.HasFormOfMemberPointer) {
  3345. OverloadExpr *ovl = find.Expression;
  3346. if (isa<UnresolvedLookupExpr>(ovl)) {
  3347. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
  3348. return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
  3349. RParenLoc, ExecConfig);
  3350. } else {
  3351. return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
  3352. RParenLoc);
  3353. }
  3354. }
  3355. }
  3356. // If we're directly calling a function, get the appropriate declaration.
  3357. if (Fn->getType() == Context.UnknownAnyTy) {
  3358. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  3359. if (result.isInvalid()) return ExprError();
  3360. Fn = result.take();
  3361. }
  3362. Expr *NakedFn = Fn->IgnoreParens();
  3363. NamedDecl *NDecl = 0;
  3364. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
  3365. if (UnOp->getOpcode() == UO_AddrOf)
  3366. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  3367. if (isa<DeclRefExpr>(NakedFn))
  3368. NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
  3369. else if (isa<MemberExpr>(NakedFn))
  3370. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  3371. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
  3372. ExecConfig, IsExecConfig);
  3373. }
  3374. ExprResult
  3375. Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
  3376. MultiExprArg ExecConfig, SourceLocation GGGLoc) {
  3377. FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
  3378. if (!ConfigDecl)
  3379. return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
  3380. << "cudaConfigureCall");
  3381. QualType ConfigQTy = ConfigDecl->getType();
  3382. DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
  3383. ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
  3384. MarkFunctionReferenced(LLLLoc, ConfigDecl);
  3385. return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
  3386. /*IsExecConfig=*/true);
  3387. }
  3388. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  3389. ///
  3390. /// __builtin_astype( value, dst type )
  3391. ///
  3392. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  3393. SourceLocation BuiltinLoc,
  3394. SourceLocation RParenLoc) {
  3395. ExprValueKind VK = VK_RValue;
  3396. ExprObjectKind OK = OK_Ordinary;
  3397. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  3398. QualType SrcTy = E->getType();
  3399. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  3400. return ExprError(Diag(BuiltinLoc,
  3401. diag::err_invalid_astype_of_different_size)
  3402. << DstTy
  3403. << SrcTy
  3404. << E->getSourceRange());
  3405. return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
  3406. RParenLoc));
  3407. }
  3408. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  3409. /// i.e. an expression not of \p OverloadTy. The expression should
  3410. /// unary-convert to an expression of function-pointer or
  3411. /// block-pointer type.
  3412. ///
  3413. /// \param NDecl the declaration being called, if available
  3414. ExprResult
  3415. Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  3416. SourceLocation LParenLoc,
  3417. Expr **Args, unsigned NumArgs,
  3418. SourceLocation RParenLoc,
  3419. Expr *Config, bool IsExecConfig) {
  3420. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  3421. // Promote the function operand.
  3422. ExprResult Result = UsualUnaryConversions(Fn);
  3423. if (Result.isInvalid())
  3424. return ExprError();
  3425. Fn = Result.take();
  3426. // Make the call expr early, before semantic checks. This guarantees cleanup
  3427. // of arguments and function on error.
  3428. CallExpr *TheCall;
  3429. if (Config)
  3430. TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
  3431. cast<CallExpr>(Config),
  3432. Args, NumArgs,
  3433. Context.BoolTy,
  3434. VK_RValue,
  3435. RParenLoc);
  3436. else
  3437. TheCall = new (Context) CallExpr(Context, Fn,
  3438. Args, NumArgs,
  3439. Context.BoolTy,
  3440. VK_RValue,
  3441. RParenLoc);
  3442. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  3443. // Bail out early if calling a builtin with custom typechecking.
  3444. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  3445. return CheckBuiltinFunctionCall(BuiltinID, TheCall);
  3446. retry:
  3447. const FunctionType *FuncT;
  3448. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  3449. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  3450. // have type pointer to function".
  3451. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  3452. if (FuncT == 0)
  3453. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  3454. << Fn->getType() << Fn->getSourceRange());
  3455. } else if (const BlockPointerType *BPT =
  3456. Fn->getType()->getAs<BlockPointerType>()) {
  3457. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  3458. } else {
  3459. // Handle calls to expressions of unknown-any type.
  3460. if (Fn->getType() == Context.UnknownAnyTy) {
  3461. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  3462. if (rewrite.isInvalid()) return ExprError();
  3463. Fn = rewrite.take();
  3464. TheCall->setCallee(Fn);
  3465. goto retry;
  3466. }
  3467. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  3468. << Fn->getType() << Fn->getSourceRange());
  3469. }
  3470. if (getLangOpts().CUDA) {
  3471. if (Config) {
  3472. // CUDA: Kernel calls must be to global functions
  3473. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  3474. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  3475. << FDecl->getName() << Fn->getSourceRange());
  3476. // CUDA: Kernel function must have 'void' return type
  3477. if (!FuncT->getResultType()->isVoidType())
  3478. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  3479. << Fn->getType() << Fn->getSourceRange());
  3480. } else {
  3481. // CUDA: Calls to global functions must be configured
  3482. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  3483. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  3484. << FDecl->getName() << Fn->getSourceRange());
  3485. }
  3486. }
  3487. // Check for a valid return type
  3488. if (CheckCallReturnType(FuncT->getResultType(),
  3489. Fn->getLocStart(), TheCall,
  3490. FDecl))
  3491. return ExprError();
  3492. // We know the result type of the call, set it.
  3493. TheCall->setType(FuncT->getCallResultType(Context));
  3494. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
  3495. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
  3496. if (Proto) {
  3497. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
  3498. RParenLoc, IsExecConfig))
  3499. return ExprError();
  3500. } else {
  3501. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  3502. if (FDecl) {
  3503. // Check if we have too few/too many template arguments, based
  3504. // on our knowledge of the function definition.
  3505. const FunctionDecl *Def = 0;
  3506. if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
  3507. Proto = Def->getType()->getAs<FunctionProtoType>();
  3508. if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
  3509. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  3510. << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
  3511. }
  3512. // If the function we're calling isn't a function prototype, but we have
  3513. // a function prototype from a prior declaratiom, use that prototype.
  3514. if (!FDecl->hasPrototype())
  3515. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  3516. }
  3517. // Promote the arguments (C99 6.5.2.2p6).
  3518. for (unsigned i = 0; i != NumArgs; i++) {
  3519. Expr *Arg = Args[i];
  3520. if (Proto && i < Proto->getNumArgs()) {
  3521. InitializedEntity Entity
  3522. = InitializedEntity::InitializeParameter(Context,
  3523. Proto->getArgType(i),
  3524. Proto->isArgConsumed(i));
  3525. ExprResult ArgE = PerformCopyInitialization(Entity,
  3526. SourceLocation(),
  3527. Owned(Arg));
  3528. if (ArgE.isInvalid())
  3529. return true;
  3530. Arg = ArgE.takeAs<Expr>();
  3531. } else {
  3532. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  3533. if (ArgE.isInvalid())
  3534. return true;
  3535. Arg = ArgE.takeAs<Expr>();
  3536. }
  3537. if (RequireCompleteType(Arg->getLocStart(),
  3538. Arg->getType(),
  3539. diag::err_call_incomplete_argument, Arg))
  3540. return ExprError();
  3541. TheCall->setArg(i, Arg);
  3542. }
  3543. }
  3544. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  3545. if (!Method->isStatic())
  3546. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  3547. << Fn->getSourceRange());
  3548. // Check for sentinels
  3549. if (NDecl)
  3550. DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
  3551. // Do special checking on direct calls to functions.
  3552. if (FDecl) {
  3553. if (CheckFunctionCall(FDecl, TheCall, Proto))
  3554. return ExprError();
  3555. if (BuiltinID)
  3556. return CheckBuiltinFunctionCall(BuiltinID, TheCall);
  3557. } else if (NDecl) {
  3558. if (CheckBlockCall(NDecl, TheCall, Proto))
  3559. return ExprError();
  3560. }
  3561. return MaybeBindToTemporary(TheCall);
  3562. }
  3563. ExprResult
  3564. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  3565. SourceLocation RParenLoc, Expr *InitExpr) {
  3566. assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
  3567. // FIXME: put back this assert when initializers are worked out.
  3568. //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
  3569. TypeSourceInfo *TInfo;
  3570. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  3571. if (!TInfo)
  3572. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  3573. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  3574. }
  3575. ExprResult
  3576. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  3577. SourceLocation RParenLoc, Expr *LiteralExpr) {
  3578. QualType literalType = TInfo->getType();
  3579. if (literalType->isArrayType()) {
  3580. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  3581. diag::err_illegal_decl_array_incomplete_type,
  3582. SourceRange(LParenLoc,
  3583. LiteralExpr->getSourceRange().getEnd())))
  3584. return ExprError();
  3585. if (literalType->isVariableArrayType())
  3586. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  3587. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  3588. } else if (!literalType->isDependentType() &&
  3589. RequireCompleteType(LParenLoc, literalType,
  3590. diag::err_typecheck_decl_incomplete_type,
  3591. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  3592. return ExprError();
  3593. InitializedEntity Entity
  3594. = InitializedEntity::InitializeTemporary(literalType);
  3595. InitializationKind Kind
  3596. = InitializationKind::CreateCStyleCast(LParenLoc,
  3597. SourceRange(LParenLoc, RParenLoc),
  3598. /*InitList=*/true);
  3599. InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
  3600. ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
  3601. MultiExprArg(*this, &LiteralExpr, 1),
  3602. &literalType);
  3603. if (Result.isInvalid())
  3604. return ExprError();
  3605. LiteralExpr = Result.get();
  3606. bool isFileScope = getCurFunctionOrMethodDecl() == 0;
  3607. if (isFileScope) { // 6.5.2.5p3
  3608. if (CheckForConstantInitializer(LiteralExpr, literalType))
  3609. return ExprError();
  3610. }
  3611. // In C, compound literals are l-values for some reason.
  3612. ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
  3613. return MaybeBindToTemporary(
  3614. new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  3615. VK, LiteralExpr, isFileScope));
  3616. }
  3617. ExprResult
  3618. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  3619. SourceLocation RBraceLoc) {
  3620. unsigned NumInit = InitArgList.size();
  3621. Expr **InitList = InitArgList.get();
  3622. // Immediately handle non-overload placeholders. Overloads can be
  3623. // resolved contextually, but everything else here can't.
  3624. for (unsigned I = 0; I != NumInit; ++I) {
  3625. if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
  3626. ExprResult result = CheckPlaceholderExpr(InitList[I]);
  3627. // Ignore failures; dropping the entire initializer list because
  3628. // of one failure would be terrible for indexing/etc.
  3629. if (result.isInvalid()) continue;
  3630. InitList[I] = result.take();
  3631. }
  3632. }
  3633. // Semantic analysis for initializers is done by ActOnDeclarator() and
  3634. // CheckInitializer() - it requires knowledge of the object being intialized.
  3635. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
  3636. NumInit, RBraceLoc);
  3637. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  3638. return Owned(E);
  3639. }
  3640. /// Do an explicit extend of the given block pointer if we're in ARC.
  3641. static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
  3642. assert(E.get()->getType()->isBlockPointerType());
  3643. assert(E.get()->isRValue());
  3644. // Only do this in an r-value context.
  3645. if (!S.getLangOpts().ObjCAutoRefCount) return;
  3646. E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
  3647. CK_ARCExtendBlockObject, E.get(),
  3648. /*base path*/ 0, VK_RValue);
  3649. S.ExprNeedsCleanups = true;
  3650. }
  3651. /// Prepare a conversion of the given expression to an ObjC object
  3652. /// pointer type.
  3653. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  3654. QualType type = E.get()->getType();
  3655. if (type->isObjCObjectPointerType()) {
  3656. return CK_BitCast;
  3657. } else if (type->isBlockPointerType()) {
  3658. maybeExtendBlockObject(*this, E);
  3659. return CK_BlockPointerToObjCPointerCast;
  3660. } else {
  3661. assert(type->isPointerType());
  3662. return CK_CPointerToObjCPointerCast;
  3663. }
  3664. }
  3665. /// Prepares for a scalar cast, performing all the necessary stages
  3666. /// except the final cast and returning the kind required.
  3667. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  3668. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  3669. // Also, callers should have filtered out the invalid cases with
  3670. // pointers. Everything else should be possible.
  3671. QualType SrcTy = Src.get()->getType();
  3672. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  3673. return CK_NoOp;
  3674. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  3675. case Type::STK_MemberPointer:
  3676. llvm_unreachable("member pointer type in C");
  3677. case Type::STK_CPointer:
  3678. case Type::STK_BlockPointer:
  3679. case Type::STK_ObjCObjectPointer:
  3680. switch (DestTy->getScalarTypeKind()) {
  3681. case Type::STK_CPointer:
  3682. return CK_BitCast;
  3683. case Type::STK_BlockPointer:
  3684. return (SrcKind == Type::STK_BlockPointer
  3685. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  3686. case Type::STK_ObjCObjectPointer:
  3687. if (SrcKind == Type::STK_ObjCObjectPointer)
  3688. return CK_BitCast;
  3689. if (SrcKind == Type::STK_CPointer)
  3690. return CK_CPointerToObjCPointerCast;
  3691. maybeExtendBlockObject(*this, Src);
  3692. return CK_BlockPointerToObjCPointerCast;
  3693. case Type::STK_Bool:
  3694. return CK_PointerToBoolean;
  3695. case Type::STK_Integral:
  3696. return CK_PointerToIntegral;
  3697. case Type::STK_Floating:
  3698. case Type::STK_FloatingComplex:
  3699. case Type::STK_IntegralComplex:
  3700. case Type::STK_MemberPointer:
  3701. llvm_unreachable("illegal cast from pointer");
  3702. }
  3703. llvm_unreachable("Should have returned before this");
  3704. case Type::STK_Bool: // casting from bool is like casting from an integer
  3705. case Type::STK_Integral:
  3706. switch (DestTy->getScalarTypeKind()) {
  3707. case Type::STK_CPointer:
  3708. case Type::STK_ObjCObjectPointer:
  3709. case Type::STK_BlockPointer:
  3710. if (Src.get()->isNullPointerConstant(Context,
  3711. Expr::NPC_ValueDependentIsNull))
  3712. return CK_NullToPointer;
  3713. return CK_IntegralToPointer;
  3714. case Type::STK_Bool:
  3715. return CK_IntegralToBoolean;
  3716. case Type::STK_Integral:
  3717. return CK_IntegralCast;
  3718. case Type::STK_Floating:
  3719. return CK_IntegralToFloating;
  3720. case Type::STK_IntegralComplex:
  3721. Src = ImpCastExprToType(Src.take(),
  3722. DestTy->castAs<ComplexType>()->getElementType(),
  3723. CK_IntegralCast);
  3724. return CK_IntegralRealToComplex;
  3725. case Type::STK_FloatingComplex:
  3726. Src = ImpCastExprToType(Src.take(),
  3727. DestTy->castAs<ComplexType>()->getElementType(),
  3728. CK_IntegralToFloating);
  3729. return CK_FloatingRealToComplex;
  3730. case Type::STK_MemberPointer:
  3731. llvm_unreachable("member pointer type in C");
  3732. }
  3733. llvm_unreachable("Should have returned before this");
  3734. case Type::STK_Floating:
  3735. switch (DestTy->getScalarTypeKind()) {
  3736. case Type::STK_Floating:
  3737. return CK_FloatingCast;
  3738. case Type::STK_Bool:
  3739. return CK_FloatingToBoolean;
  3740. case Type::STK_Integral:
  3741. return CK_FloatingToIntegral;
  3742. case Type::STK_FloatingComplex:
  3743. Src = ImpCastExprToType(Src.take(),
  3744. DestTy->castAs<ComplexType>()->getElementType(),
  3745. CK_FloatingCast);
  3746. return CK_FloatingRealToComplex;
  3747. case Type::STK_IntegralComplex:
  3748. Src = ImpCastExprToType(Src.take(),
  3749. DestTy->castAs<ComplexType>()->getElementType(),
  3750. CK_FloatingToIntegral);
  3751. return CK_IntegralRealToComplex;
  3752. case Type::STK_CPointer:
  3753. case Type::STK_ObjCObjectPointer:
  3754. case Type::STK_BlockPointer:
  3755. llvm_unreachable("valid float->pointer cast?");
  3756. case Type::STK_MemberPointer:
  3757. llvm_unreachable("member pointer type in C");
  3758. }
  3759. llvm_unreachable("Should have returned before this");
  3760. case Type::STK_FloatingComplex:
  3761. switch (DestTy->getScalarTypeKind()) {
  3762. case Type::STK_FloatingComplex:
  3763. return CK_FloatingComplexCast;
  3764. case Type::STK_IntegralComplex:
  3765. return CK_FloatingComplexToIntegralComplex;
  3766. case Type::STK_Floating: {
  3767. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  3768. if (Context.hasSameType(ET, DestTy))
  3769. return CK_FloatingComplexToReal;
  3770. Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
  3771. return CK_FloatingCast;
  3772. }
  3773. case Type::STK_Bool:
  3774. return CK_FloatingComplexToBoolean;
  3775. case Type::STK_Integral:
  3776. Src = ImpCastExprToType(Src.take(),
  3777. SrcTy->castAs<ComplexType>()->getElementType(),
  3778. CK_FloatingComplexToReal);
  3779. return CK_FloatingToIntegral;
  3780. case Type::STK_CPointer:
  3781. case Type::STK_ObjCObjectPointer:
  3782. case Type::STK_BlockPointer:
  3783. llvm_unreachable("valid complex float->pointer cast?");
  3784. case Type::STK_MemberPointer:
  3785. llvm_unreachable("member pointer type in C");
  3786. }
  3787. llvm_unreachable("Should have returned before this");
  3788. case Type::STK_IntegralComplex:
  3789. switch (DestTy->getScalarTypeKind()) {
  3790. case Type::STK_FloatingComplex:
  3791. return CK_IntegralComplexToFloatingComplex;
  3792. case Type::STK_IntegralComplex:
  3793. return CK_IntegralComplexCast;
  3794. case Type::STK_Integral: {
  3795. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  3796. if (Context.hasSameType(ET, DestTy))
  3797. return CK_IntegralComplexToReal;
  3798. Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
  3799. return CK_IntegralCast;
  3800. }
  3801. case Type::STK_Bool:
  3802. return CK_IntegralComplexToBoolean;
  3803. case Type::STK_Floating:
  3804. Src = ImpCastExprToType(Src.take(),
  3805. SrcTy->castAs<ComplexType>()->getElementType(),
  3806. CK_IntegralComplexToReal);
  3807. return CK_IntegralToFloating;
  3808. case Type::STK_CPointer:
  3809. case Type::STK_ObjCObjectPointer:
  3810. case Type::STK_BlockPointer:
  3811. llvm_unreachable("valid complex int->pointer cast?");
  3812. case Type::STK_MemberPointer:
  3813. llvm_unreachable("member pointer type in C");
  3814. }
  3815. llvm_unreachable("Should have returned before this");
  3816. }
  3817. llvm_unreachable("Unhandled scalar cast");
  3818. }
  3819. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  3820. CastKind &Kind) {
  3821. assert(VectorTy->isVectorType() && "Not a vector type!");
  3822. if (Ty->isVectorType() || Ty->isIntegerType()) {
  3823. if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
  3824. return Diag(R.getBegin(),
  3825. Ty->isVectorType() ?
  3826. diag::err_invalid_conversion_between_vectors :
  3827. diag::err_invalid_conversion_between_vector_and_integer)
  3828. << VectorTy << Ty << R;
  3829. } else
  3830. return Diag(R.getBegin(),
  3831. diag::err_invalid_conversion_between_vector_and_scalar)
  3832. << VectorTy << Ty << R;
  3833. Kind = CK_BitCast;
  3834. return false;
  3835. }
  3836. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  3837. Expr *CastExpr, CastKind &Kind) {
  3838. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  3839. QualType SrcTy = CastExpr->getType();
  3840. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  3841. // an ExtVectorType.
  3842. // In OpenCL, casts between vectors of different types are not allowed.
  3843. // (See OpenCL 6.2).
  3844. if (SrcTy->isVectorType()) {
  3845. if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
  3846. || (getLangOpts().OpenCL &&
  3847. (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
  3848. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  3849. << DestTy << SrcTy << R;
  3850. return ExprError();
  3851. }
  3852. Kind = CK_BitCast;
  3853. return Owned(CastExpr);
  3854. }
  3855. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  3856. // conversion will take place first from scalar to elt type, and then
  3857. // splat from elt type to vector.
  3858. if (SrcTy->isPointerType())
  3859. return Diag(R.getBegin(),
  3860. diag::err_invalid_conversion_between_vector_and_scalar)
  3861. << DestTy << SrcTy << R;
  3862. QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
  3863. ExprResult CastExprRes = Owned(CastExpr);
  3864. CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
  3865. if (CastExprRes.isInvalid())
  3866. return ExprError();
  3867. CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
  3868. Kind = CK_VectorSplat;
  3869. return Owned(CastExpr);
  3870. }
  3871. ExprResult
  3872. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  3873. Declarator &D, ParsedType &Ty,
  3874. SourceLocation RParenLoc, Expr *CastExpr) {
  3875. assert(!D.isInvalidType() && (CastExpr != 0) &&
  3876. "ActOnCastExpr(): missing type or expr");
  3877. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  3878. if (D.isInvalidType())
  3879. return ExprError();
  3880. if (getLangOpts().CPlusPlus) {
  3881. // Check that there are no default arguments (C++ only).
  3882. CheckExtraCXXDefaultArguments(D);
  3883. }
  3884. checkUnusedDeclAttributes(D);
  3885. QualType castType = castTInfo->getType();
  3886. Ty = CreateParsedType(castType, castTInfo);
  3887. bool isVectorLiteral = false;
  3888. // Check for an altivec or OpenCL literal,
  3889. // i.e. all the elements are integer constants.
  3890. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  3891. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  3892. if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
  3893. && castType->isVectorType() && (PE || PLE)) {
  3894. if (PLE && PLE->getNumExprs() == 0) {
  3895. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  3896. return ExprError();
  3897. }
  3898. if (PE || PLE->getNumExprs() == 1) {
  3899. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  3900. if (!E->getType()->isVectorType())
  3901. isVectorLiteral = true;
  3902. }
  3903. else
  3904. isVectorLiteral = true;
  3905. }
  3906. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  3907. // then handle it as such.
  3908. if (isVectorLiteral)
  3909. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  3910. // If the Expr being casted is a ParenListExpr, handle it specially.
  3911. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  3912. // sequence of BinOp comma operators.
  3913. if (isa<ParenListExpr>(CastExpr)) {
  3914. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  3915. if (Result.isInvalid()) return ExprError();
  3916. CastExpr = Result.take();
  3917. }
  3918. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  3919. }
  3920. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  3921. SourceLocation RParenLoc, Expr *E,
  3922. TypeSourceInfo *TInfo) {
  3923. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  3924. "Expected paren or paren list expression");
  3925. Expr **exprs;
  3926. unsigned numExprs;
  3927. Expr *subExpr;
  3928. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  3929. exprs = PE->getExprs();
  3930. numExprs = PE->getNumExprs();
  3931. } else {
  3932. subExpr = cast<ParenExpr>(E)->getSubExpr();
  3933. exprs = &subExpr;
  3934. numExprs = 1;
  3935. }
  3936. QualType Ty = TInfo->getType();
  3937. assert(Ty->isVectorType() && "Expected vector type");
  3938. SmallVector<Expr *, 8> initExprs;
  3939. const VectorType *VTy = Ty->getAs<VectorType>();
  3940. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  3941. // '(...)' form of vector initialization in AltiVec: the number of
  3942. // initializers must be one or must match the size of the vector.
  3943. // If a single value is specified in the initializer then it will be
  3944. // replicated to all the components of the vector
  3945. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  3946. // The number of initializers must be one or must match the size of the
  3947. // vector. If a single value is specified in the initializer then it will
  3948. // be replicated to all the components of the vector
  3949. if (numExprs == 1) {
  3950. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  3951. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  3952. if (Literal.isInvalid())
  3953. return ExprError();
  3954. Literal = ImpCastExprToType(Literal.take(), ElemTy,
  3955. PrepareScalarCast(Literal, ElemTy));
  3956. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
  3957. }
  3958. else if (numExprs < numElems) {
  3959. Diag(E->getExprLoc(),
  3960. diag::err_incorrect_number_of_vector_initializers);
  3961. return ExprError();
  3962. }
  3963. else
  3964. initExprs.append(exprs, exprs + numExprs);
  3965. }
  3966. else {
  3967. // For OpenCL, when the number of initializers is a single value,
  3968. // it will be replicated to all components of the vector.
  3969. if (getLangOpts().OpenCL &&
  3970. VTy->getVectorKind() == VectorType::GenericVector &&
  3971. numExprs == 1) {
  3972. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  3973. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  3974. if (Literal.isInvalid())
  3975. return ExprError();
  3976. Literal = ImpCastExprToType(Literal.take(), ElemTy,
  3977. PrepareScalarCast(Literal, ElemTy));
  3978. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
  3979. }
  3980. initExprs.append(exprs, exprs + numExprs);
  3981. }
  3982. // FIXME: This means that pretty-printing the final AST will produce curly
  3983. // braces instead of the original commas.
  3984. InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
  3985. &initExprs[0],
  3986. initExprs.size(), RParenLoc);
  3987. initE->setType(Ty);
  3988. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  3989. }
  3990. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  3991. /// the ParenListExpr into a sequence of comma binary operators.
  3992. ExprResult
  3993. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  3994. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  3995. if (!E)
  3996. return Owned(OrigExpr);
  3997. ExprResult Result(E->getExpr(0));
  3998. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  3999. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  4000. E->getExpr(i));
  4001. if (Result.isInvalid()) return ExprError();
  4002. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  4003. }
  4004. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  4005. SourceLocation R,
  4006. MultiExprArg Val) {
  4007. unsigned nexprs = Val.size();
  4008. Expr **exprs = Val.get();
  4009. assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
  4010. Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
  4011. return Owned(expr);
  4012. }
  4013. /// \brief Emit a specialized diagnostic when one expression is a null pointer
  4014. /// constant and the other is not a pointer. Returns true if a diagnostic is
  4015. /// emitted.
  4016. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  4017. SourceLocation QuestionLoc) {
  4018. Expr *NullExpr = LHSExpr;
  4019. Expr *NonPointerExpr = RHSExpr;
  4020. Expr::NullPointerConstantKind NullKind =
  4021. NullExpr->isNullPointerConstant(Context,
  4022. Expr::NPC_ValueDependentIsNotNull);
  4023. if (NullKind == Expr::NPCK_NotNull) {
  4024. NullExpr = RHSExpr;
  4025. NonPointerExpr = LHSExpr;
  4026. NullKind =
  4027. NullExpr->isNullPointerConstant(Context,
  4028. Expr::NPC_ValueDependentIsNotNull);
  4029. }
  4030. if (NullKind == Expr::NPCK_NotNull)
  4031. return false;
  4032. if (NullKind == Expr::NPCK_ZeroExpression)
  4033. return false;
  4034. if (NullKind == Expr::NPCK_ZeroLiteral) {
  4035. // In this case, check to make sure that we got here from a "NULL"
  4036. // string in the source code.
  4037. NullExpr = NullExpr->IgnoreParenImpCasts();
  4038. SourceLocation loc = NullExpr->getExprLoc();
  4039. if (!findMacroSpelling(loc, "NULL"))
  4040. return false;
  4041. }
  4042. int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
  4043. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  4044. << NonPointerExpr->getType() << DiagType
  4045. << NonPointerExpr->getSourceRange();
  4046. return true;
  4047. }
  4048. /// \brief Return false if the condition expression is valid, true otherwise.
  4049. static bool checkCondition(Sema &S, Expr *Cond) {
  4050. QualType CondTy = Cond->getType();
  4051. // C99 6.5.15p2
  4052. if (CondTy->isScalarType()) return false;
  4053. // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
  4054. if (S.getLangOpts().OpenCL && CondTy->isVectorType())
  4055. return false;
  4056. // Emit the proper error message.
  4057. S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
  4058. diag::err_typecheck_cond_expect_scalar :
  4059. diag::err_typecheck_cond_expect_scalar_or_vector)
  4060. << CondTy;
  4061. return true;
  4062. }
  4063. /// \brief Return false if the two expressions can be converted to a vector,
  4064. /// true otherwise
  4065. static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
  4066. ExprResult &RHS,
  4067. QualType CondTy) {
  4068. // Both operands should be of scalar type.
  4069. if (!LHS.get()->getType()->isScalarType()) {
  4070. S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
  4071. << CondTy;
  4072. return true;
  4073. }
  4074. if (!RHS.get()->getType()->isScalarType()) {
  4075. S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
  4076. << CondTy;
  4077. return true;
  4078. }
  4079. // Implicity convert these scalars to the type of the condition.
  4080. LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
  4081. RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
  4082. return false;
  4083. }
  4084. /// \brief Handle when one or both operands are void type.
  4085. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  4086. ExprResult &RHS) {
  4087. Expr *LHSExpr = LHS.get();
  4088. Expr *RHSExpr = RHS.get();
  4089. if (!LHSExpr->getType()->isVoidType())
  4090. S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  4091. << RHSExpr->getSourceRange();
  4092. if (!RHSExpr->getType()->isVoidType())
  4093. S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  4094. << LHSExpr->getSourceRange();
  4095. LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
  4096. RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
  4097. return S.Context.VoidTy;
  4098. }
  4099. /// \brief Return false if the NullExpr can be promoted to PointerTy,
  4100. /// true otherwise.
  4101. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  4102. QualType PointerTy) {
  4103. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  4104. !NullExpr.get()->isNullPointerConstant(S.Context,
  4105. Expr::NPC_ValueDependentIsNull))
  4106. return true;
  4107. NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
  4108. return false;
  4109. }
  4110. /// \brief Checks compatibility between two pointers and return the resulting
  4111. /// type.
  4112. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  4113. ExprResult &RHS,
  4114. SourceLocation Loc) {
  4115. QualType LHSTy = LHS.get()->getType();
  4116. QualType RHSTy = RHS.get()->getType();
  4117. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  4118. // Two identical pointers types are always compatible.
  4119. return LHSTy;
  4120. }
  4121. QualType lhptee, rhptee;
  4122. // Get the pointee types.
  4123. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  4124. lhptee = LHSBTy->getPointeeType();
  4125. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  4126. } else {
  4127. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  4128. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  4129. }
  4130. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  4131. // differently qualified versions of compatible types, the result type is
  4132. // a pointer to an appropriately qualified version of the composite
  4133. // type.
  4134. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  4135. // clause doesn't make sense for our extensions. E.g. address space 2 should
  4136. // be incompatible with address space 3: they may live on different devices or
  4137. // anything.
  4138. Qualifiers lhQual = lhptee.getQualifiers();
  4139. Qualifiers rhQual = rhptee.getQualifiers();
  4140. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  4141. lhQual.removeCVRQualifiers();
  4142. rhQual.removeCVRQualifiers();
  4143. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  4144. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  4145. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  4146. if (CompositeTy.isNull()) {
  4147. S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
  4148. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  4149. << RHS.get()->getSourceRange();
  4150. // In this situation, we assume void* type. No especially good
  4151. // reason, but this is what gcc does, and we do have to pick
  4152. // to get a consistent AST.
  4153. QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
  4154. LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
  4155. RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
  4156. return incompatTy;
  4157. }
  4158. // The pointer types are compatible.
  4159. QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
  4160. ResultTy = S.Context.getPointerType(ResultTy);
  4161. LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
  4162. RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
  4163. return ResultTy;
  4164. }
  4165. /// \brief Return the resulting type when the operands are both block pointers.
  4166. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  4167. ExprResult &LHS,
  4168. ExprResult &RHS,
  4169. SourceLocation Loc) {
  4170. QualType LHSTy = LHS.get()->getType();
  4171. QualType RHSTy = RHS.get()->getType();
  4172. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  4173. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  4174. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  4175. LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
  4176. RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
  4177. return destType;
  4178. }
  4179. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  4180. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  4181. << RHS.get()->getSourceRange();
  4182. return QualType();
  4183. }
  4184. // We have 2 block pointer types.
  4185. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  4186. }
  4187. /// \brief Return the resulting type when the operands are both pointers.
  4188. static QualType
  4189. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  4190. ExprResult &RHS,
  4191. SourceLocation Loc) {
  4192. // get the pointer types
  4193. QualType LHSTy = LHS.get()->getType();
  4194. QualType RHSTy = RHS.get()->getType();
  4195. // get the "pointed to" types
  4196. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  4197. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  4198. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  4199. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  4200. // Figure out necessary qualifiers (C99 6.5.15p6)
  4201. QualType destPointee
  4202. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  4203. QualType destType = S.Context.getPointerType(destPointee);
  4204. // Add qualifiers if necessary.
  4205. LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
  4206. // Promote to void*.
  4207. RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
  4208. return destType;
  4209. }
  4210. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  4211. QualType destPointee
  4212. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  4213. QualType destType = S.Context.getPointerType(destPointee);
  4214. // Add qualifiers if necessary.
  4215. RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
  4216. // Promote to void*.
  4217. LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
  4218. return destType;
  4219. }
  4220. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  4221. }
  4222. /// \brief Return false if the first expression is not an integer and the second
  4223. /// expression is not a pointer, true otherwise.
  4224. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  4225. Expr* PointerExpr, SourceLocation Loc,
  4226. bool IsIntFirstExpr) {
  4227. if (!PointerExpr->getType()->isPointerType() ||
  4228. !Int.get()->getType()->isIntegerType())
  4229. return false;
  4230. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  4231. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  4232. S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
  4233. << Expr1->getType() << Expr2->getType()
  4234. << Expr1->getSourceRange() << Expr2->getSourceRange();
  4235. Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
  4236. CK_IntegralToPointer);
  4237. return true;
  4238. }
  4239. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  4240. /// In that case, LHS = cond.
  4241. /// C99 6.5.15
  4242. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  4243. ExprResult &RHS, ExprValueKind &VK,
  4244. ExprObjectKind &OK,
  4245. SourceLocation QuestionLoc) {
  4246. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  4247. if (!LHSResult.isUsable()) return QualType();
  4248. LHS = LHSResult;
  4249. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  4250. if (!RHSResult.isUsable()) return QualType();
  4251. RHS = RHSResult;
  4252. // C++ is sufficiently different to merit its own checker.
  4253. if (getLangOpts().CPlusPlus)
  4254. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  4255. VK = VK_RValue;
  4256. OK = OK_Ordinary;
  4257. Cond = UsualUnaryConversions(Cond.take());
  4258. if (Cond.isInvalid())
  4259. return QualType();
  4260. LHS = UsualUnaryConversions(LHS.take());
  4261. if (LHS.isInvalid())
  4262. return QualType();
  4263. RHS = UsualUnaryConversions(RHS.take());
  4264. if (RHS.isInvalid())
  4265. return QualType();
  4266. QualType CondTy = Cond.get()->getType();
  4267. QualType LHSTy = LHS.get()->getType();
  4268. QualType RHSTy = RHS.get()->getType();
  4269. // first, check the condition.
  4270. if (checkCondition(*this, Cond.get()))
  4271. return QualType();
  4272. // Now check the two expressions.
  4273. if (LHSTy->isVectorType() || RHSTy->isVectorType())
  4274. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
  4275. // OpenCL: If the condition is a vector, and both operands are scalar,
  4276. // attempt to implicity convert them to the vector type to act like the
  4277. // built in select.
  4278. if (getLangOpts().OpenCL && CondTy->isVectorType())
  4279. if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
  4280. return QualType();
  4281. // If both operands have arithmetic type, do the usual arithmetic conversions
  4282. // to find a common type: C99 6.5.15p3,5.
  4283. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  4284. UsualArithmeticConversions(LHS, RHS);
  4285. if (LHS.isInvalid() || RHS.isInvalid())
  4286. return QualType();
  4287. return LHS.get()->getType();
  4288. }
  4289. // If both operands are the same structure or union type, the result is that
  4290. // type.
  4291. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  4292. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  4293. if (LHSRT->getDecl() == RHSRT->getDecl())
  4294. // "If both the operands have structure or union type, the result has
  4295. // that type." This implies that CV qualifiers are dropped.
  4296. return LHSTy.getUnqualifiedType();
  4297. // FIXME: Type of conditional expression must be complete in C mode.
  4298. }
  4299. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  4300. // The following || allows only one side to be void (a GCC-ism).
  4301. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  4302. return checkConditionalVoidType(*this, LHS, RHS);
  4303. }
  4304. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  4305. // the type of the other operand."
  4306. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  4307. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  4308. // All objective-c pointer type analysis is done here.
  4309. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  4310. QuestionLoc);
  4311. if (LHS.isInvalid() || RHS.isInvalid())
  4312. return QualType();
  4313. if (!compositeType.isNull())
  4314. return compositeType;
  4315. // Handle block pointer types.
  4316. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  4317. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  4318. QuestionLoc);
  4319. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  4320. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  4321. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  4322. QuestionLoc);
  4323. // GCC compatibility: soften pointer/integer mismatch. Note that
  4324. // null pointers have been filtered out by this point.
  4325. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  4326. /*isIntFirstExpr=*/true))
  4327. return RHSTy;
  4328. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  4329. /*isIntFirstExpr=*/false))
  4330. return LHSTy;
  4331. // Emit a better diagnostic if one of the expressions is a null pointer
  4332. // constant and the other is not a pointer type. In this case, the user most
  4333. // likely forgot to take the address of the other expression.
  4334. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  4335. return QualType();
  4336. // Otherwise, the operands are not compatible.
  4337. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  4338. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  4339. << RHS.get()->getSourceRange();
  4340. return QualType();
  4341. }
  4342. /// FindCompositeObjCPointerType - Helper method to find composite type of
  4343. /// two objective-c pointer types of the two input expressions.
  4344. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  4345. SourceLocation QuestionLoc) {
  4346. QualType LHSTy = LHS.get()->getType();
  4347. QualType RHSTy = RHS.get()->getType();
  4348. // Handle things like Class and struct objc_class*. Here we case the result
  4349. // to the pseudo-builtin, because that will be implicitly cast back to the
  4350. // redefinition type if an attempt is made to access its fields.
  4351. if (LHSTy->isObjCClassType() &&
  4352. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  4353. RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
  4354. return LHSTy;
  4355. }
  4356. if (RHSTy->isObjCClassType() &&
  4357. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  4358. LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
  4359. return RHSTy;
  4360. }
  4361. // And the same for struct objc_object* / id
  4362. if (LHSTy->isObjCIdType() &&
  4363. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  4364. RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
  4365. return LHSTy;
  4366. }
  4367. if (RHSTy->isObjCIdType() &&
  4368. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  4369. LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
  4370. return RHSTy;
  4371. }
  4372. // And the same for struct objc_selector* / SEL
  4373. if (Context.isObjCSelType(LHSTy) &&
  4374. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  4375. RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
  4376. return LHSTy;
  4377. }
  4378. if (Context.isObjCSelType(RHSTy) &&
  4379. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  4380. LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
  4381. return RHSTy;
  4382. }
  4383. // Check constraints for Objective-C object pointers types.
  4384. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  4385. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  4386. // Two identical object pointer types are always compatible.
  4387. return LHSTy;
  4388. }
  4389. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  4390. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  4391. QualType compositeType = LHSTy;
  4392. // If both operands are interfaces and either operand can be
  4393. // assigned to the other, use that type as the composite
  4394. // type. This allows
  4395. // xxx ? (A*) a : (B*) b
  4396. // where B is a subclass of A.
  4397. //
  4398. // Additionally, as for assignment, if either type is 'id'
  4399. // allow silent coercion. Finally, if the types are
  4400. // incompatible then make sure to use 'id' as the composite
  4401. // type so the result is acceptable for sending messages to.
  4402. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  4403. // It could return the composite type.
  4404. if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  4405. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  4406. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  4407. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  4408. } else if ((LHSTy->isObjCQualifiedIdType() ||
  4409. RHSTy->isObjCQualifiedIdType()) &&
  4410. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  4411. // Need to handle "id<xx>" explicitly.
  4412. // GCC allows qualified id and any Objective-C type to devolve to
  4413. // id. Currently localizing to here until clear this should be
  4414. // part of ObjCQualifiedIdTypesAreCompatible.
  4415. compositeType = Context.getObjCIdType();
  4416. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  4417. compositeType = Context.getObjCIdType();
  4418. } else if (!(compositeType =
  4419. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
  4420. ;
  4421. else {
  4422. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  4423. << LHSTy << RHSTy
  4424. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4425. QualType incompatTy = Context.getObjCIdType();
  4426. LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
  4427. RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
  4428. return incompatTy;
  4429. }
  4430. // The object pointer types are compatible.
  4431. LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
  4432. RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
  4433. return compositeType;
  4434. }
  4435. // Check Objective-C object pointer types and 'void *'
  4436. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  4437. if (getLangOpts().ObjCAutoRefCount) {
  4438. // ARC forbids the implicit conversion of object pointers to 'void *',
  4439. // so these types are not compatible.
  4440. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  4441. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4442. LHS = RHS = true;
  4443. return QualType();
  4444. }
  4445. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  4446. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  4447. QualType destPointee
  4448. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  4449. QualType destType = Context.getPointerType(destPointee);
  4450. // Add qualifiers if necessary.
  4451. LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
  4452. // Promote to void*.
  4453. RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
  4454. return destType;
  4455. }
  4456. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  4457. if (getLangOpts().ObjCAutoRefCount) {
  4458. // ARC forbids the implicit conversion of object pointers to 'void *',
  4459. // so these types are not compatible.
  4460. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  4461. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  4462. LHS = RHS = true;
  4463. return QualType();
  4464. }
  4465. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  4466. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  4467. QualType destPointee
  4468. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  4469. QualType destType = Context.getPointerType(destPointee);
  4470. // Add qualifiers if necessary.
  4471. RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
  4472. // Promote to void*.
  4473. LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
  4474. return destType;
  4475. }
  4476. return QualType();
  4477. }
  4478. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  4479. /// ParenRange in parentheses.
  4480. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  4481. const PartialDiagnostic &Note,
  4482. SourceRange ParenRange) {
  4483. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
  4484. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  4485. EndLoc.isValid()) {
  4486. Self.Diag(Loc, Note)
  4487. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  4488. << FixItHint::CreateInsertion(EndLoc, ")");
  4489. } else {
  4490. // We can't display the parentheses, so just show the bare note.
  4491. Self.Diag(Loc, Note) << ParenRange;
  4492. }
  4493. }
  4494. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  4495. return Opc >= BO_Mul && Opc <= BO_Shr;
  4496. }
  4497. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  4498. /// expression, either using a built-in or overloaded operator,
  4499. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  4500. /// expression.
  4501. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  4502. Expr **RHSExprs) {
  4503. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  4504. E = E->IgnoreImpCasts();
  4505. E = E->IgnoreConversionOperator();
  4506. E = E->IgnoreImpCasts();
  4507. // Built-in binary operator.
  4508. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  4509. if (IsArithmeticOp(OP->getOpcode())) {
  4510. *Opcode = OP->getOpcode();
  4511. *RHSExprs = OP->getRHS();
  4512. return true;
  4513. }
  4514. }
  4515. // Overloaded operator.
  4516. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  4517. if (Call->getNumArgs() != 2)
  4518. return false;
  4519. // Make sure this is really a binary operator that is safe to pass into
  4520. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  4521. OverloadedOperatorKind OO = Call->getOperator();
  4522. if (OO < OO_Plus || OO > OO_Arrow)
  4523. return false;
  4524. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  4525. if (IsArithmeticOp(OpKind)) {
  4526. *Opcode = OpKind;
  4527. *RHSExprs = Call->getArg(1);
  4528. return true;
  4529. }
  4530. }
  4531. return false;
  4532. }
  4533. static bool IsLogicOp(BinaryOperatorKind Opc) {
  4534. return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
  4535. }
  4536. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  4537. /// or is a logical expression such as (x==y) which has int type, but is
  4538. /// commonly interpreted as boolean.
  4539. static bool ExprLooksBoolean(Expr *E) {
  4540. E = E->IgnoreParenImpCasts();
  4541. if (E->getType()->isBooleanType())
  4542. return true;
  4543. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  4544. return IsLogicOp(OP->getOpcode());
  4545. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  4546. return OP->getOpcode() == UO_LNot;
  4547. return false;
  4548. }
  4549. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  4550. /// and binary operator are mixed in a way that suggests the programmer assumed
  4551. /// the conditional operator has higher precedence, for example:
  4552. /// "int x = a + someBinaryCondition ? 1 : 2".
  4553. static void DiagnoseConditionalPrecedence(Sema &Self,
  4554. SourceLocation OpLoc,
  4555. Expr *Condition,
  4556. Expr *LHSExpr,
  4557. Expr *RHSExpr) {
  4558. BinaryOperatorKind CondOpcode;
  4559. Expr *CondRHS;
  4560. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  4561. return;
  4562. if (!ExprLooksBoolean(CondRHS))
  4563. return;
  4564. // The condition is an arithmetic binary expression, with a right-
  4565. // hand side that looks boolean, so warn.
  4566. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  4567. << Condition->getSourceRange()
  4568. << BinaryOperator::getOpcodeStr(CondOpcode);
  4569. SuggestParentheses(Self, OpLoc,
  4570. Self.PDiag(diag::note_precedence_conditional_silence)
  4571. << BinaryOperator::getOpcodeStr(CondOpcode),
  4572. SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
  4573. SuggestParentheses(Self, OpLoc,
  4574. Self.PDiag(diag::note_precedence_conditional_first),
  4575. SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
  4576. }
  4577. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  4578. /// in the case of a the GNU conditional expr extension.
  4579. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  4580. SourceLocation ColonLoc,
  4581. Expr *CondExpr, Expr *LHSExpr,
  4582. Expr *RHSExpr) {
  4583. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  4584. // was the condition.
  4585. OpaqueValueExpr *opaqueValue = 0;
  4586. Expr *commonExpr = 0;
  4587. if (LHSExpr == 0) {
  4588. commonExpr = CondExpr;
  4589. // We usually want to apply unary conversions *before* saving, except
  4590. // in the special case of a C++ l-value conditional.
  4591. if (!(getLangOpts().CPlusPlus
  4592. && !commonExpr->isTypeDependent()
  4593. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  4594. && commonExpr->isGLValue()
  4595. && commonExpr->isOrdinaryOrBitFieldObject()
  4596. && RHSExpr->isOrdinaryOrBitFieldObject()
  4597. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  4598. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  4599. if (commonRes.isInvalid())
  4600. return ExprError();
  4601. commonExpr = commonRes.take();
  4602. }
  4603. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  4604. commonExpr->getType(),
  4605. commonExpr->getValueKind(),
  4606. commonExpr->getObjectKind(),
  4607. commonExpr);
  4608. LHSExpr = CondExpr = opaqueValue;
  4609. }
  4610. ExprValueKind VK = VK_RValue;
  4611. ExprObjectKind OK = OK_Ordinary;
  4612. ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
  4613. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  4614. VK, OK, QuestionLoc);
  4615. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  4616. RHS.isInvalid())
  4617. return ExprError();
  4618. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  4619. RHS.get());
  4620. if (!commonExpr)
  4621. return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
  4622. LHS.take(), ColonLoc,
  4623. RHS.take(), result, VK, OK));
  4624. return Owned(new (Context)
  4625. BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
  4626. RHS.take(), QuestionLoc, ColonLoc, result, VK,
  4627. OK));
  4628. }
  4629. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  4630. // being closely modeled after the C99 spec:-). The odd characteristic of this
  4631. // routine is it effectively iqnores the qualifiers on the top level pointee.
  4632. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  4633. // FIXME: add a couple examples in this comment.
  4634. static Sema::AssignConvertType
  4635. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  4636. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  4637. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  4638. // get the "pointed to" type (ignoring qualifiers at the top level)
  4639. const Type *lhptee, *rhptee;
  4640. Qualifiers lhq, rhq;
  4641. llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
  4642. llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
  4643. Sema::AssignConvertType ConvTy = Sema::Compatible;
  4644. // C99 6.5.16.1p1: This following citation is common to constraints
  4645. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  4646. // qualifiers of the type *pointed to* by the right;
  4647. Qualifiers lq;
  4648. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  4649. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  4650. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  4651. // Ignore lifetime for further calculation.
  4652. lhq.removeObjCLifetime();
  4653. rhq.removeObjCLifetime();
  4654. }
  4655. if (!lhq.compatiblyIncludes(rhq)) {
  4656. // Treat address-space mismatches as fatal. TODO: address subspaces
  4657. if (lhq.getAddressSpace() != rhq.getAddressSpace())
  4658. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  4659. // It's okay to add or remove GC or lifetime qualifiers when converting to
  4660. // and from void*.
  4661. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  4662. .compatiblyIncludes(
  4663. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  4664. && (lhptee->isVoidType() || rhptee->isVoidType()))
  4665. ; // keep old
  4666. // Treat lifetime mismatches as fatal.
  4667. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  4668. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  4669. // For GCC compatibility, other qualifier mismatches are treated
  4670. // as still compatible in C.
  4671. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  4672. }
  4673. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  4674. // incomplete type and the other is a pointer to a qualified or unqualified
  4675. // version of void...
  4676. if (lhptee->isVoidType()) {
  4677. if (rhptee->isIncompleteOrObjectType())
  4678. return ConvTy;
  4679. // As an extension, we allow cast to/from void* to function pointer.
  4680. assert(rhptee->isFunctionType());
  4681. return Sema::FunctionVoidPointer;
  4682. }
  4683. if (rhptee->isVoidType()) {
  4684. if (lhptee->isIncompleteOrObjectType())
  4685. return ConvTy;
  4686. // As an extension, we allow cast to/from void* to function pointer.
  4687. assert(lhptee->isFunctionType());
  4688. return Sema::FunctionVoidPointer;
  4689. }
  4690. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  4691. // unqualified versions of compatible types, ...
  4692. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  4693. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  4694. // Check if the pointee types are compatible ignoring the sign.
  4695. // We explicitly check for char so that we catch "char" vs
  4696. // "unsigned char" on systems where "char" is unsigned.
  4697. if (lhptee->isCharType())
  4698. ltrans = S.Context.UnsignedCharTy;
  4699. else if (lhptee->hasSignedIntegerRepresentation())
  4700. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  4701. if (rhptee->isCharType())
  4702. rtrans = S.Context.UnsignedCharTy;
  4703. else if (rhptee->hasSignedIntegerRepresentation())
  4704. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  4705. if (ltrans == rtrans) {
  4706. // Types are compatible ignoring the sign. Qualifier incompatibility
  4707. // takes priority over sign incompatibility because the sign
  4708. // warning can be disabled.
  4709. if (ConvTy != Sema::Compatible)
  4710. return ConvTy;
  4711. return Sema::IncompatiblePointerSign;
  4712. }
  4713. // If we are a multi-level pointer, it's possible that our issue is simply
  4714. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  4715. // the eventual target type is the same and the pointers have the same
  4716. // level of indirection, this must be the issue.
  4717. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  4718. do {
  4719. lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
  4720. rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
  4721. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  4722. if (lhptee == rhptee)
  4723. return Sema::IncompatibleNestedPointerQualifiers;
  4724. }
  4725. // General pointer incompatibility takes priority over qualifiers.
  4726. return Sema::IncompatiblePointer;
  4727. }
  4728. if (!S.getLangOpts().CPlusPlus &&
  4729. S.IsNoReturnConversion(ltrans, rtrans, ltrans))
  4730. return Sema::IncompatiblePointer;
  4731. return ConvTy;
  4732. }
  4733. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  4734. /// block pointer types are compatible or whether a block and normal pointer
  4735. /// are compatible. It is more restrict than comparing two function pointer
  4736. // types.
  4737. static Sema::AssignConvertType
  4738. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  4739. QualType RHSType) {
  4740. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  4741. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  4742. QualType lhptee, rhptee;
  4743. // get the "pointed to" type (ignoring qualifiers at the top level)
  4744. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  4745. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  4746. // In C++, the types have to match exactly.
  4747. if (S.getLangOpts().CPlusPlus)
  4748. return Sema::IncompatibleBlockPointer;
  4749. Sema::AssignConvertType ConvTy = Sema::Compatible;
  4750. // For blocks we enforce that qualifiers are identical.
  4751. if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
  4752. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  4753. if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  4754. return Sema::IncompatibleBlockPointer;
  4755. return ConvTy;
  4756. }
  4757. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  4758. /// for assignment compatibility.
  4759. static Sema::AssignConvertType
  4760. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  4761. QualType RHSType) {
  4762. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  4763. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  4764. if (LHSType->isObjCBuiltinType()) {
  4765. // Class is not compatible with ObjC object pointers.
  4766. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  4767. !RHSType->isObjCQualifiedClassType())
  4768. return Sema::IncompatiblePointer;
  4769. return Sema::Compatible;
  4770. }
  4771. if (RHSType->isObjCBuiltinType()) {
  4772. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  4773. !LHSType->isObjCQualifiedClassType())
  4774. return Sema::IncompatiblePointer;
  4775. return Sema::Compatible;
  4776. }
  4777. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  4778. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  4779. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  4780. // make an exception for id<P>
  4781. !LHSType->isObjCQualifiedIdType())
  4782. return Sema::CompatiblePointerDiscardsQualifiers;
  4783. if (S.Context.typesAreCompatible(LHSType, RHSType))
  4784. return Sema::Compatible;
  4785. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  4786. return Sema::IncompatibleObjCQualifiedId;
  4787. return Sema::IncompatiblePointer;
  4788. }
  4789. Sema::AssignConvertType
  4790. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  4791. QualType LHSType, QualType RHSType) {
  4792. // Fake up an opaque expression. We don't actually care about what
  4793. // cast operations are required, so if CheckAssignmentConstraints
  4794. // adds casts to this they'll be wasted, but fortunately that doesn't
  4795. // usually happen on valid code.
  4796. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  4797. ExprResult RHSPtr = &RHSExpr;
  4798. CastKind K = CK_Invalid;
  4799. return CheckAssignmentConstraints(LHSType, RHSPtr, K);
  4800. }
  4801. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  4802. /// has code to accommodate several GCC extensions when type checking
  4803. /// pointers. Here are some objectionable examples that GCC considers warnings:
  4804. ///
  4805. /// int a, *pint;
  4806. /// short *pshort;
  4807. /// struct foo *pfoo;
  4808. ///
  4809. /// pint = pshort; // warning: assignment from incompatible pointer type
  4810. /// a = pint; // warning: assignment makes integer from pointer without a cast
  4811. /// pint = a; // warning: assignment makes pointer from integer without a cast
  4812. /// pint = pfoo; // warning: assignment from incompatible pointer type
  4813. ///
  4814. /// As a result, the code for dealing with pointers is more complex than the
  4815. /// C99 spec dictates.
  4816. ///
  4817. /// Sets 'Kind' for any result kind except Incompatible.
  4818. Sema::AssignConvertType
  4819. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  4820. CastKind &Kind) {
  4821. QualType RHSType = RHS.get()->getType();
  4822. QualType OrigLHSType = LHSType;
  4823. // Get canonical types. We're not formatting these types, just comparing
  4824. // them.
  4825. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  4826. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  4827. // Common case: no conversion required.
  4828. if (LHSType == RHSType) {
  4829. Kind = CK_NoOp;
  4830. return Compatible;
  4831. }
  4832. // If we have an atomic type, try a non-atomic assignment, then just add an
  4833. // atomic qualification step.
  4834. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  4835. Sema::AssignConvertType result =
  4836. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  4837. if (result != Compatible)
  4838. return result;
  4839. if (Kind != CK_NoOp)
  4840. RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
  4841. Kind = CK_NonAtomicToAtomic;
  4842. return Compatible;
  4843. }
  4844. // If the left-hand side is a reference type, then we are in a
  4845. // (rare!) case where we've allowed the use of references in C,
  4846. // e.g., as a parameter type in a built-in function. In this case,
  4847. // just make sure that the type referenced is compatible with the
  4848. // right-hand side type. The caller is responsible for adjusting
  4849. // LHSType so that the resulting expression does not have reference
  4850. // type.
  4851. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  4852. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  4853. Kind = CK_LValueBitCast;
  4854. return Compatible;
  4855. }
  4856. return Incompatible;
  4857. }
  4858. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  4859. // to the same ExtVector type.
  4860. if (LHSType->isExtVectorType()) {
  4861. if (RHSType->isExtVectorType())
  4862. return Incompatible;
  4863. if (RHSType->isArithmeticType()) {
  4864. // CK_VectorSplat does T -> vector T, so first cast to the
  4865. // element type.
  4866. QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
  4867. if (elType != RHSType) {
  4868. Kind = PrepareScalarCast(RHS, elType);
  4869. RHS = ImpCastExprToType(RHS.take(), elType, Kind);
  4870. }
  4871. Kind = CK_VectorSplat;
  4872. return Compatible;
  4873. }
  4874. }
  4875. // Conversions to or from vector type.
  4876. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  4877. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  4878. // Allow assignments of an AltiVec vector type to an equivalent GCC
  4879. // vector type and vice versa
  4880. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  4881. Kind = CK_BitCast;
  4882. return Compatible;
  4883. }
  4884. // If we are allowing lax vector conversions, and LHS and RHS are both
  4885. // vectors, the total size only needs to be the same. This is a bitcast;
  4886. // no bits are changed but the result type is different.
  4887. if (getLangOpts().LaxVectorConversions &&
  4888. (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
  4889. Kind = CK_BitCast;
  4890. return IncompatibleVectors;
  4891. }
  4892. }
  4893. return Incompatible;
  4894. }
  4895. // Arithmetic conversions.
  4896. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  4897. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  4898. Kind = PrepareScalarCast(RHS, LHSType);
  4899. return Compatible;
  4900. }
  4901. // Conversions to normal pointers.
  4902. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  4903. // U* -> T*
  4904. if (isa<PointerType>(RHSType)) {
  4905. Kind = CK_BitCast;
  4906. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  4907. }
  4908. // int -> T*
  4909. if (RHSType->isIntegerType()) {
  4910. Kind = CK_IntegralToPointer; // FIXME: null?
  4911. return IntToPointer;
  4912. }
  4913. // C pointers are not compatible with ObjC object pointers,
  4914. // with two exceptions:
  4915. if (isa<ObjCObjectPointerType>(RHSType)) {
  4916. // - conversions to void*
  4917. if (LHSPointer->getPointeeType()->isVoidType()) {
  4918. Kind = CK_BitCast;
  4919. return Compatible;
  4920. }
  4921. // - conversions from 'Class' to the redefinition type
  4922. if (RHSType->isObjCClassType() &&
  4923. Context.hasSameType(LHSType,
  4924. Context.getObjCClassRedefinitionType())) {
  4925. Kind = CK_BitCast;
  4926. return Compatible;
  4927. }
  4928. Kind = CK_BitCast;
  4929. return IncompatiblePointer;
  4930. }
  4931. // U^ -> void*
  4932. if (RHSType->getAs<BlockPointerType>()) {
  4933. if (LHSPointer->getPointeeType()->isVoidType()) {
  4934. Kind = CK_BitCast;
  4935. return Compatible;
  4936. }
  4937. }
  4938. return Incompatible;
  4939. }
  4940. // Conversions to block pointers.
  4941. if (isa<BlockPointerType>(LHSType)) {
  4942. // U^ -> T^
  4943. if (RHSType->isBlockPointerType()) {
  4944. Kind = CK_BitCast;
  4945. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  4946. }
  4947. // int or null -> T^
  4948. if (RHSType->isIntegerType()) {
  4949. Kind = CK_IntegralToPointer; // FIXME: null
  4950. return IntToBlockPointer;
  4951. }
  4952. // id -> T^
  4953. if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
  4954. Kind = CK_AnyPointerToBlockPointerCast;
  4955. return Compatible;
  4956. }
  4957. // void* -> T^
  4958. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  4959. if (RHSPT->getPointeeType()->isVoidType()) {
  4960. Kind = CK_AnyPointerToBlockPointerCast;
  4961. return Compatible;
  4962. }
  4963. return Incompatible;
  4964. }
  4965. // Conversions to Objective-C pointers.
  4966. if (isa<ObjCObjectPointerType>(LHSType)) {
  4967. // A* -> B*
  4968. if (RHSType->isObjCObjectPointerType()) {
  4969. Kind = CK_BitCast;
  4970. Sema::AssignConvertType result =
  4971. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  4972. if (getLangOpts().ObjCAutoRefCount &&
  4973. result == Compatible &&
  4974. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  4975. result = IncompatibleObjCWeakRef;
  4976. return result;
  4977. }
  4978. // int or null -> A*
  4979. if (RHSType->isIntegerType()) {
  4980. Kind = CK_IntegralToPointer; // FIXME: null
  4981. return IntToPointer;
  4982. }
  4983. // In general, C pointers are not compatible with ObjC object pointers,
  4984. // with two exceptions:
  4985. if (isa<PointerType>(RHSType)) {
  4986. Kind = CK_CPointerToObjCPointerCast;
  4987. // - conversions from 'void*'
  4988. if (RHSType->isVoidPointerType()) {
  4989. return Compatible;
  4990. }
  4991. // - conversions to 'Class' from its redefinition type
  4992. if (LHSType->isObjCClassType() &&
  4993. Context.hasSameType(RHSType,
  4994. Context.getObjCClassRedefinitionType())) {
  4995. return Compatible;
  4996. }
  4997. return IncompatiblePointer;
  4998. }
  4999. // T^ -> A*
  5000. if (RHSType->isBlockPointerType()) {
  5001. maybeExtendBlockObject(*this, RHS);
  5002. Kind = CK_BlockPointerToObjCPointerCast;
  5003. return Compatible;
  5004. }
  5005. return Incompatible;
  5006. }
  5007. // Conversions from pointers that are not covered by the above.
  5008. if (isa<PointerType>(RHSType)) {
  5009. // T* -> _Bool
  5010. if (LHSType == Context.BoolTy) {
  5011. Kind = CK_PointerToBoolean;
  5012. return Compatible;
  5013. }
  5014. // T* -> int
  5015. if (LHSType->isIntegerType()) {
  5016. Kind = CK_PointerToIntegral;
  5017. return PointerToInt;
  5018. }
  5019. return Incompatible;
  5020. }
  5021. // Conversions from Objective-C pointers that are not covered by the above.
  5022. if (isa<ObjCObjectPointerType>(RHSType)) {
  5023. // T* -> _Bool
  5024. if (LHSType == Context.BoolTy) {
  5025. Kind = CK_PointerToBoolean;
  5026. return Compatible;
  5027. }
  5028. // T* -> int
  5029. if (LHSType->isIntegerType()) {
  5030. Kind = CK_PointerToIntegral;
  5031. return PointerToInt;
  5032. }
  5033. return Incompatible;
  5034. }
  5035. // struct A -> struct B
  5036. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  5037. if (Context.typesAreCompatible(LHSType, RHSType)) {
  5038. Kind = CK_NoOp;
  5039. return Compatible;
  5040. }
  5041. }
  5042. return Incompatible;
  5043. }
  5044. /// \brief Constructs a transparent union from an expression that is
  5045. /// used to initialize the transparent union.
  5046. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  5047. ExprResult &EResult, QualType UnionType,
  5048. FieldDecl *Field) {
  5049. // Build an initializer list that designates the appropriate member
  5050. // of the transparent union.
  5051. Expr *E = EResult.take();
  5052. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  5053. &E, 1,
  5054. SourceLocation());
  5055. Initializer->setType(UnionType);
  5056. Initializer->setInitializedFieldInUnion(Field);
  5057. // Build a compound literal constructing a value of the transparent
  5058. // union type from this initializer list.
  5059. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  5060. EResult = S.Owned(
  5061. new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  5062. VK_RValue, Initializer, false));
  5063. }
  5064. Sema::AssignConvertType
  5065. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  5066. ExprResult &RHS) {
  5067. QualType RHSType = RHS.get()->getType();
  5068. // If the ArgType is a Union type, we want to handle a potential
  5069. // transparent_union GCC extension.
  5070. const RecordType *UT = ArgType->getAsUnionType();
  5071. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  5072. return Incompatible;
  5073. // The field to initialize within the transparent union.
  5074. RecordDecl *UD = UT->getDecl();
  5075. FieldDecl *InitField = 0;
  5076. // It's compatible if the expression matches any of the fields.
  5077. for (RecordDecl::field_iterator it = UD->field_begin(),
  5078. itend = UD->field_end();
  5079. it != itend; ++it) {
  5080. if (it->getType()->isPointerType()) {
  5081. // If the transparent union contains a pointer type, we allow:
  5082. // 1) void pointer
  5083. // 2) null pointer constant
  5084. if (RHSType->isPointerType())
  5085. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  5086. RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
  5087. InitField = *it;
  5088. break;
  5089. }
  5090. if (RHS.get()->isNullPointerConstant(Context,
  5091. Expr::NPC_ValueDependentIsNull)) {
  5092. RHS = ImpCastExprToType(RHS.take(), it->getType(),
  5093. CK_NullToPointer);
  5094. InitField = *it;
  5095. break;
  5096. }
  5097. }
  5098. CastKind Kind = CK_Invalid;
  5099. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  5100. == Compatible) {
  5101. RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
  5102. InitField = *it;
  5103. break;
  5104. }
  5105. }
  5106. if (!InitField)
  5107. return Incompatible;
  5108. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  5109. return Compatible;
  5110. }
  5111. Sema::AssignConvertType
  5112. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  5113. bool Diagnose) {
  5114. if (getLangOpts().CPlusPlus) {
  5115. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  5116. // C++ 5.17p3: If the left operand is not of class type, the
  5117. // expression is implicitly converted (C++ 4) to the
  5118. // cv-unqualified type of the left operand.
  5119. ExprResult Res;
  5120. if (Diagnose) {
  5121. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  5122. AA_Assigning);
  5123. } else {
  5124. ImplicitConversionSequence ICS =
  5125. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  5126. /*SuppressUserConversions=*/false,
  5127. /*AllowExplicit=*/false,
  5128. /*InOverloadResolution=*/false,
  5129. /*CStyle=*/false,
  5130. /*AllowObjCWritebackConversion=*/false);
  5131. if (ICS.isFailure())
  5132. return Incompatible;
  5133. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  5134. ICS, AA_Assigning);
  5135. }
  5136. if (Res.isInvalid())
  5137. return Incompatible;
  5138. Sema::AssignConvertType result = Compatible;
  5139. if (getLangOpts().ObjCAutoRefCount &&
  5140. !CheckObjCARCUnavailableWeakConversion(LHSType,
  5141. RHS.get()->getType()))
  5142. result = IncompatibleObjCWeakRef;
  5143. RHS = Res;
  5144. return result;
  5145. }
  5146. // FIXME: Currently, we fall through and treat C++ classes like C
  5147. // structures.
  5148. // FIXME: We also fall through for atomics; not sure what should
  5149. // happen there, though.
  5150. }
  5151. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  5152. // a null pointer constant.
  5153. if ((LHSType->isPointerType() ||
  5154. LHSType->isObjCObjectPointerType() ||
  5155. LHSType->isBlockPointerType())
  5156. && RHS.get()->isNullPointerConstant(Context,
  5157. Expr::NPC_ValueDependentIsNull)) {
  5158. RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
  5159. return Compatible;
  5160. }
  5161. // This check seems unnatural, however it is necessary to ensure the proper
  5162. // conversion of functions/arrays. If the conversion were done for all
  5163. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  5164. // expressions that suppress this implicit conversion (&, sizeof).
  5165. //
  5166. // Suppress this for references: C++ 8.5.3p5.
  5167. if (!LHSType->isReferenceType()) {
  5168. RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
  5169. if (RHS.isInvalid())
  5170. return Incompatible;
  5171. }
  5172. CastKind Kind = CK_Invalid;
  5173. Sema::AssignConvertType result =
  5174. CheckAssignmentConstraints(LHSType, RHS, Kind);
  5175. // C99 6.5.16.1p2: The value of the right operand is converted to the
  5176. // type of the assignment expression.
  5177. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  5178. // so that we can use references in built-in functions even in C.
  5179. // The getNonReferenceType() call makes sure that the resulting expression
  5180. // does not have reference type.
  5181. if (result != Incompatible && RHS.get()->getType() != LHSType)
  5182. RHS = ImpCastExprToType(RHS.take(),
  5183. LHSType.getNonLValueExprType(Context), Kind);
  5184. return result;
  5185. }
  5186. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  5187. ExprResult &RHS) {
  5188. Diag(Loc, diag::err_typecheck_invalid_operands)
  5189. << LHS.get()->getType() << RHS.get()->getType()
  5190. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5191. return QualType();
  5192. }
  5193. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  5194. SourceLocation Loc, bool IsCompAssign) {
  5195. if (!IsCompAssign) {
  5196. LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
  5197. if (LHS.isInvalid())
  5198. return QualType();
  5199. }
  5200. RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
  5201. if (RHS.isInvalid())
  5202. return QualType();
  5203. // For conversion purposes, we ignore any qualifiers.
  5204. // For example, "const float" and "float" are equivalent.
  5205. QualType LHSType =
  5206. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  5207. QualType RHSType =
  5208. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  5209. // If the vector types are identical, return.
  5210. if (LHSType == RHSType)
  5211. return LHSType;
  5212. // Handle the case of equivalent AltiVec and GCC vector types
  5213. if (LHSType->isVectorType() && RHSType->isVectorType() &&
  5214. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  5215. if (LHSType->isExtVectorType()) {
  5216. RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
  5217. return LHSType;
  5218. }
  5219. if (!IsCompAssign)
  5220. LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
  5221. return RHSType;
  5222. }
  5223. if (getLangOpts().LaxVectorConversions &&
  5224. Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
  5225. // If we are allowing lax vector conversions, and LHS and RHS are both
  5226. // vectors, the total size only needs to be the same. This is a
  5227. // bitcast; no bits are changed but the result type is different.
  5228. // FIXME: Should we really be allowing this?
  5229. RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
  5230. return LHSType;
  5231. }
  5232. // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
  5233. // swap back (so that we don't reverse the inputs to a subtract, for instance.
  5234. bool swapped = false;
  5235. if (RHSType->isExtVectorType() && !IsCompAssign) {
  5236. swapped = true;
  5237. std::swap(RHS, LHS);
  5238. std::swap(RHSType, LHSType);
  5239. }
  5240. // Handle the case of an ext vector and scalar.
  5241. if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
  5242. QualType EltTy = LV->getElementType();
  5243. if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
  5244. int order = Context.getIntegerTypeOrder(EltTy, RHSType);
  5245. if (order > 0)
  5246. RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
  5247. if (order >= 0) {
  5248. RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
  5249. if (swapped) std::swap(RHS, LHS);
  5250. return LHSType;
  5251. }
  5252. }
  5253. if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
  5254. RHSType->isRealFloatingType()) {
  5255. int order = Context.getFloatingTypeOrder(EltTy, RHSType);
  5256. if (order > 0)
  5257. RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
  5258. if (order >= 0) {
  5259. RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
  5260. if (swapped) std::swap(RHS, LHS);
  5261. return LHSType;
  5262. }
  5263. }
  5264. }
  5265. // Vectors of different size or scalar and non-ext-vector are errors.
  5266. if (swapped) std::swap(RHS, LHS);
  5267. Diag(Loc, diag::err_typecheck_vector_not_convertable)
  5268. << LHS.get()->getType() << RHS.get()->getType()
  5269. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5270. return QualType();
  5271. }
  5272. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  5273. // expression. These are mainly cases where the null pointer is used as an
  5274. // integer instead of a pointer.
  5275. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  5276. SourceLocation Loc, bool IsCompare) {
  5277. // The canonical way to check for a GNU null is with isNullPointerConstant,
  5278. // but we use a bit of a hack here for speed; this is a relatively
  5279. // hot path, and isNullPointerConstant is slow.
  5280. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  5281. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  5282. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  5283. // Avoid analyzing cases where the result will either be invalid (and
  5284. // diagnosed as such) or entirely valid and not something to warn about.
  5285. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  5286. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  5287. return;
  5288. // Comparison operations would not make sense with a null pointer no matter
  5289. // what the other expression is.
  5290. if (!IsCompare) {
  5291. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  5292. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  5293. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  5294. return;
  5295. }
  5296. // The rest of the operations only make sense with a null pointer
  5297. // if the other expression is a pointer.
  5298. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  5299. NonNullType->canDecayToPointerType())
  5300. return;
  5301. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  5302. << LHSNull /* LHS is NULL */ << NonNullType
  5303. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5304. }
  5305. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  5306. SourceLocation Loc,
  5307. bool IsCompAssign, bool IsDiv) {
  5308. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  5309. if (LHS.get()->getType()->isVectorType() ||
  5310. RHS.get()->getType()->isVectorType())
  5311. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
  5312. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  5313. if (LHS.isInvalid() || RHS.isInvalid())
  5314. return QualType();
  5315. if (compType.isNull() || !compType->isArithmeticType())
  5316. return InvalidOperands(Loc, LHS, RHS);
  5317. // Check for division by zero.
  5318. if (IsDiv &&
  5319. RHS.get()->isNullPointerConstant(Context,
  5320. Expr::NPC_ValueDependentIsNotNull))
  5321. DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
  5322. << RHS.get()->getSourceRange());
  5323. return compType;
  5324. }
  5325. QualType Sema::CheckRemainderOperands(
  5326. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  5327. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  5328. if (LHS.get()->getType()->isVectorType() ||
  5329. RHS.get()->getType()->isVectorType()) {
  5330. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  5331. RHS.get()->getType()->hasIntegerRepresentation())
  5332. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
  5333. return InvalidOperands(Loc, LHS, RHS);
  5334. }
  5335. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  5336. if (LHS.isInvalid() || RHS.isInvalid())
  5337. return QualType();
  5338. if (compType.isNull() || !compType->isIntegerType())
  5339. return InvalidOperands(Loc, LHS, RHS);
  5340. // Check for remainder by zero.
  5341. if (RHS.get()->isNullPointerConstant(Context,
  5342. Expr::NPC_ValueDependentIsNotNull))
  5343. DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
  5344. << RHS.get()->getSourceRange());
  5345. return compType;
  5346. }
  5347. /// \brief Diagnose invalid arithmetic on two void pointers.
  5348. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  5349. Expr *LHSExpr, Expr *RHSExpr) {
  5350. S.Diag(Loc, S.getLangOpts().CPlusPlus
  5351. ? diag::err_typecheck_pointer_arith_void_type
  5352. : diag::ext_gnu_void_ptr)
  5353. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  5354. << RHSExpr->getSourceRange();
  5355. }
  5356. /// \brief Diagnose invalid arithmetic on a void pointer.
  5357. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  5358. Expr *Pointer) {
  5359. S.Diag(Loc, S.getLangOpts().CPlusPlus
  5360. ? diag::err_typecheck_pointer_arith_void_type
  5361. : diag::ext_gnu_void_ptr)
  5362. << 0 /* one pointer */ << Pointer->getSourceRange();
  5363. }
  5364. /// \brief Diagnose invalid arithmetic on two function pointers.
  5365. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  5366. Expr *LHS, Expr *RHS) {
  5367. assert(LHS->getType()->isAnyPointerType());
  5368. assert(RHS->getType()->isAnyPointerType());
  5369. S.Diag(Loc, S.getLangOpts().CPlusPlus
  5370. ? diag::err_typecheck_pointer_arith_function_type
  5371. : diag::ext_gnu_ptr_func_arith)
  5372. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  5373. // We only show the second type if it differs from the first.
  5374. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  5375. RHS->getType())
  5376. << RHS->getType()->getPointeeType()
  5377. << LHS->getSourceRange() << RHS->getSourceRange();
  5378. }
  5379. /// \brief Diagnose invalid arithmetic on a function pointer.
  5380. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  5381. Expr *Pointer) {
  5382. assert(Pointer->getType()->isAnyPointerType());
  5383. S.Diag(Loc, S.getLangOpts().CPlusPlus
  5384. ? diag::err_typecheck_pointer_arith_function_type
  5385. : diag::ext_gnu_ptr_func_arith)
  5386. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  5387. << 0 /* one pointer, so only one type */
  5388. << Pointer->getSourceRange();
  5389. }
  5390. /// \brief Emit error if Operand is incomplete pointer type
  5391. ///
  5392. /// \returns True if pointer has incomplete type
  5393. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  5394. Expr *Operand) {
  5395. assert(Operand->getType()->isAnyPointerType() &&
  5396. !Operand->getType()->isDependentType());
  5397. QualType PointeeTy = Operand->getType()->getPointeeType();
  5398. return S.RequireCompleteType(Loc, PointeeTy,
  5399. diag::err_typecheck_arithmetic_incomplete_type,
  5400. PointeeTy, Operand->getSourceRange());
  5401. }
  5402. /// \brief Check the validity of an arithmetic pointer operand.
  5403. ///
  5404. /// If the operand has pointer type, this code will check for pointer types
  5405. /// which are invalid in arithmetic operations. These will be diagnosed
  5406. /// appropriately, including whether or not the use is supported as an
  5407. /// extension.
  5408. ///
  5409. /// \returns True when the operand is valid to use (even if as an extension).
  5410. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  5411. Expr *Operand) {
  5412. if (!Operand->getType()->isAnyPointerType()) return true;
  5413. QualType PointeeTy = Operand->getType()->getPointeeType();
  5414. if (PointeeTy->isVoidType()) {
  5415. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  5416. return !S.getLangOpts().CPlusPlus;
  5417. }
  5418. if (PointeeTy->isFunctionType()) {
  5419. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  5420. return !S.getLangOpts().CPlusPlus;
  5421. }
  5422. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  5423. return true;
  5424. }
  5425. /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
  5426. /// operands.
  5427. ///
  5428. /// This routine will diagnose any invalid arithmetic on pointer operands much
  5429. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  5430. /// for emitting a single diagnostic even for operations where both LHS and RHS
  5431. /// are (potentially problematic) pointers.
  5432. ///
  5433. /// \returns True when the operand is valid to use (even if as an extension).
  5434. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  5435. Expr *LHSExpr, Expr *RHSExpr) {
  5436. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  5437. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  5438. if (!isLHSPointer && !isRHSPointer) return true;
  5439. QualType LHSPointeeTy, RHSPointeeTy;
  5440. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  5441. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  5442. // Check for arithmetic on pointers to incomplete types.
  5443. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  5444. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  5445. if (isLHSVoidPtr || isRHSVoidPtr) {
  5446. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  5447. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  5448. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  5449. return !S.getLangOpts().CPlusPlus;
  5450. }
  5451. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  5452. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  5453. if (isLHSFuncPtr || isRHSFuncPtr) {
  5454. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  5455. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  5456. RHSExpr);
  5457. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  5458. return !S.getLangOpts().CPlusPlus;
  5459. }
  5460. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  5461. return false;
  5462. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  5463. return false;
  5464. return true;
  5465. }
  5466. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  5467. /// literal.
  5468. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  5469. Expr *LHSExpr, Expr *RHSExpr) {
  5470. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  5471. Expr* IndexExpr = RHSExpr;
  5472. if (!StrExpr) {
  5473. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  5474. IndexExpr = LHSExpr;
  5475. }
  5476. bool IsStringPlusInt = StrExpr &&
  5477. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  5478. if (!IsStringPlusInt)
  5479. return;
  5480. llvm::APSInt index;
  5481. if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
  5482. unsigned StrLenWithNull = StrExpr->getLength() + 1;
  5483. if (index.isNonNegative() &&
  5484. index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
  5485. index.isUnsigned()))
  5486. return;
  5487. }
  5488. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  5489. Self.Diag(OpLoc, diag::warn_string_plus_int)
  5490. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  5491. // Only print a fixit for "str" + int, not for int + "str".
  5492. if (IndexExpr == RHSExpr) {
  5493. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
  5494. Self.Diag(OpLoc, diag::note_string_plus_int_silence)
  5495. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  5496. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  5497. << FixItHint::CreateInsertion(EndLoc, "]");
  5498. } else
  5499. Self.Diag(OpLoc, diag::note_string_plus_int_silence);
  5500. }
  5501. /// \brief Emit error when two pointers are incompatible.
  5502. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  5503. Expr *LHSExpr, Expr *RHSExpr) {
  5504. assert(LHSExpr->getType()->isAnyPointerType());
  5505. assert(RHSExpr->getType()->isAnyPointerType());
  5506. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  5507. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  5508. << RHSExpr->getSourceRange();
  5509. }
  5510. QualType Sema::CheckAdditionOperands( // C99 6.5.6
  5511. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
  5512. QualType* CompLHSTy) {
  5513. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  5514. if (LHS.get()->getType()->isVectorType() ||
  5515. RHS.get()->getType()->isVectorType()) {
  5516. QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
  5517. if (CompLHSTy) *CompLHSTy = compType;
  5518. return compType;
  5519. }
  5520. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  5521. if (LHS.isInvalid() || RHS.isInvalid())
  5522. return QualType();
  5523. // Diagnose "string literal" '+' int.
  5524. if (Opc == BO_Add)
  5525. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  5526. // handle the common case first (both operands are arithmetic).
  5527. if (!compType.isNull() && compType->isArithmeticType()) {
  5528. if (CompLHSTy) *CompLHSTy = compType;
  5529. return compType;
  5530. }
  5531. // Type-checking. Ultimately the pointer's going to be in PExp;
  5532. // note that we bias towards the LHS being the pointer.
  5533. Expr *PExp = LHS.get(), *IExp = RHS.get();
  5534. bool isObjCPointer;
  5535. if (PExp->getType()->isPointerType()) {
  5536. isObjCPointer = false;
  5537. } else if (PExp->getType()->isObjCObjectPointerType()) {
  5538. isObjCPointer = true;
  5539. } else {
  5540. std::swap(PExp, IExp);
  5541. if (PExp->getType()->isPointerType()) {
  5542. isObjCPointer = false;
  5543. } else if (PExp->getType()->isObjCObjectPointerType()) {
  5544. isObjCPointer = true;
  5545. } else {
  5546. return InvalidOperands(Loc, LHS, RHS);
  5547. }
  5548. }
  5549. assert(PExp->getType()->isAnyPointerType());
  5550. if (!IExp->getType()->isIntegerType())
  5551. return InvalidOperands(Loc, LHS, RHS);
  5552. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  5553. return QualType();
  5554. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  5555. return QualType();
  5556. // Check array bounds for pointer arithemtic
  5557. CheckArrayAccess(PExp, IExp);
  5558. if (CompLHSTy) {
  5559. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  5560. if (LHSTy.isNull()) {
  5561. LHSTy = LHS.get()->getType();
  5562. if (LHSTy->isPromotableIntegerType())
  5563. LHSTy = Context.getPromotedIntegerType(LHSTy);
  5564. }
  5565. *CompLHSTy = LHSTy;
  5566. }
  5567. return PExp->getType();
  5568. }
  5569. // C99 6.5.6
  5570. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  5571. SourceLocation Loc,
  5572. QualType* CompLHSTy) {
  5573. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  5574. if (LHS.get()->getType()->isVectorType() ||
  5575. RHS.get()->getType()->isVectorType()) {
  5576. QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
  5577. if (CompLHSTy) *CompLHSTy = compType;
  5578. return compType;
  5579. }
  5580. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  5581. if (LHS.isInvalid() || RHS.isInvalid())
  5582. return QualType();
  5583. // Enforce type constraints: C99 6.5.6p3.
  5584. // Handle the common case first (both operands are arithmetic).
  5585. if (!compType.isNull() && compType->isArithmeticType()) {
  5586. if (CompLHSTy) *CompLHSTy = compType;
  5587. return compType;
  5588. }
  5589. // Either ptr - int or ptr - ptr.
  5590. if (LHS.get()->getType()->isAnyPointerType()) {
  5591. QualType lpointee = LHS.get()->getType()->getPointeeType();
  5592. // Diagnose bad cases where we step over interface counts.
  5593. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  5594. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  5595. return QualType();
  5596. // The result type of a pointer-int computation is the pointer type.
  5597. if (RHS.get()->getType()->isIntegerType()) {
  5598. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  5599. return QualType();
  5600. // Check array bounds for pointer arithemtic
  5601. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
  5602. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  5603. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  5604. return LHS.get()->getType();
  5605. }
  5606. // Handle pointer-pointer subtractions.
  5607. if (const PointerType *RHSPTy
  5608. = RHS.get()->getType()->getAs<PointerType>()) {
  5609. QualType rpointee = RHSPTy->getPointeeType();
  5610. if (getLangOpts().CPlusPlus) {
  5611. // Pointee types must be the same: C++ [expr.add]
  5612. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  5613. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  5614. }
  5615. } else {
  5616. // Pointee types must be compatible C99 6.5.6p3
  5617. if (!Context.typesAreCompatible(
  5618. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  5619. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  5620. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  5621. return QualType();
  5622. }
  5623. }
  5624. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  5625. LHS.get(), RHS.get()))
  5626. return QualType();
  5627. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  5628. return Context.getPointerDiffType();
  5629. }
  5630. }
  5631. return InvalidOperands(Loc, LHS, RHS);
  5632. }
  5633. static bool isScopedEnumerationType(QualType T) {
  5634. if (const EnumType *ET = dyn_cast<EnumType>(T))
  5635. return ET->getDecl()->isScoped();
  5636. return false;
  5637. }
  5638. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  5639. SourceLocation Loc, unsigned Opc,
  5640. QualType LHSType) {
  5641. llvm::APSInt Right;
  5642. // Check right/shifter operand
  5643. if (RHS.get()->isValueDependent() ||
  5644. !RHS.get()->isIntegerConstantExpr(Right, S.Context))
  5645. return;
  5646. if (Right.isNegative()) {
  5647. S.DiagRuntimeBehavior(Loc, RHS.get(),
  5648. S.PDiag(diag::warn_shift_negative)
  5649. << RHS.get()->getSourceRange());
  5650. return;
  5651. }
  5652. llvm::APInt LeftBits(Right.getBitWidth(),
  5653. S.Context.getTypeSize(LHS.get()->getType()));
  5654. if (Right.uge(LeftBits)) {
  5655. S.DiagRuntimeBehavior(Loc, RHS.get(),
  5656. S.PDiag(diag::warn_shift_gt_typewidth)
  5657. << RHS.get()->getSourceRange());
  5658. return;
  5659. }
  5660. if (Opc != BO_Shl)
  5661. return;
  5662. // When left shifting an ICE which is signed, we can check for overflow which
  5663. // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
  5664. // integers have defined behavior modulo one more than the maximum value
  5665. // representable in the result type, so never warn for those.
  5666. llvm::APSInt Left;
  5667. if (LHS.get()->isValueDependent() ||
  5668. !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
  5669. LHSType->hasUnsignedIntegerRepresentation())
  5670. return;
  5671. llvm::APInt ResultBits =
  5672. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  5673. if (LeftBits.uge(ResultBits))
  5674. return;
  5675. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  5676. Result = Result.shl(Right);
  5677. // Print the bit representation of the signed integer as an unsigned
  5678. // hexadecimal number.
  5679. SmallString<40> HexResult;
  5680. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  5681. // If we are only missing a sign bit, this is less likely to result in actual
  5682. // bugs -- if the result is cast back to an unsigned type, it will have the
  5683. // expected value. Thus we place this behind a different warning that can be
  5684. // turned off separately if needed.
  5685. if (LeftBits == ResultBits - 1) {
  5686. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  5687. << HexResult.str() << LHSType
  5688. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5689. return;
  5690. }
  5691. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  5692. << HexResult.str() << Result.getMinSignedBits() << LHSType
  5693. << Left.getBitWidth() << LHS.get()->getSourceRange()
  5694. << RHS.get()->getSourceRange();
  5695. }
  5696. // C99 6.5.7
  5697. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  5698. SourceLocation Loc, unsigned Opc,
  5699. bool IsCompAssign) {
  5700. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  5701. // C99 6.5.7p2: Each of the operands shall have integer type.
  5702. if (!LHS.get()->getType()->hasIntegerRepresentation() ||
  5703. !RHS.get()->getType()->hasIntegerRepresentation())
  5704. return InvalidOperands(Loc, LHS, RHS);
  5705. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  5706. // hasIntegerRepresentation() above instead of this.
  5707. if (isScopedEnumerationType(LHS.get()->getType()) ||
  5708. isScopedEnumerationType(RHS.get()->getType())) {
  5709. return InvalidOperands(Loc, LHS, RHS);
  5710. }
  5711. // Vector shifts promote their scalar inputs to vector type.
  5712. if (LHS.get()->getType()->isVectorType() ||
  5713. RHS.get()->getType()->isVectorType())
  5714. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
  5715. // Shifts don't perform usual arithmetic conversions, they just do integer
  5716. // promotions on each operand. C99 6.5.7p3
  5717. // For the LHS, do usual unary conversions, but then reset them away
  5718. // if this is a compound assignment.
  5719. ExprResult OldLHS = LHS;
  5720. LHS = UsualUnaryConversions(LHS.take());
  5721. if (LHS.isInvalid())
  5722. return QualType();
  5723. QualType LHSType = LHS.get()->getType();
  5724. if (IsCompAssign) LHS = OldLHS;
  5725. // The RHS is simpler.
  5726. RHS = UsualUnaryConversions(RHS.take());
  5727. if (RHS.isInvalid())
  5728. return QualType();
  5729. // Sanity-check shift operands
  5730. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  5731. // "The type of the result is that of the promoted left operand."
  5732. return LHSType;
  5733. }
  5734. static bool IsWithinTemplateSpecialization(Decl *D) {
  5735. if (DeclContext *DC = D->getDeclContext()) {
  5736. if (isa<ClassTemplateSpecializationDecl>(DC))
  5737. return true;
  5738. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
  5739. return FD->isFunctionTemplateSpecialization();
  5740. }
  5741. return false;
  5742. }
  5743. /// If two different enums are compared, raise a warning.
  5744. static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
  5745. ExprResult &RHS) {
  5746. QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
  5747. QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
  5748. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  5749. if (!LHSEnumType)
  5750. return;
  5751. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  5752. if (!RHSEnumType)
  5753. return;
  5754. // Ignore anonymous enums.
  5755. if (!LHSEnumType->getDecl()->getIdentifier())
  5756. return;
  5757. if (!RHSEnumType->getDecl()->getIdentifier())
  5758. return;
  5759. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  5760. return;
  5761. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  5762. << LHSStrippedType << RHSStrippedType
  5763. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5764. }
  5765. /// \brief Diagnose bad pointer comparisons.
  5766. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  5767. ExprResult &LHS, ExprResult &RHS,
  5768. bool IsError) {
  5769. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  5770. : diag::ext_typecheck_comparison_of_distinct_pointers)
  5771. << LHS.get()->getType() << RHS.get()->getType()
  5772. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5773. }
  5774. /// \brief Returns false if the pointers are converted to a composite type,
  5775. /// true otherwise.
  5776. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  5777. ExprResult &LHS, ExprResult &RHS) {
  5778. // C++ [expr.rel]p2:
  5779. // [...] Pointer conversions (4.10) and qualification
  5780. // conversions (4.4) are performed on pointer operands (or on
  5781. // a pointer operand and a null pointer constant) to bring
  5782. // them to their composite pointer type. [...]
  5783. //
  5784. // C++ [expr.eq]p1 uses the same notion for (in)equality
  5785. // comparisons of pointers.
  5786. // C++ [expr.eq]p2:
  5787. // In addition, pointers to members can be compared, or a pointer to
  5788. // member and a null pointer constant. Pointer to member conversions
  5789. // (4.11) and qualification conversions (4.4) are performed to bring
  5790. // them to a common type. If one operand is a null pointer constant,
  5791. // the common type is the type of the other operand. Otherwise, the
  5792. // common type is a pointer to member type similar (4.4) to the type
  5793. // of one of the operands, with a cv-qualification signature (4.4)
  5794. // that is the union of the cv-qualification signatures of the operand
  5795. // types.
  5796. QualType LHSType = LHS.get()->getType();
  5797. QualType RHSType = RHS.get()->getType();
  5798. assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
  5799. (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
  5800. bool NonStandardCompositeType = false;
  5801. bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
  5802. QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
  5803. if (T.isNull()) {
  5804. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  5805. return true;
  5806. }
  5807. if (NonStandardCompositeType)
  5808. S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
  5809. << LHSType << RHSType << T << LHS.get()->getSourceRange()
  5810. << RHS.get()->getSourceRange();
  5811. LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
  5812. RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
  5813. return false;
  5814. }
  5815. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  5816. ExprResult &LHS,
  5817. ExprResult &RHS,
  5818. bool IsError) {
  5819. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  5820. : diag::ext_typecheck_comparison_of_fptr_to_void)
  5821. << LHS.get()->getType() << RHS.get()->getType()
  5822. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5823. }
  5824. static bool isObjCObjectLiteral(ExprResult &E) {
  5825. switch (E.get()->getStmtClass()) {
  5826. case Stmt::ObjCArrayLiteralClass:
  5827. case Stmt::ObjCDictionaryLiteralClass:
  5828. case Stmt::ObjCStringLiteralClass:
  5829. case Stmt::ObjCBoxedExprClass:
  5830. return true;
  5831. default:
  5832. // Note that ObjCBoolLiteral is NOT an object literal!
  5833. return false;
  5834. }
  5835. }
  5836. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  5837. // Get the LHS object's interface type.
  5838. QualType Type = LHS->getType();
  5839. QualType InterfaceType;
  5840. if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
  5841. InterfaceType = PTy->getPointeeType();
  5842. if (const ObjCObjectType *iQFaceTy =
  5843. InterfaceType->getAsObjCQualifiedInterfaceType())
  5844. InterfaceType = iQFaceTy->getBaseType();
  5845. } else {
  5846. // If this is not actually an Objective-C object, bail out.
  5847. return false;
  5848. }
  5849. // If the RHS isn't an Objective-C object, bail out.
  5850. if (!RHS->getType()->isObjCObjectPointerType())
  5851. return false;
  5852. // Try to find the -isEqual: method.
  5853. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  5854. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  5855. InterfaceType,
  5856. /*instance=*/true);
  5857. if (!Method) {
  5858. if (Type->isObjCIdType()) {
  5859. // For 'id', just check the global pool.
  5860. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  5861. /*receiverId=*/true,
  5862. /*warn=*/false);
  5863. } else {
  5864. // Check protocols.
  5865. Method = S.LookupMethodInQualifiedType(IsEqualSel,
  5866. cast<ObjCObjectPointerType>(Type),
  5867. /*instance=*/true);
  5868. }
  5869. }
  5870. if (!Method)
  5871. return false;
  5872. QualType T = Method->param_begin()[0]->getType();
  5873. if (!T->isObjCObjectPointerType())
  5874. return false;
  5875. QualType R = Method->getResultType();
  5876. if (!R->isScalarType())
  5877. return false;
  5878. return true;
  5879. }
  5880. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  5881. ExprResult &LHS, ExprResult &RHS,
  5882. BinaryOperator::Opcode Opc){
  5883. Expr *Literal;
  5884. Expr *Other;
  5885. if (isObjCObjectLiteral(LHS)) {
  5886. Literal = LHS.get();
  5887. Other = RHS.get();
  5888. } else {
  5889. Literal = RHS.get();
  5890. Other = LHS.get();
  5891. }
  5892. // Don't warn on comparisons against nil.
  5893. Other = Other->IgnoreParenCasts();
  5894. if (Other->isNullPointerConstant(S.getASTContext(),
  5895. Expr::NPC_ValueDependentIsNotNull))
  5896. return;
  5897. // This should be kept in sync with warn_objc_literal_comparison.
  5898. // LK_String should always be last, since it has its own warning flag.
  5899. enum {
  5900. LK_Array,
  5901. LK_Dictionary,
  5902. LK_Numeric,
  5903. LK_Boxed,
  5904. LK_String
  5905. } LiteralKind;
  5906. switch (Literal->getStmtClass()) {
  5907. case Stmt::ObjCStringLiteralClass:
  5908. // "string literal"
  5909. LiteralKind = LK_String;
  5910. break;
  5911. case Stmt::ObjCArrayLiteralClass:
  5912. // "array literal"
  5913. LiteralKind = LK_Array;
  5914. break;
  5915. case Stmt::ObjCDictionaryLiteralClass:
  5916. // "dictionary literal"
  5917. LiteralKind = LK_Dictionary;
  5918. break;
  5919. case Stmt::ObjCBoxedExprClass: {
  5920. Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
  5921. switch (Inner->getStmtClass()) {
  5922. case Stmt::IntegerLiteralClass:
  5923. case Stmt::FloatingLiteralClass:
  5924. case Stmt::CharacterLiteralClass:
  5925. case Stmt::ObjCBoolLiteralExprClass:
  5926. case Stmt::CXXBoolLiteralExprClass:
  5927. // "numeric literal"
  5928. LiteralKind = LK_Numeric;
  5929. break;
  5930. case Stmt::ImplicitCastExprClass: {
  5931. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  5932. // Boolean literals can be represented by implicit casts.
  5933. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
  5934. LiteralKind = LK_Numeric;
  5935. break;
  5936. }
  5937. // FALLTHROUGH
  5938. }
  5939. default:
  5940. // "boxed expression"
  5941. LiteralKind = LK_Boxed;
  5942. break;
  5943. }
  5944. break;
  5945. }
  5946. default:
  5947. llvm_unreachable("Unknown Objective-C object literal kind");
  5948. }
  5949. if (LiteralKind == LK_String)
  5950. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  5951. << Literal->getSourceRange();
  5952. else
  5953. S.Diag(Loc, diag::warn_objc_literal_comparison)
  5954. << LiteralKind << Literal->getSourceRange();
  5955. if (BinaryOperator::isEqualityOp(Opc) &&
  5956. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  5957. SourceLocation Start = LHS.get()->getLocStart();
  5958. SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
  5959. SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
  5960. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  5961. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  5962. << FixItHint::CreateReplacement(OpRange, "isEqual:")
  5963. << FixItHint::CreateInsertion(End, "]");
  5964. }
  5965. }
  5966. // C99 6.5.8, C++ [expr.rel]
  5967. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  5968. SourceLocation Loc, unsigned OpaqueOpc,
  5969. bool IsRelational) {
  5970. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
  5971. BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
  5972. // Handle vector comparisons separately.
  5973. if (LHS.get()->getType()->isVectorType() ||
  5974. RHS.get()->getType()->isVectorType())
  5975. return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
  5976. QualType LHSType = LHS.get()->getType();
  5977. QualType RHSType = RHS.get()->getType();
  5978. Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
  5979. Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
  5980. checkEnumComparison(*this, Loc, LHS, RHS);
  5981. if (!LHSType->hasFloatingRepresentation() &&
  5982. !(LHSType->isBlockPointerType() && IsRelational) &&
  5983. !LHS.get()->getLocStart().isMacroID() &&
  5984. !RHS.get()->getLocStart().isMacroID()) {
  5985. // For non-floating point types, check for self-comparisons of the form
  5986. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  5987. // often indicate logic errors in the program.
  5988. //
  5989. // NOTE: Don't warn about comparison expressions resulting from macro
  5990. // expansion. Also don't warn about comparisons which are only self
  5991. // comparisons within a template specialization. The warnings should catch
  5992. // obvious cases in the definition of the template anyways. The idea is to
  5993. // warn when the typed comparison operator will always evaluate to the same
  5994. // result.
  5995. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
  5996. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
  5997. if (DRL->getDecl() == DRR->getDecl() &&
  5998. !IsWithinTemplateSpecialization(DRL->getDecl())) {
  5999. DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
  6000. << 0 // self-
  6001. << (Opc == BO_EQ
  6002. || Opc == BO_LE
  6003. || Opc == BO_GE));
  6004. } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
  6005. !DRL->getDecl()->getType()->isReferenceType() &&
  6006. !DRR->getDecl()->getType()->isReferenceType()) {
  6007. // what is it always going to eval to?
  6008. char always_evals_to;
  6009. switch(Opc) {
  6010. case BO_EQ: // e.g. array1 == array2
  6011. always_evals_to = 0; // false
  6012. break;
  6013. case BO_NE: // e.g. array1 != array2
  6014. always_evals_to = 1; // true
  6015. break;
  6016. default:
  6017. // best we can say is 'a constant'
  6018. always_evals_to = 2; // e.g. array1 <= array2
  6019. break;
  6020. }
  6021. DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
  6022. << 1 // array
  6023. << always_evals_to);
  6024. }
  6025. }
  6026. }
  6027. if (isa<CastExpr>(LHSStripped))
  6028. LHSStripped = LHSStripped->IgnoreParenCasts();
  6029. if (isa<CastExpr>(RHSStripped))
  6030. RHSStripped = RHSStripped->IgnoreParenCasts();
  6031. // Warn about comparisons against a string constant (unless the other
  6032. // operand is null), the user probably wants strcmp.
  6033. Expr *literalString = 0;
  6034. Expr *literalStringStripped = 0;
  6035. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  6036. !RHSStripped->isNullPointerConstant(Context,
  6037. Expr::NPC_ValueDependentIsNull)) {
  6038. literalString = LHS.get();
  6039. literalStringStripped = LHSStripped;
  6040. } else if ((isa<StringLiteral>(RHSStripped) ||
  6041. isa<ObjCEncodeExpr>(RHSStripped)) &&
  6042. !LHSStripped->isNullPointerConstant(Context,
  6043. Expr::NPC_ValueDependentIsNull)) {
  6044. literalString = RHS.get();
  6045. literalStringStripped = RHSStripped;
  6046. }
  6047. if (literalString) {
  6048. std::string resultComparison;
  6049. switch (Opc) {
  6050. case BO_LT: resultComparison = ") < 0"; break;
  6051. case BO_GT: resultComparison = ") > 0"; break;
  6052. case BO_LE: resultComparison = ") <= 0"; break;
  6053. case BO_GE: resultComparison = ") >= 0"; break;
  6054. case BO_EQ: resultComparison = ") == 0"; break;
  6055. case BO_NE: resultComparison = ") != 0"; break;
  6056. default: llvm_unreachable("Invalid comparison operator");
  6057. }
  6058. DiagRuntimeBehavior(Loc, 0,
  6059. PDiag(diag::warn_stringcompare)
  6060. << isa<ObjCEncodeExpr>(literalStringStripped)
  6061. << literalString->getSourceRange());
  6062. }
  6063. }
  6064. // C99 6.5.8p3 / C99 6.5.9p4
  6065. if (LHS.get()->getType()->isArithmeticType() &&
  6066. RHS.get()->getType()->isArithmeticType()) {
  6067. UsualArithmeticConversions(LHS, RHS);
  6068. if (LHS.isInvalid() || RHS.isInvalid())
  6069. return QualType();
  6070. }
  6071. else {
  6072. LHS = UsualUnaryConversions(LHS.take());
  6073. if (LHS.isInvalid())
  6074. return QualType();
  6075. RHS = UsualUnaryConversions(RHS.take());
  6076. if (RHS.isInvalid())
  6077. return QualType();
  6078. }
  6079. LHSType = LHS.get()->getType();
  6080. RHSType = RHS.get()->getType();
  6081. // The result of comparisons is 'bool' in C++, 'int' in C.
  6082. QualType ResultTy = Context.getLogicalOperationType();
  6083. if (IsRelational) {
  6084. if (LHSType->isRealType() && RHSType->isRealType())
  6085. return ResultTy;
  6086. } else {
  6087. // Check for comparisons of floating point operands using != and ==.
  6088. if (LHSType->hasFloatingRepresentation())
  6089. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  6090. if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
  6091. return ResultTy;
  6092. }
  6093. bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
  6094. Expr::NPC_ValueDependentIsNull);
  6095. bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
  6096. Expr::NPC_ValueDependentIsNull);
  6097. // All of the following pointer-related warnings are GCC extensions, except
  6098. // when handling null pointer constants.
  6099. if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
  6100. QualType LCanPointeeTy =
  6101. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  6102. QualType RCanPointeeTy =
  6103. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  6104. if (getLangOpts().CPlusPlus) {
  6105. if (LCanPointeeTy == RCanPointeeTy)
  6106. return ResultTy;
  6107. if (!IsRelational &&
  6108. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  6109. // Valid unless comparison between non-null pointer and function pointer
  6110. // This is a gcc extension compatibility comparison.
  6111. // In a SFINAE context, we treat this as a hard error to maintain
  6112. // conformance with the C++ standard.
  6113. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  6114. && !LHSIsNull && !RHSIsNull) {
  6115. diagnoseFunctionPointerToVoidComparison(
  6116. *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
  6117. if (isSFINAEContext())
  6118. return QualType();
  6119. RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
  6120. return ResultTy;
  6121. }
  6122. }
  6123. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  6124. return QualType();
  6125. else
  6126. return ResultTy;
  6127. }
  6128. // C99 6.5.9p2 and C99 6.5.8p2
  6129. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  6130. RCanPointeeTy.getUnqualifiedType())) {
  6131. // Valid unless a relational comparison of function pointers
  6132. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  6133. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  6134. << LHSType << RHSType << LHS.get()->getSourceRange()
  6135. << RHS.get()->getSourceRange();
  6136. }
  6137. } else if (!IsRelational &&
  6138. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  6139. // Valid unless comparison between non-null pointer and function pointer
  6140. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  6141. && !LHSIsNull && !RHSIsNull)
  6142. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  6143. /*isError*/false);
  6144. } else {
  6145. // Invalid
  6146. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  6147. }
  6148. if (LCanPointeeTy != RCanPointeeTy) {
  6149. if (LHSIsNull && !RHSIsNull)
  6150. LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
  6151. else
  6152. RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
  6153. }
  6154. return ResultTy;
  6155. }
  6156. if (getLangOpts().CPlusPlus) {
  6157. // Comparison of nullptr_t with itself.
  6158. if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
  6159. return ResultTy;
  6160. // Comparison of pointers with null pointer constants and equality
  6161. // comparisons of member pointers to null pointer constants.
  6162. if (RHSIsNull &&
  6163. ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
  6164. (!IsRelational &&
  6165. (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
  6166. RHS = ImpCastExprToType(RHS.take(), LHSType,
  6167. LHSType->isMemberPointerType()
  6168. ? CK_NullToMemberPointer
  6169. : CK_NullToPointer);
  6170. return ResultTy;
  6171. }
  6172. if (LHSIsNull &&
  6173. ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
  6174. (!IsRelational &&
  6175. (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
  6176. LHS = ImpCastExprToType(LHS.take(), RHSType,
  6177. RHSType->isMemberPointerType()
  6178. ? CK_NullToMemberPointer
  6179. : CK_NullToPointer);
  6180. return ResultTy;
  6181. }
  6182. // Comparison of member pointers.
  6183. if (!IsRelational &&
  6184. LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
  6185. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  6186. return QualType();
  6187. else
  6188. return ResultTy;
  6189. }
  6190. // Handle scoped enumeration types specifically, since they don't promote
  6191. // to integers.
  6192. if (LHS.get()->getType()->isEnumeralType() &&
  6193. Context.hasSameUnqualifiedType(LHS.get()->getType(),
  6194. RHS.get()->getType()))
  6195. return ResultTy;
  6196. }
  6197. // Handle block pointer types.
  6198. if (!IsRelational && LHSType->isBlockPointerType() &&
  6199. RHSType->isBlockPointerType()) {
  6200. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  6201. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  6202. if (!LHSIsNull && !RHSIsNull &&
  6203. !Context.typesAreCompatible(lpointee, rpointee)) {
  6204. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  6205. << LHSType << RHSType << LHS.get()->getSourceRange()
  6206. << RHS.get()->getSourceRange();
  6207. }
  6208. RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
  6209. return ResultTy;
  6210. }
  6211. // Allow block pointers to be compared with null pointer constants.
  6212. if (!IsRelational
  6213. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  6214. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  6215. if (!LHSIsNull && !RHSIsNull) {
  6216. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  6217. ->getPointeeType()->isVoidType())
  6218. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  6219. ->getPointeeType()->isVoidType())))
  6220. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  6221. << LHSType << RHSType << LHS.get()->getSourceRange()
  6222. << RHS.get()->getSourceRange();
  6223. }
  6224. if (LHSIsNull && !RHSIsNull)
  6225. LHS = ImpCastExprToType(LHS.take(), RHSType,
  6226. RHSType->isPointerType() ? CK_BitCast
  6227. : CK_AnyPointerToBlockPointerCast);
  6228. else
  6229. RHS = ImpCastExprToType(RHS.take(), LHSType,
  6230. LHSType->isPointerType() ? CK_BitCast
  6231. : CK_AnyPointerToBlockPointerCast);
  6232. return ResultTy;
  6233. }
  6234. if (LHSType->isObjCObjectPointerType() ||
  6235. RHSType->isObjCObjectPointerType()) {
  6236. const PointerType *LPT = LHSType->getAs<PointerType>();
  6237. const PointerType *RPT = RHSType->getAs<PointerType>();
  6238. if (LPT || RPT) {
  6239. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  6240. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  6241. if (!LPtrToVoid && !RPtrToVoid &&
  6242. !Context.typesAreCompatible(LHSType, RHSType)) {
  6243. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  6244. /*isError*/false);
  6245. }
  6246. if (LHSIsNull && !RHSIsNull)
  6247. LHS = ImpCastExprToType(LHS.take(), RHSType,
  6248. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  6249. else
  6250. RHS = ImpCastExprToType(RHS.take(), LHSType,
  6251. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  6252. return ResultTy;
  6253. }
  6254. if (LHSType->isObjCObjectPointerType() &&
  6255. RHSType->isObjCObjectPointerType()) {
  6256. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  6257. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  6258. /*isError*/false);
  6259. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  6260. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  6261. if (LHSIsNull && !RHSIsNull)
  6262. LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
  6263. else
  6264. RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
  6265. return ResultTy;
  6266. }
  6267. }
  6268. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  6269. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  6270. unsigned DiagID = 0;
  6271. bool isError = false;
  6272. if ((LHSIsNull && LHSType->isIntegerType()) ||
  6273. (RHSIsNull && RHSType->isIntegerType())) {
  6274. if (IsRelational && !getLangOpts().CPlusPlus)
  6275. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  6276. } else if (IsRelational && !getLangOpts().CPlusPlus)
  6277. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  6278. else if (getLangOpts().CPlusPlus) {
  6279. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  6280. isError = true;
  6281. } else
  6282. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  6283. if (DiagID) {
  6284. Diag(Loc, DiagID)
  6285. << LHSType << RHSType << LHS.get()->getSourceRange()
  6286. << RHS.get()->getSourceRange();
  6287. if (isError)
  6288. return QualType();
  6289. }
  6290. if (LHSType->isIntegerType())
  6291. LHS = ImpCastExprToType(LHS.take(), RHSType,
  6292. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  6293. else
  6294. RHS = ImpCastExprToType(RHS.take(), LHSType,
  6295. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  6296. return ResultTy;
  6297. }
  6298. // Handle block pointers.
  6299. if (!IsRelational && RHSIsNull
  6300. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  6301. RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
  6302. return ResultTy;
  6303. }
  6304. if (!IsRelational && LHSIsNull
  6305. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  6306. LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
  6307. return ResultTy;
  6308. }
  6309. return InvalidOperands(Loc, LHS, RHS);
  6310. }
  6311. // Return a signed type that is of identical size and number of elements.
  6312. // For floating point vectors, return an integer type of identical size
  6313. // and number of elements.
  6314. QualType Sema::GetSignedVectorType(QualType V) {
  6315. const VectorType *VTy = V->getAs<VectorType>();
  6316. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  6317. if (TypeSize == Context.getTypeSize(Context.CharTy))
  6318. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  6319. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  6320. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  6321. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  6322. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  6323. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  6324. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  6325. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  6326. "Unhandled vector element size in vector compare");
  6327. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  6328. }
  6329. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  6330. /// operates on extended vector types. Instead of producing an IntTy result,
  6331. /// like a scalar comparison, a vector comparison produces a vector of integer
  6332. /// types.
  6333. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  6334. SourceLocation Loc,
  6335. bool IsRelational) {
  6336. // Check to make sure we're operating on vectors of the same type and width,
  6337. // Allowing one side to be a scalar of element type.
  6338. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
  6339. if (vType.isNull())
  6340. return vType;
  6341. QualType LHSType = LHS.get()->getType();
  6342. // If AltiVec, the comparison results in a numeric type, i.e.
  6343. // bool for C++, int for C
  6344. if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  6345. return Context.getLogicalOperationType();
  6346. // For non-floating point types, check for self-comparisons of the form
  6347. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  6348. // often indicate logic errors in the program.
  6349. if (!LHSType->hasFloatingRepresentation()) {
  6350. if (DeclRefExpr* DRL
  6351. = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
  6352. if (DeclRefExpr* DRR
  6353. = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
  6354. if (DRL->getDecl() == DRR->getDecl())
  6355. DiagRuntimeBehavior(Loc, 0,
  6356. PDiag(diag::warn_comparison_always)
  6357. << 0 // self-
  6358. << 2 // "a constant"
  6359. );
  6360. }
  6361. // Check for comparisons of floating point operands using != and ==.
  6362. if (!IsRelational && LHSType->hasFloatingRepresentation()) {
  6363. assert (RHS.get()->getType()->hasFloatingRepresentation());
  6364. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  6365. }
  6366. // Return a signed type for the vector.
  6367. return GetSignedVectorType(LHSType);
  6368. }
  6369. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  6370. SourceLocation Loc) {
  6371. // Ensure that either both operands are of the same vector type, or
  6372. // one operand is of a vector type and the other is of its element type.
  6373. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
  6374. if (vType.isNull() || vType->isFloatingType())
  6375. return InvalidOperands(Loc, LHS, RHS);
  6376. return GetSignedVectorType(LHS.get()->getType());
  6377. }
  6378. inline QualType Sema::CheckBitwiseOperands(
  6379. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  6380. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6381. if (LHS.get()->getType()->isVectorType() ||
  6382. RHS.get()->getType()->isVectorType()) {
  6383. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  6384. RHS.get()->getType()->hasIntegerRepresentation())
  6385. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
  6386. return InvalidOperands(Loc, LHS, RHS);
  6387. }
  6388. ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
  6389. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  6390. IsCompAssign);
  6391. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  6392. return QualType();
  6393. LHS = LHSResult.take();
  6394. RHS = RHSResult.take();
  6395. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  6396. return compType;
  6397. return InvalidOperands(Loc, LHS, RHS);
  6398. }
  6399. inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
  6400. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
  6401. // Check vector operands differently.
  6402. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  6403. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  6404. // Diagnose cases where the user write a logical and/or but probably meant a
  6405. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  6406. // is a constant.
  6407. if (LHS.get()->getType()->isIntegerType() &&
  6408. !LHS.get()->getType()->isBooleanType() &&
  6409. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  6410. // Don't warn in macros or template instantiations.
  6411. !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
  6412. // If the RHS can be constant folded, and if it constant folds to something
  6413. // that isn't 0 or 1 (which indicate a potential logical operation that
  6414. // happened to fold to true/false) then warn.
  6415. // Parens on the RHS are ignored.
  6416. llvm::APSInt Result;
  6417. if (RHS.get()->EvaluateAsInt(Result, Context))
  6418. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
  6419. (Result != 0 && Result != 1)) {
  6420. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  6421. << RHS.get()->getSourceRange()
  6422. << (Opc == BO_LAnd ? "&&" : "||");
  6423. // Suggest replacing the logical operator with the bitwise version
  6424. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  6425. << (Opc == BO_LAnd ? "&" : "|")
  6426. << FixItHint::CreateReplacement(SourceRange(
  6427. Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
  6428. getLangOpts())),
  6429. Opc == BO_LAnd ? "&" : "|");
  6430. if (Opc == BO_LAnd)
  6431. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  6432. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  6433. << FixItHint::CreateRemoval(
  6434. SourceRange(
  6435. Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
  6436. 0, getSourceManager(),
  6437. getLangOpts()),
  6438. RHS.get()->getLocEnd()));
  6439. }
  6440. }
  6441. if (!Context.getLangOpts().CPlusPlus) {
  6442. LHS = UsualUnaryConversions(LHS.take());
  6443. if (LHS.isInvalid())
  6444. return QualType();
  6445. RHS = UsualUnaryConversions(RHS.take());
  6446. if (RHS.isInvalid())
  6447. return QualType();
  6448. if (!LHS.get()->getType()->isScalarType() ||
  6449. !RHS.get()->getType()->isScalarType())
  6450. return InvalidOperands(Loc, LHS, RHS);
  6451. return Context.IntTy;
  6452. }
  6453. // The following is safe because we only use this method for
  6454. // non-overloadable operands.
  6455. // C++ [expr.log.and]p1
  6456. // C++ [expr.log.or]p1
  6457. // The operands are both contextually converted to type bool.
  6458. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  6459. if (LHSRes.isInvalid())
  6460. return InvalidOperands(Loc, LHS, RHS);
  6461. LHS = LHSRes;
  6462. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  6463. if (RHSRes.isInvalid())
  6464. return InvalidOperands(Loc, LHS, RHS);
  6465. RHS = RHSRes;
  6466. // C++ [expr.log.and]p2
  6467. // C++ [expr.log.or]p2
  6468. // The result is a bool.
  6469. return Context.BoolTy;
  6470. }
  6471. /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
  6472. /// is a read-only property; return true if so. A readonly property expression
  6473. /// depends on various declarations and thus must be treated specially.
  6474. ///
  6475. static bool IsReadonlyProperty(Expr *E, Sema &S) {
  6476. const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
  6477. if (!PropExpr) return false;
  6478. if (PropExpr->isImplicitProperty()) return false;
  6479. ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
  6480. QualType BaseType = PropExpr->isSuperReceiver() ?
  6481. PropExpr->getSuperReceiverType() :
  6482. PropExpr->getBase()->getType();
  6483. if (const ObjCObjectPointerType *OPT =
  6484. BaseType->getAsObjCInterfacePointerType())
  6485. if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
  6486. if (S.isPropertyReadonly(PDecl, IFace))
  6487. return true;
  6488. return false;
  6489. }
  6490. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  6491. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  6492. if (!ME) return false;
  6493. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  6494. ObjCMessageExpr *Base =
  6495. dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
  6496. if (!Base) return false;
  6497. return Base->getMethodDecl() != 0;
  6498. }
  6499. /// Is the given expression (which must be 'const') a reference to a
  6500. /// variable which was originally non-const, but which has become
  6501. /// 'const' due to being captured within a block?
  6502. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  6503. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  6504. assert(E->isLValue() && E->getType().isConstQualified());
  6505. E = E->IgnoreParens();
  6506. // Must be a reference to a declaration from an enclosing scope.
  6507. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  6508. if (!DRE) return NCCK_None;
  6509. if (!DRE->refersToEnclosingLocal()) return NCCK_None;
  6510. // The declaration must be a variable which is not declared 'const'.
  6511. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  6512. if (!var) return NCCK_None;
  6513. if (var->getType().isConstQualified()) return NCCK_None;
  6514. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  6515. // Decide whether the first capture was for a block or a lambda.
  6516. DeclContext *DC = S.CurContext;
  6517. while (DC->getParent() != var->getDeclContext())
  6518. DC = DC->getParent();
  6519. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  6520. }
  6521. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  6522. /// emit an error and return true. If so, return false.
  6523. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  6524. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  6525. SourceLocation OrigLoc = Loc;
  6526. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  6527. &Loc);
  6528. if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
  6529. IsLV = Expr::MLV_ReadonlyProperty;
  6530. else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  6531. IsLV = Expr::MLV_InvalidMessageExpression;
  6532. if (IsLV == Expr::MLV_Valid)
  6533. return false;
  6534. unsigned Diag = 0;
  6535. bool NeedType = false;
  6536. switch (IsLV) { // C99 6.5.16p2
  6537. case Expr::MLV_ConstQualified:
  6538. Diag = diag::err_typecheck_assign_const;
  6539. // Use a specialized diagnostic when we're assigning to an object
  6540. // from an enclosing function or block.
  6541. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  6542. if (NCCK == NCCK_Block)
  6543. Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
  6544. else
  6545. Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  6546. break;
  6547. }
  6548. // In ARC, use some specialized diagnostics for occasions where we
  6549. // infer 'const'. These are always pseudo-strong variables.
  6550. if (S.getLangOpts().ObjCAutoRefCount) {
  6551. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  6552. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  6553. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  6554. // Use the normal diagnostic if it's pseudo-__strong but the
  6555. // user actually wrote 'const'.
  6556. if (var->isARCPseudoStrong() &&
  6557. (!var->getTypeSourceInfo() ||
  6558. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  6559. // There are two pseudo-strong cases:
  6560. // - self
  6561. ObjCMethodDecl *method = S.getCurMethodDecl();
  6562. if (method && var == method->getSelfDecl())
  6563. Diag = method->isClassMethod()
  6564. ? diag::err_typecheck_arc_assign_self_class_method
  6565. : diag::err_typecheck_arc_assign_self;
  6566. // - fast enumeration variables
  6567. else
  6568. Diag = diag::err_typecheck_arr_assign_enumeration;
  6569. SourceRange Assign;
  6570. if (Loc != OrigLoc)
  6571. Assign = SourceRange(OrigLoc, OrigLoc);
  6572. S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
  6573. // We need to preserve the AST regardless, so migration tool
  6574. // can do its job.
  6575. return false;
  6576. }
  6577. }
  6578. }
  6579. break;
  6580. case Expr::MLV_ArrayType:
  6581. case Expr::MLV_ArrayTemporary:
  6582. Diag = diag::err_typecheck_array_not_modifiable_lvalue;
  6583. NeedType = true;
  6584. break;
  6585. case Expr::MLV_NotObjectType:
  6586. Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
  6587. NeedType = true;
  6588. break;
  6589. case Expr::MLV_LValueCast:
  6590. Diag = diag::err_typecheck_lvalue_casts_not_supported;
  6591. break;
  6592. case Expr::MLV_Valid:
  6593. llvm_unreachable("did not take early return for MLV_Valid");
  6594. case Expr::MLV_InvalidExpression:
  6595. case Expr::MLV_MemberFunction:
  6596. case Expr::MLV_ClassTemporary:
  6597. Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
  6598. break;
  6599. case Expr::MLV_IncompleteType:
  6600. case Expr::MLV_IncompleteVoidType:
  6601. return S.RequireCompleteType(Loc, E->getType(),
  6602. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  6603. case Expr::MLV_DuplicateVectorComponents:
  6604. Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  6605. break;
  6606. case Expr::MLV_ReadonlyProperty:
  6607. case Expr::MLV_NoSetterProperty:
  6608. llvm_unreachable("readonly properties should be processed differently");
  6609. case Expr::MLV_InvalidMessageExpression:
  6610. Diag = diag::error_readonly_message_assignment;
  6611. break;
  6612. case Expr::MLV_SubObjCPropertySetting:
  6613. Diag = diag::error_no_subobject_property_setting;
  6614. break;
  6615. }
  6616. SourceRange Assign;
  6617. if (Loc != OrigLoc)
  6618. Assign = SourceRange(OrigLoc, OrigLoc);
  6619. if (NeedType)
  6620. S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
  6621. else
  6622. S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
  6623. return true;
  6624. }
  6625. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  6626. SourceLocation Loc,
  6627. Sema &Sema) {
  6628. // C / C++ fields
  6629. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  6630. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  6631. if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
  6632. if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
  6633. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  6634. }
  6635. // Objective-C instance variables
  6636. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  6637. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  6638. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  6639. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  6640. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  6641. if (RL && RR && RL->getDecl() == RR->getDecl())
  6642. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  6643. }
  6644. }
  6645. // C99 6.5.16.1
  6646. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  6647. SourceLocation Loc,
  6648. QualType CompoundType) {
  6649. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  6650. // Verify that LHS is a modifiable lvalue, and emit error if not.
  6651. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  6652. return QualType();
  6653. QualType LHSType = LHSExpr->getType();
  6654. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  6655. CompoundType;
  6656. AssignConvertType ConvTy;
  6657. if (CompoundType.isNull()) {
  6658. Expr *RHSCheck = RHS.get();
  6659. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  6660. QualType LHSTy(LHSType);
  6661. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  6662. if (RHS.isInvalid())
  6663. return QualType();
  6664. // Special case of NSObject attributes on c-style pointer types.
  6665. if (ConvTy == IncompatiblePointer &&
  6666. ((Context.isObjCNSObjectType(LHSType) &&
  6667. RHSType->isObjCObjectPointerType()) ||
  6668. (Context.isObjCNSObjectType(RHSType) &&
  6669. LHSType->isObjCObjectPointerType())))
  6670. ConvTy = Compatible;
  6671. if (ConvTy == Compatible &&
  6672. LHSType->isObjCObjectType())
  6673. Diag(Loc, diag::err_objc_object_assignment)
  6674. << LHSType;
  6675. // If the RHS is a unary plus or minus, check to see if they = and + are
  6676. // right next to each other. If so, the user may have typo'd "x =+ 4"
  6677. // instead of "x += 4".
  6678. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  6679. RHSCheck = ICE->getSubExpr();
  6680. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  6681. if ((UO->getOpcode() == UO_Plus ||
  6682. UO->getOpcode() == UO_Minus) &&
  6683. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  6684. // Only if the two operators are exactly adjacent.
  6685. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  6686. // And there is a space or other character before the subexpr of the
  6687. // unary +/-. We don't want to warn on "x=-1".
  6688. Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
  6689. UO->getSubExpr()->getLocStart().isFileID()) {
  6690. Diag(Loc, diag::warn_not_compound_assign)
  6691. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  6692. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  6693. }
  6694. }
  6695. if (ConvTy == Compatible) {
  6696. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
  6697. checkRetainCycles(LHSExpr, RHS.get());
  6698. else if (getLangOpts().ObjCAutoRefCount)
  6699. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  6700. }
  6701. } else {
  6702. // Compound assignment "x += y"
  6703. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  6704. }
  6705. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  6706. RHS.get(), AA_Assigning))
  6707. return QualType();
  6708. CheckForNullPointerDereference(*this, LHSExpr);
  6709. // C99 6.5.16p3: The type of an assignment expression is the type of the
  6710. // left operand unless the left operand has qualified type, in which case
  6711. // it is the unqualified version of the type of the left operand.
  6712. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  6713. // is converted to the type of the assignment expression (above).
  6714. // C++ 5.17p1: the type of the assignment expression is that of its left
  6715. // operand.
  6716. return (getLangOpts().CPlusPlus
  6717. ? LHSType : LHSType.getUnqualifiedType());
  6718. }
  6719. // C99 6.5.17
  6720. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  6721. SourceLocation Loc) {
  6722. LHS = S.CheckPlaceholderExpr(LHS.take());
  6723. RHS = S.CheckPlaceholderExpr(RHS.take());
  6724. if (LHS.isInvalid() || RHS.isInvalid())
  6725. return QualType();
  6726. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  6727. // operands, but not unary promotions.
  6728. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  6729. // So we treat the LHS as a ignored value, and in C++ we allow the
  6730. // containing site to determine what should be done with the RHS.
  6731. LHS = S.IgnoredValueConversions(LHS.take());
  6732. if (LHS.isInvalid())
  6733. return QualType();
  6734. S.DiagnoseUnusedExprResult(LHS.get());
  6735. if (!S.getLangOpts().CPlusPlus) {
  6736. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
  6737. if (RHS.isInvalid())
  6738. return QualType();
  6739. if (!RHS.get()->getType()->isVoidType())
  6740. S.RequireCompleteType(Loc, RHS.get()->getType(),
  6741. diag::err_incomplete_type);
  6742. }
  6743. return RHS.get()->getType();
  6744. }
  6745. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  6746. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  6747. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  6748. ExprValueKind &VK,
  6749. SourceLocation OpLoc,
  6750. bool IsInc, bool IsPrefix) {
  6751. if (Op->isTypeDependent())
  6752. return S.Context.DependentTy;
  6753. QualType ResType = Op->getType();
  6754. // Atomic types can be used for increment / decrement where the non-atomic
  6755. // versions can, so ignore the _Atomic() specifier for the purpose of
  6756. // checking.
  6757. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6758. ResType = ResAtomicType->getValueType();
  6759. assert(!ResType.isNull() && "no type for increment/decrement expression");
  6760. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  6761. // Decrement of bool is not allowed.
  6762. if (!IsInc) {
  6763. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  6764. return QualType();
  6765. }
  6766. // Increment of bool sets it to true, but is deprecated.
  6767. S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
  6768. } else if (ResType->isRealType()) {
  6769. // OK!
  6770. } else if (ResType->isPointerType()) {
  6771. // C99 6.5.2.4p2, 6.5.6p2
  6772. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  6773. return QualType();
  6774. } else if (ResType->isObjCObjectPointerType()) {
  6775. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  6776. // Otherwise, we just need a complete type.
  6777. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  6778. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  6779. return QualType();
  6780. } else if (ResType->isAnyComplexType()) {
  6781. // C99 does not support ++/-- on complex types, we allow as an extension.
  6782. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  6783. << ResType << Op->getSourceRange();
  6784. } else if (ResType->isPlaceholderType()) {
  6785. ExprResult PR = S.CheckPlaceholderExpr(Op);
  6786. if (PR.isInvalid()) return QualType();
  6787. return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
  6788. IsInc, IsPrefix);
  6789. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  6790. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  6791. } else {
  6792. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  6793. << ResType << int(IsInc) << Op->getSourceRange();
  6794. return QualType();
  6795. }
  6796. // At this point, we know we have a real, complex or pointer type.
  6797. // Now make sure the operand is a modifiable lvalue.
  6798. if (CheckForModifiableLvalue(Op, OpLoc, S))
  6799. return QualType();
  6800. // In C++, a prefix increment is the same type as the operand. Otherwise
  6801. // (in C or with postfix), the increment is the unqualified type of the
  6802. // operand.
  6803. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  6804. VK = VK_LValue;
  6805. return ResType;
  6806. } else {
  6807. VK = VK_RValue;
  6808. return ResType.getUnqualifiedType();
  6809. }
  6810. }
  6811. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  6812. /// This routine allows us to typecheck complex/recursive expressions
  6813. /// where the declaration is needed for type checking. We only need to
  6814. /// handle cases when the expression references a function designator
  6815. /// or is an lvalue. Here are some examples:
  6816. /// - &(x) => x
  6817. /// - &*****f => f for f a function designator.
  6818. /// - &s.xx => s
  6819. /// - &s.zz[1].yy -> s, if zz is an array
  6820. /// - *(x + 1) -> x, if x is an array
  6821. /// - &"123"[2] -> 0
  6822. /// - & __real__ x -> x
  6823. static ValueDecl *getPrimaryDecl(Expr *E) {
  6824. switch (E->getStmtClass()) {
  6825. case Stmt::DeclRefExprClass:
  6826. return cast<DeclRefExpr>(E)->getDecl();
  6827. case Stmt::MemberExprClass:
  6828. // If this is an arrow operator, the address is an offset from
  6829. // the base's value, so the object the base refers to is
  6830. // irrelevant.
  6831. if (cast<MemberExpr>(E)->isArrow())
  6832. return 0;
  6833. // Otherwise, the expression refers to a part of the base
  6834. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  6835. case Stmt::ArraySubscriptExprClass: {
  6836. // FIXME: This code shouldn't be necessary! We should catch the implicit
  6837. // promotion of register arrays earlier.
  6838. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  6839. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  6840. if (ICE->getSubExpr()->getType()->isArrayType())
  6841. return getPrimaryDecl(ICE->getSubExpr());
  6842. }
  6843. return 0;
  6844. }
  6845. case Stmt::UnaryOperatorClass: {
  6846. UnaryOperator *UO = cast<UnaryOperator>(E);
  6847. switch(UO->getOpcode()) {
  6848. case UO_Real:
  6849. case UO_Imag:
  6850. case UO_Extension:
  6851. return getPrimaryDecl(UO->getSubExpr());
  6852. default:
  6853. return 0;
  6854. }
  6855. }
  6856. case Stmt::ParenExprClass:
  6857. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  6858. case Stmt::ImplicitCastExprClass:
  6859. // If the result of an implicit cast is an l-value, we care about
  6860. // the sub-expression; otherwise, the result here doesn't matter.
  6861. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  6862. default:
  6863. return 0;
  6864. }
  6865. }
  6866. namespace {
  6867. enum {
  6868. AO_Bit_Field = 0,
  6869. AO_Vector_Element = 1,
  6870. AO_Property_Expansion = 2,
  6871. AO_Register_Variable = 3,
  6872. AO_No_Error = 4
  6873. };
  6874. }
  6875. /// \brief Diagnose invalid operand for address of operations.
  6876. ///
  6877. /// \param Type The type of operand which cannot have its address taken.
  6878. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  6879. Expr *E, unsigned Type) {
  6880. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  6881. }
  6882. /// CheckAddressOfOperand - The operand of & must be either a function
  6883. /// designator or an lvalue designating an object. If it is an lvalue, the
  6884. /// object cannot be declared with storage class register or be a bit field.
  6885. /// Note: The usual conversions are *not* applied to the operand of the &
  6886. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  6887. /// In C++, the operand might be an overloaded function name, in which case
  6888. /// we allow the '&' but retain the overloaded-function type.
  6889. static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
  6890. SourceLocation OpLoc) {
  6891. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  6892. if (PTy->getKind() == BuiltinType::Overload) {
  6893. if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
  6894. S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  6895. << OrigOp.get()->getSourceRange();
  6896. return QualType();
  6897. }
  6898. return S.Context.OverloadTy;
  6899. }
  6900. if (PTy->getKind() == BuiltinType::UnknownAny)
  6901. return S.Context.UnknownAnyTy;
  6902. if (PTy->getKind() == BuiltinType::BoundMember) {
  6903. S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  6904. << OrigOp.get()->getSourceRange();
  6905. return QualType();
  6906. }
  6907. OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
  6908. if (OrigOp.isInvalid()) return QualType();
  6909. }
  6910. if (OrigOp.get()->isTypeDependent())
  6911. return S.Context.DependentTy;
  6912. assert(!OrigOp.get()->getType()->isPlaceholderType());
  6913. // Make sure to ignore parentheses in subsequent checks
  6914. Expr *op = OrigOp.get()->IgnoreParens();
  6915. if (S.getLangOpts().C99) {
  6916. // Implement C99-only parts of addressof rules.
  6917. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  6918. if (uOp->getOpcode() == UO_Deref)
  6919. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  6920. // (assuming the deref expression is valid).
  6921. return uOp->getSubExpr()->getType();
  6922. }
  6923. // Technically, there should be a check for array subscript
  6924. // expressions here, but the result of one is always an lvalue anyway.
  6925. }
  6926. ValueDecl *dcl = getPrimaryDecl(op);
  6927. Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
  6928. unsigned AddressOfError = AO_No_Error;
  6929. if (lval == Expr::LV_ClassTemporary) {
  6930. bool sfinae = S.isSFINAEContext();
  6931. S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
  6932. : diag::ext_typecheck_addrof_class_temporary)
  6933. << op->getType() << op->getSourceRange();
  6934. if (sfinae)
  6935. return QualType();
  6936. } else if (isa<ObjCSelectorExpr>(op)) {
  6937. return S.Context.getPointerType(op->getType());
  6938. } else if (lval == Expr::LV_MemberFunction) {
  6939. // If it's an instance method, make a member pointer.
  6940. // The expression must have exactly the form &A::foo.
  6941. // If the underlying expression isn't a decl ref, give up.
  6942. if (!isa<DeclRefExpr>(op)) {
  6943. S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  6944. << OrigOp.get()->getSourceRange();
  6945. return QualType();
  6946. }
  6947. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  6948. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  6949. // The id-expression was parenthesized.
  6950. if (OrigOp.get() != DRE) {
  6951. S.Diag(OpLoc, diag::err_parens_pointer_member_function)
  6952. << OrigOp.get()->getSourceRange();
  6953. // The method was named without a qualifier.
  6954. } else if (!DRE->getQualifier()) {
  6955. S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  6956. << op->getSourceRange();
  6957. }
  6958. return S.Context.getMemberPointerType(op->getType(),
  6959. S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
  6960. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  6961. // C99 6.5.3.2p1
  6962. // The operand must be either an l-value or a function designator
  6963. if (!op->getType()->isFunctionType()) {
  6964. // Use a special diagnostic for loads from property references.
  6965. if (isa<PseudoObjectExpr>(op)) {
  6966. AddressOfError = AO_Property_Expansion;
  6967. } else {
  6968. // FIXME: emit more specific diag...
  6969. S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  6970. << op->getSourceRange();
  6971. return QualType();
  6972. }
  6973. }
  6974. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  6975. // The operand cannot be a bit-field
  6976. AddressOfError = AO_Bit_Field;
  6977. } else if (op->getObjectKind() == OK_VectorComponent) {
  6978. // The operand cannot be an element of a vector
  6979. AddressOfError = AO_Vector_Element;
  6980. } else if (dcl) { // C99 6.5.3.2p1
  6981. // We have an lvalue with a decl. Make sure the decl is not declared
  6982. // with the register storage-class specifier.
  6983. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  6984. // in C++ it is not error to take address of a register
  6985. // variable (c++03 7.1.1P3)
  6986. if (vd->getStorageClass() == SC_Register &&
  6987. !S.getLangOpts().CPlusPlus) {
  6988. AddressOfError = AO_Register_Variable;
  6989. }
  6990. } else if (isa<FunctionTemplateDecl>(dcl)) {
  6991. return S.Context.OverloadTy;
  6992. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  6993. // Okay: we can take the address of a field.
  6994. // Could be a pointer to member, though, if there is an explicit
  6995. // scope qualifier for the class.
  6996. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  6997. DeclContext *Ctx = dcl->getDeclContext();
  6998. if (Ctx && Ctx->isRecord()) {
  6999. if (dcl->getType()->isReferenceType()) {
  7000. S.Diag(OpLoc,
  7001. diag::err_cannot_form_pointer_to_member_of_reference_type)
  7002. << dcl->getDeclName() << dcl->getType();
  7003. return QualType();
  7004. }
  7005. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  7006. Ctx = Ctx->getParent();
  7007. return S.Context.getMemberPointerType(op->getType(),
  7008. S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  7009. }
  7010. }
  7011. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
  7012. llvm_unreachable("Unknown/unexpected decl type");
  7013. }
  7014. if (AddressOfError != AO_No_Error) {
  7015. diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
  7016. return QualType();
  7017. }
  7018. if (lval == Expr::LV_IncompleteVoidType) {
  7019. // Taking the address of a void variable is technically illegal, but we
  7020. // allow it in cases which are otherwise valid.
  7021. // Example: "extern void x; void* y = &x;".
  7022. S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  7023. }
  7024. // If the operand has type "type", the result has type "pointer to type".
  7025. if (op->getType()->isObjCObjectType())
  7026. return S.Context.getObjCObjectPointerType(op->getType());
  7027. return S.Context.getPointerType(op->getType());
  7028. }
  7029. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  7030. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  7031. SourceLocation OpLoc) {
  7032. if (Op->isTypeDependent())
  7033. return S.Context.DependentTy;
  7034. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  7035. if (ConvResult.isInvalid())
  7036. return QualType();
  7037. Op = ConvResult.take();
  7038. QualType OpTy = Op->getType();
  7039. QualType Result;
  7040. if (isa<CXXReinterpretCastExpr>(Op)) {
  7041. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  7042. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  7043. Op->getSourceRange());
  7044. }
  7045. // Note that per both C89 and C99, indirection is always legal, even if OpTy
  7046. // is an incomplete type or void. It would be possible to warn about
  7047. // dereferencing a void pointer, but it's completely well-defined, and such a
  7048. // warning is unlikely to catch any mistakes.
  7049. if (const PointerType *PT = OpTy->getAs<PointerType>())
  7050. Result = PT->getPointeeType();
  7051. else if (const ObjCObjectPointerType *OPT =
  7052. OpTy->getAs<ObjCObjectPointerType>())
  7053. Result = OPT->getPointeeType();
  7054. else {
  7055. ExprResult PR = S.CheckPlaceholderExpr(Op);
  7056. if (PR.isInvalid()) return QualType();
  7057. if (PR.take() != Op)
  7058. return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
  7059. }
  7060. if (Result.isNull()) {
  7061. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  7062. << OpTy << Op->getSourceRange();
  7063. return QualType();
  7064. }
  7065. // Dereferences are usually l-values...
  7066. VK = VK_LValue;
  7067. // ...except that certain expressions are never l-values in C.
  7068. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  7069. VK = VK_RValue;
  7070. return Result;
  7071. }
  7072. static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
  7073. tok::TokenKind Kind) {
  7074. BinaryOperatorKind Opc;
  7075. switch (Kind) {
  7076. default: llvm_unreachable("Unknown binop!");
  7077. case tok::periodstar: Opc = BO_PtrMemD; break;
  7078. case tok::arrowstar: Opc = BO_PtrMemI; break;
  7079. case tok::star: Opc = BO_Mul; break;
  7080. case tok::slash: Opc = BO_Div; break;
  7081. case tok::percent: Opc = BO_Rem; break;
  7082. case tok::plus: Opc = BO_Add; break;
  7083. case tok::minus: Opc = BO_Sub; break;
  7084. case tok::lessless: Opc = BO_Shl; break;
  7085. case tok::greatergreater: Opc = BO_Shr; break;
  7086. case tok::lessequal: Opc = BO_LE; break;
  7087. case tok::less: Opc = BO_LT; break;
  7088. case tok::greaterequal: Opc = BO_GE; break;
  7089. case tok::greater: Opc = BO_GT; break;
  7090. case tok::exclaimequal: Opc = BO_NE; break;
  7091. case tok::equalequal: Opc = BO_EQ; break;
  7092. case tok::amp: Opc = BO_And; break;
  7093. case tok::caret: Opc = BO_Xor; break;
  7094. case tok::pipe: Opc = BO_Or; break;
  7095. case tok::ampamp: Opc = BO_LAnd; break;
  7096. case tok::pipepipe: Opc = BO_LOr; break;
  7097. case tok::equal: Opc = BO_Assign; break;
  7098. case tok::starequal: Opc = BO_MulAssign; break;
  7099. case tok::slashequal: Opc = BO_DivAssign; break;
  7100. case tok::percentequal: Opc = BO_RemAssign; break;
  7101. case tok::plusequal: Opc = BO_AddAssign; break;
  7102. case tok::minusequal: Opc = BO_SubAssign; break;
  7103. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  7104. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  7105. case tok::ampequal: Opc = BO_AndAssign; break;
  7106. case tok::caretequal: Opc = BO_XorAssign; break;
  7107. case tok::pipeequal: Opc = BO_OrAssign; break;
  7108. case tok::comma: Opc = BO_Comma; break;
  7109. }
  7110. return Opc;
  7111. }
  7112. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  7113. tok::TokenKind Kind) {
  7114. UnaryOperatorKind Opc;
  7115. switch (Kind) {
  7116. default: llvm_unreachable("Unknown unary op!");
  7117. case tok::plusplus: Opc = UO_PreInc; break;
  7118. case tok::minusminus: Opc = UO_PreDec; break;
  7119. case tok::amp: Opc = UO_AddrOf; break;
  7120. case tok::star: Opc = UO_Deref; break;
  7121. case tok::plus: Opc = UO_Plus; break;
  7122. case tok::minus: Opc = UO_Minus; break;
  7123. case tok::tilde: Opc = UO_Not; break;
  7124. case tok::exclaim: Opc = UO_LNot; break;
  7125. case tok::kw___real: Opc = UO_Real; break;
  7126. case tok::kw___imag: Opc = UO_Imag; break;
  7127. case tok::kw___extension__: Opc = UO_Extension; break;
  7128. }
  7129. return Opc;
  7130. }
  7131. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  7132. /// This warning is only emitted for builtin assignment operations. It is also
  7133. /// suppressed in the event of macro expansions.
  7134. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  7135. SourceLocation OpLoc) {
  7136. if (!S.ActiveTemplateInstantiations.empty())
  7137. return;
  7138. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  7139. return;
  7140. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  7141. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  7142. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  7143. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  7144. if (!LHSDeclRef || !RHSDeclRef ||
  7145. LHSDeclRef->getLocation().isMacroID() ||
  7146. RHSDeclRef->getLocation().isMacroID())
  7147. return;
  7148. const ValueDecl *LHSDecl =
  7149. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  7150. const ValueDecl *RHSDecl =
  7151. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  7152. if (LHSDecl != RHSDecl)
  7153. return;
  7154. if (LHSDecl->getType().isVolatileQualified())
  7155. return;
  7156. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  7157. if (RefTy->getPointeeType().isVolatileQualified())
  7158. return;
  7159. S.Diag(OpLoc, diag::warn_self_assignment)
  7160. << LHSDeclRef->getType()
  7161. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  7162. }
  7163. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  7164. /// operator @p Opc at location @c TokLoc. This routine only supports
  7165. /// built-in operations; ActOnBinOp handles overloaded operators.
  7166. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  7167. BinaryOperatorKind Opc,
  7168. Expr *LHSExpr, Expr *RHSExpr) {
  7169. if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
  7170. // The syntax only allows initializer lists on the RHS of assignment,
  7171. // so we don't need to worry about accepting invalid code for
  7172. // non-assignment operators.
  7173. // C++11 5.17p9:
  7174. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  7175. // of x = {} is x = T().
  7176. InitializationKind Kind =
  7177. InitializationKind::CreateDirectList(RHSExpr->getLocStart());
  7178. InitializedEntity Entity =
  7179. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  7180. InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
  7181. ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
  7182. MultiExprArg(&RHSExpr, 1));
  7183. if (Init.isInvalid())
  7184. return Init;
  7185. RHSExpr = Init.take();
  7186. }
  7187. ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
  7188. QualType ResultTy; // Result type of the binary operator.
  7189. // The following two variables are used for compound assignment operators
  7190. QualType CompLHSTy; // Type of LHS after promotions for computation
  7191. QualType CompResultTy; // Type of computation result
  7192. ExprValueKind VK = VK_RValue;
  7193. ExprObjectKind OK = OK_Ordinary;
  7194. switch (Opc) {
  7195. case BO_Assign:
  7196. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  7197. if (getLangOpts().CPlusPlus &&
  7198. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  7199. VK = LHS.get()->getValueKind();
  7200. OK = LHS.get()->getObjectKind();
  7201. }
  7202. if (!ResultTy.isNull())
  7203. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  7204. break;
  7205. case BO_PtrMemD:
  7206. case BO_PtrMemI:
  7207. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  7208. Opc == BO_PtrMemI);
  7209. break;
  7210. case BO_Mul:
  7211. case BO_Div:
  7212. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  7213. Opc == BO_Div);
  7214. break;
  7215. case BO_Rem:
  7216. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  7217. break;
  7218. case BO_Add:
  7219. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  7220. break;
  7221. case BO_Sub:
  7222. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  7223. break;
  7224. case BO_Shl:
  7225. case BO_Shr:
  7226. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  7227. break;
  7228. case BO_LE:
  7229. case BO_LT:
  7230. case BO_GE:
  7231. case BO_GT:
  7232. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
  7233. break;
  7234. case BO_EQ:
  7235. case BO_NE:
  7236. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
  7237. break;
  7238. case BO_And:
  7239. case BO_Xor:
  7240. case BO_Or:
  7241. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
  7242. break;
  7243. case BO_LAnd:
  7244. case BO_LOr:
  7245. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  7246. break;
  7247. case BO_MulAssign:
  7248. case BO_DivAssign:
  7249. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  7250. Opc == BO_DivAssign);
  7251. CompLHSTy = CompResultTy;
  7252. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  7253. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  7254. break;
  7255. case BO_RemAssign:
  7256. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  7257. CompLHSTy = CompResultTy;
  7258. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  7259. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  7260. break;
  7261. case BO_AddAssign:
  7262. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  7263. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  7264. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  7265. break;
  7266. case BO_SubAssign:
  7267. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  7268. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  7269. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  7270. break;
  7271. case BO_ShlAssign:
  7272. case BO_ShrAssign:
  7273. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  7274. CompLHSTy = CompResultTy;
  7275. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  7276. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  7277. break;
  7278. case BO_AndAssign:
  7279. case BO_XorAssign:
  7280. case BO_OrAssign:
  7281. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
  7282. CompLHSTy = CompResultTy;
  7283. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  7284. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  7285. break;
  7286. case BO_Comma:
  7287. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  7288. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  7289. VK = RHS.get()->getValueKind();
  7290. OK = RHS.get()->getObjectKind();
  7291. }
  7292. break;
  7293. }
  7294. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  7295. return ExprError();
  7296. // Check for array bounds violations for both sides of the BinaryOperator
  7297. CheckArrayAccess(LHS.get());
  7298. CheckArrayAccess(RHS.get());
  7299. if (CompResultTy.isNull())
  7300. return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
  7301. ResultTy, VK, OK, OpLoc));
  7302. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  7303. OK_ObjCProperty) {
  7304. VK = VK_LValue;
  7305. OK = LHS.get()->getObjectKind();
  7306. }
  7307. return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
  7308. ResultTy, VK, OK, CompLHSTy,
  7309. CompResultTy, OpLoc));
  7310. }
  7311. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  7312. /// operators are mixed in a way that suggests that the programmer forgot that
  7313. /// comparison operators have higher precedence. The most typical example of
  7314. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  7315. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  7316. SourceLocation OpLoc, Expr *LHSExpr,
  7317. Expr *RHSExpr) {
  7318. typedef BinaryOperator BinOp;
  7319. BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
  7320. RHSopc = static_cast<BinOp::Opcode>(-1);
  7321. if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
  7322. LHSopc = BO->getOpcode();
  7323. if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
  7324. RHSopc = BO->getOpcode();
  7325. // Subs are not binary operators.
  7326. if (LHSopc == -1 && RHSopc == -1)
  7327. return;
  7328. // Bitwise operations are sometimes used as eager logical ops.
  7329. // Don't diagnose this.
  7330. if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
  7331. (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
  7332. return;
  7333. bool isLeftComp = BinOp::isComparisonOp(LHSopc);
  7334. bool isRightComp = BinOp::isComparisonOp(RHSopc);
  7335. if (!isLeftComp && !isRightComp) return;
  7336. SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
  7337. OpLoc)
  7338. : SourceRange(OpLoc, RHSExpr->getLocEnd());
  7339. std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
  7340. : BinOp::getOpcodeStr(RHSopc);
  7341. SourceRange ParensRange = isLeftComp ?
  7342. SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
  7343. RHSExpr->getLocEnd())
  7344. : SourceRange(LHSExpr->getLocStart(),
  7345. cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
  7346. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  7347. << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
  7348. SuggestParentheses(Self, OpLoc,
  7349. Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
  7350. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  7351. SuggestParentheses(Self, OpLoc,
  7352. Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
  7353. ParensRange);
  7354. }
  7355. /// \brief It accepts a '&' expr that is inside a '|' one.
  7356. /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
  7357. /// in parentheses.
  7358. static void
  7359. EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
  7360. BinaryOperator *Bop) {
  7361. assert(Bop->getOpcode() == BO_And);
  7362. Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
  7363. << Bop->getSourceRange() << OpLoc;
  7364. SuggestParentheses(Self, Bop->getOperatorLoc(),
  7365. Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
  7366. Bop->getSourceRange());
  7367. }
  7368. /// \brief It accepts a '&&' expr that is inside a '||' one.
  7369. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  7370. /// in parentheses.
  7371. static void
  7372. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  7373. BinaryOperator *Bop) {
  7374. assert(Bop->getOpcode() == BO_LAnd);
  7375. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  7376. << Bop->getSourceRange() << OpLoc;
  7377. SuggestParentheses(Self, Bop->getOperatorLoc(),
  7378. Self.PDiag(diag::note_logical_and_in_logical_or_silence),
  7379. Bop->getSourceRange());
  7380. }
  7381. /// \brief Returns true if the given expression can be evaluated as a constant
  7382. /// 'true'.
  7383. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  7384. bool Res;
  7385. return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  7386. }
  7387. /// \brief Returns true if the given expression can be evaluated as a constant
  7388. /// 'false'.
  7389. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  7390. bool Res;
  7391. return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  7392. }
  7393. /// \brief Look for '&&' in the left hand of a '||' expr.
  7394. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  7395. Expr *LHSExpr, Expr *RHSExpr) {
  7396. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  7397. if (Bop->getOpcode() == BO_LAnd) {
  7398. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  7399. if (EvaluatesAsFalse(S, RHSExpr))
  7400. return;
  7401. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  7402. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  7403. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  7404. } else if (Bop->getOpcode() == BO_LOr) {
  7405. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  7406. // If it's "a || b && 1 || c" we didn't warn earlier for
  7407. // "a || b && 1", but warn now.
  7408. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  7409. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  7410. }
  7411. }
  7412. }
  7413. }
  7414. /// \brief Look for '&&' in the right hand of a '||' expr.
  7415. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  7416. Expr *LHSExpr, Expr *RHSExpr) {
  7417. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  7418. if (Bop->getOpcode() == BO_LAnd) {
  7419. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  7420. if (EvaluatesAsFalse(S, LHSExpr))
  7421. return;
  7422. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  7423. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  7424. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  7425. }
  7426. }
  7427. }
  7428. /// \brief Look for '&' in the left or right hand of a '|' expr.
  7429. static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
  7430. Expr *OrArg) {
  7431. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
  7432. if (Bop->getOpcode() == BO_And)
  7433. return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
  7434. }
  7435. }
  7436. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  7437. /// precedence.
  7438. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  7439. SourceLocation OpLoc, Expr *LHSExpr,
  7440. Expr *RHSExpr){
  7441. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  7442. if (BinaryOperator::isBitwiseOp(Opc))
  7443. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  7444. // Diagnose "arg1 & arg2 | arg3"
  7445. if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  7446. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
  7447. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
  7448. }
  7449. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  7450. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  7451. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  7452. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  7453. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  7454. }
  7455. }
  7456. // Binary Operators. 'Tok' is the token for the operator.
  7457. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  7458. tok::TokenKind Kind,
  7459. Expr *LHSExpr, Expr *RHSExpr) {
  7460. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  7461. assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
  7462. assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
  7463. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  7464. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  7465. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  7466. }
  7467. /// Build an overloaded binary operator expression in the given scope.
  7468. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  7469. BinaryOperatorKind Opc,
  7470. Expr *LHS, Expr *RHS) {
  7471. // Find all of the overloaded operators visible from this
  7472. // point. We perform both an operator-name lookup from the local
  7473. // scope and an argument-dependent lookup based on the types of
  7474. // the arguments.
  7475. UnresolvedSet<16> Functions;
  7476. OverloadedOperatorKind OverOp
  7477. = BinaryOperator::getOverloadedOperator(Opc);
  7478. if (Sc && OverOp != OO_None)
  7479. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  7480. RHS->getType(), Functions);
  7481. // Build the (potentially-overloaded, potentially-dependent)
  7482. // binary operation.
  7483. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  7484. }
  7485. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  7486. BinaryOperatorKind Opc,
  7487. Expr *LHSExpr, Expr *RHSExpr) {
  7488. // We want to end up calling one of checkPseudoObjectAssignment
  7489. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  7490. // both expressions are overloadable or either is type-dependent),
  7491. // or CreateBuiltinBinOp (in any other case). We also want to get
  7492. // any placeholder types out of the way.
  7493. // Handle pseudo-objects in the LHS.
  7494. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  7495. // Assignments with a pseudo-object l-value need special analysis.
  7496. if (pty->getKind() == BuiltinType::PseudoObject &&
  7497. BinaryOperator::isAssignmentOp(Opc))
  7498. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  7499. // Don't resolve overloads if the other type is overloadable.
  7500. if (pty->getKind() == BuiltinType::Overload) {
  7501. // We can't actually test that if we still have a placeholder,
  7502. // though. Fortunately, none of the exceptions we see in that
  7503. // code below are valid when the LHS is an overload set. Note
  7504. // that an overload set can be dependently-typed, but it never
  7505. // instantiates to having an overloadable type.
  7506. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  7507. if (resolvedRHS.isInvalid()) return ExprError();
  7508. RHSExpr = resolvedRHS.take();
  7509. if (RHSExpr->isTypeDependent() ||
  7510. RHSExpr->getType()->isOverloadableType())
  7511. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  7512. }
  7513. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  7514. if (LHS.isInvalid()) return ExprError();
  7515. LHSExpr = LHS.take();
  7516. }
  7517. // Handle pseudo-objects in the RHS.
  7518. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  7519. // An overload in the RHS can potentially be resolved by the type
  7520. // being assigned to.
  7521. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  7522. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  7523. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  7524. if (LHSExpr->getType()->isOverloadableType())
  7525. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  7526. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  7527. }
  7528. // Don't resolve overloads if the other type is overloadable.
  7529. if (pty->getKind() == BuiltinType::Overload &&
  7530. LHSExpr->getType()->isOverloadableType())
  7531. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  7532. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  7533. if (!resolvedRHS.isUsable()) return ExprError();
  7534. RHSExpr = resolvedRHS.take();
  7535. }
  7536. if (getLangOpts().CPlusPlus) {
  7537. // If either expression is type-dependent, always build an
  7538. // overloaded op.
  7539. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  7540. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  7541. // Otherwise, build an overloaded op if either expression has an
  7542. // overloadable type.
  7543. if (LHSExpr->getType()->isOverloadableType() ||
  7544. RHSExpr->getType()->isOverloadableType())
  7545. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  7546. }
  7547. // Build a built-in binary operation.
  7548. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  7549. }
  7550. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  7551. UnaryOperatorKind Opc,
  7552. Expr *InputExpr) {
  7553. ExprResult Input = Owned(InputExpr);
  7554. ExprValueKind VK = VK_RValue;
  7555. ExprObjectKind OK = OK_Ordinary;
  7556. QualType resultType;
  7557. switch (Opc) {
  7558. case UO_PreInc:
  7559. case UO_PreDec:
  7560. case UO_PostInc:
  7561. case UO_PostDec:
  7562. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
  7563. Opc == UO_PreInc ||
  7564. Opc == UO_PostInc,
  7565. Opc == UO_PreInc ||
  7566. Opc == UO_PreDec);
  7567. break;
  7568. case UO_AddrOf:
  7569. resultType = CheckAddressOfOperand(*this, Input, OpLoc);
  7570. break;
  7571. case UO_Deref: {
  7572. Input = DefaultFunctionArrayLvalueConversion(Input.take());
  7573. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  7574. break;
  7575. }
  7576. case UO_Plus:
  7577. case UO_Minus:
  7578. Input = UsualUnaryConversions(Input.take());
  7579. if (Input.isInvalid()) return ExprError();
  7580. resultType = Input.get()->getType();
  7581. if (resultType->isDependentType())
  7582. break;
  7583. if (resultType->isArithmeticType() || // C99 6.5.3.3p1
  7584. resultType->isVectorType())
  7585. break;
  7586. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
  7587. resultType->isEnumeralType())
  7588. break;
  7589. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  7590. Opc == UO_Plus &&
  7591. resultType->isPointerType())
  7592. break;
  7593. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  7594. << resultType << Input.get()->getSourceRange());
  7595. case UO_Not: // bitwise complement
  7596. Input = UsualUnaryConversions(Input.take());
  7597. if (Input.isInvalid()) return ExprError();
  7598. resultType = Input.get()->getType();
  7599. if (resultType->isDependentType())
  7600. break;
  7601. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  7602. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  7603. // C99 does not support '~' for complex conjugation.
  7604. Diag(OpLoc, diag::ext_integer_complement_complex)
  7605. << resultType << Input.get()->getSourceRange();
  7606. else if (resultType->hasIntegerRepresentation())
  7607. break;
  7608. else {
  7609. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  7610. << resultType << Input.get()->getSourceRange());
  7611. }
  7612. break;
  7613. case UO_LNot: // logical negation
  7614. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  7615. Input = DefaultFunctionArrayLvalueConversion(Input.take());
  7616. if (Input.isInvalid()) return ExprError();
  7617. resultType = Input.get()->getType();
  7618. // Though we still have to promote half FP to float...
  7619. if (resultType->isHalfType()) {
  7620. Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
  7621. resultType = Context.FloatTy;
  7622. }
  7623. if (resultType->isDependentType())
  7624. break;
  7625. if (resultType->isScalarType()) {
  7626. // C99 6.5.3.3p1: ok, fallthrough;
  7627. if (Context.getLangOpts().CPlusPlus) {
  7628. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  7629. // operand contextually converted to bool.
  7630. Input = ImpCastExprToType(Input.take(), Context.BoolTy,
  7631. ScalarTypeToBooleanCastKind(resultType));
  7632. }
  7633. } else if (resultType->isExtVectorType()) {
  7634. // Vector logical not returns the signed variant of the operand type.
  7635. resultType = GetSignedVectorType(resultType);
  7636. break;
  7637. } else {
  7638. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  7639. << resultType << Input.get()->getSourceRange());
  7640. }
  7641. // LNot always has type int. C99 6.5.3.3p5.
  7642. // In C++, it's bool. C++ 5.3.1p8
  7643. resultType = Context.getLogicalOperationType();
  7644. break;
  7645. case UO_Real:
  7646. case UO_Imag:
  7647. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  7648. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  7649. // complex l-values to ordinary l-values and all other values to r-values.
  7650. if (Input.isInvalid()) return ExprError();
  7651. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  7652. if (Input.get()->getValueKind() != VK_RValue &&
  7653. Input.get()->getObjectKind() == OK_Ordinary)
  7654. VK = Input.get()->getValueKind();
  7655. } else if (!getLangOpts().CPlusPlus) {
  7656. // In C, a volatile scalar is read by __imag. In C++, it is not.
  7657. Input = DefaultLvalueConversion(Input.take());
  7658. }
  7659. break;
  7660. case UO_Extension:
  7661. resultType = Input.get()->getType();
  7662. VK = Input.get()->getValueKind();
  7663. OK = Input.get()->getObjectKind();
  7664. break;
  7665. }
  7666. if (resultType.isNull() || Input.isInvalid())
  7667. return ExprError();
  7668. // Check for array bounds violations in the operand of the UnaryOperator,
  7669. // except for the '*' and '&' operators that have to be handled specially
  7670. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  7671. // that are explicitly defined as valid by the standard).
  7672. if (Opc != UO_AddrOf && Opc != UO_Deref)
  7673. CheckArrayAccess(Input.get());
  7674. return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
  7675. VK, OK, OpLoc));
  7676. }
  7677. /// \brief Determine whether the given expression is a qualified member
  7678. /// access expression, of a form that could be turned into a pointer to member
  7679. /// with the address-of operator.
  7680. static bool isQualifiedMemberAccess(Expr *E) {
  7681. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  7682. if (!DRE->getQualifier())
  7683. return false;
  7684. ValueDecl *VD = DRE->getDecl();
  7685. if (!VD->isCXXClassMember())
  7686. return false;
  7687. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  7688. return true;
  7689. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  7690. return Method->isInstance();
  7691. return false;
  7692. }
  7693. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  7694. if (!ULE->getQualifier())
  7695. return false;
  7696. for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
  7697. DEnd = ULE->decls_end();
  7698. D != DEnd; ++D) {
  7699. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
  7700. if (Method->isInstance())
  7701. return true;
  7702. } else {
  7703. // Overload set does not contain methods.
  7704. break;
  7705. }
  7706. }
  7707. return false;
  7708. }
  7709. return false;
  7710. }
  7711. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  7712. UnaryOperatorKind Opc, Expr *Input) {
  7713. // First things first: handle placeholders so that the
  7714. // overloaded-operator check considers the right type.
  7715. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  7716. // Increment and decrement of pseudo-object references.
  7717. if (pty->getKind() == BuiltinType::PseudoObject &&
  7718. UnaryOperator::isIncrementDecrementOp(Opc))
  7719. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  7720. // extension is always a builtin operator.
  7721. if (Opc == UO_Extension)
  7722. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  7723. // & gets special logic for several kinds of placeholder.
  7724. // The builtin code knows what to do.
  7725. if (Opc == UO_AddrOf &&
  7726. (pty->getKind() == BuiltinType::Overload ||
  7727. pty->getKind() == BuiltinType::UnknownAny ||
  7728. pty->getKind() == BuiltinType::BoundMember))
  7729. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  7730. // Anything else needs to be handled now.
  7731. ExprResult Result = CheckPlaceholderExpr(Input);
  7732. if (Result.isInvalid()) return ExprError();
  7733. Input = Result.take();
  7734. }
  7735. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  7736. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  7737. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  7738. // Find all of the overloaded operators visible from this
  7739. // point. We perform both an operator-name lookup from the local
  7740. // scope and an argument-dependent lookup based on the types of
  7741. // the arguments.
  7742. UnresolvedSet<16> Functions;
  7743. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  7744. if (S && OverOp != OO_None)
  7745. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  7746. Functions);
  7747. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  7748. }
  7749. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  7750. }
  7751. // Unary Operators. 'Tok' is the token for the operator.
  7752. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  7753. tok::TokenKind Op, Expr *Input) {
  7754. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  7755. }
  7756. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  7757. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  7758. LabelDecl *TheDecl) {
  7759. TheDecl->setUsed();
  7760. // Create the AST node. The address of a label always has type 'void*'.
  7761. return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  7762. Context.getPointerType(Context.VoidTy)));
  7763. }
  7764. /// Given the last statement in a statement-expression, check whether
  7765. /// the result is a producing expression (like a call to an
  7766. /// ns_returns_retained function) and, if so, rebuild it to hoist the
  7767. /// release out of the full-expression. Otherwise, return null.
  7768. /// Cannot fail.
  7769. static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
  7770. // Should always be wrapped with one of these.
  7771. ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
  7772. if (!cleanups) return 0;
  7773. ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
  7774. if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
  7775. return 0;
  7776. // Splice out the cast. This shouldn't modify any interesting
  7777. // features of the statement.
  7778. Expr *producer = cast->getSubExpr();
  7779. assert(producer->getType() == cast->getType());
  7780. assert(producer->getValueKind() == cast->getValueKind());
  7781. cleanups->setSubExpr(producer);
  7782. return cleanups;
  7783. }
  7784. void Sema::ActOnStartStmtExpr() {
  7785. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  7786. }
  7787. void Sema::ActOnStmtExprError() {
  7788. // Note that function is also called by TreeTransform when leaving a
  7789. // StmtExpr scope without rebuilding anything.
  7790. DiscardCleanupsInEvaluationContext();
  7791. PopExpressionEvaluationContext();
  7792. }
  7793. ExprResult
  7794. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  7795. SourceLocation RPLoc) { // "({..})"
  7796. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  7797. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  7798. if (hasAnyUnrecoverableErrorsInThisFunction())
  7799. DiscardCleanupsInEvaluationContext();
  7800. assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
  7801. PopExpressionEvaluationContext();
  7802. bool isFileScope
  7803. = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
  7804. if (isFileScope)
  7805. return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
  7806. // FIXME: there are a variety of strange constraints to enforce here, for
  7807. // example, it is not possible to goto into a stmt expression apparently.
  7808. // More semantic analysis is needed.
  7809. // If there are sub stmts in the compound stmt, take the type of the last one
  7810. // as the type of the stmtexpr.
  7811. QualType Ty = Context.VoidTy;
  7812. bool StmtExprMayBindToTemp = false;
  7813. if (!Compound->body_empty()) {
  7814. Stmt *LastStmt = Compound->body_back();
  7815. LabelStmt *LastLabelStmt = 0;
  7816. // If LastStmt is a label, skip down through into the body.
  7817. while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
  7818. LastLabelStmt = Label;
  7819. LastStmt = Label->getSubStmt();
  7820. }
  7821. if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
  7822. // Do function/array conversion on the last expression, but not
  7823. // lvalue-to-rvalue. However, initialize an unqualified type.
  7824. ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
  7825. if (LastExpr.isInvalid())
  7826. return ExprError();
  7827. Ty = LastExpr.get()->getType().getUnqualifiedType();
  7828. if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
  7829. // In ARC, if the final expression ends in a consume, splice
  7830. // the consume out and bind it later. In the alternate case
  7831. // (when dealing with a retainable type), the result
  7832. // initialization will create a produce. In both cases the
  7833. // result will be +1, and we'll need to balance that out with
  7834. // a bind.
  7835. if (Expr *rebuiltLastStmt
  7836. = maybeRebuildARCConsumingStmt(LastExpr.get())) {
  7837. LastExpr = rebuiltLastStmt;
  7838. } else {
  7839. LastExpr = PerformCopyInitialization(
  7840. InitializedEntity::InitializeResult(LPLoc,
  7841. Ty,
  7842. false),
  7843. SourceLocation(),
  7844. LastExpr);
  7845. }
  7846. if (LastExpr.isInvalid())
  7847. return ExprError();
  7848. if (LastExpr.get() != 0) {
  7849. if (!LastLabelStmt)
  7850. Compound->setLastStmt(LastExpr.take());
  7851. else
  7852. LastLabelStmt->setSubStmt(LastExpr.take());
  7853. StmtExprMayBindToTemp = true;
  7854. }
  7855. }
  7856. }
  7857. }
  7858. // FIXME: Check that expression type is complete/non-abstract; statement
  7859. // expressions are not lvalues.
  7860. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  7861. if (StmtExprMayBindToTemp)
  7862. return MaybeBindToTemporary(ResStmtExpr);
  7863. return Owned(ResStmtExpr);
  7864. }
  7865. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  7866. TypeSourceInfo *TInfo,
  7867. OffsetOfComponent *CompPtr,
  7868. unsigned NumComponents,
  7869. SourceLocation RParenLoc) {
  7870. QualType ArgTy = TInfo->getType();
  7871. bool Dependent = ArgTy->isDependentType();
  7872. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  7873. // We must have at least one component that refers to the type, and the first
  7874. // one is known to be a field designator. Verify that the ArgTy represents
  7875. // a struct/union/class.
  7876. if (!Dependent && !ArgTy->isRecordType())
  7877. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  7878. << ArgTy << TypeRange);
  7879. // Type must be complete per C99 7.17p3 because a declaring a variable
  7880. // with an incomplete type would be ill-formed.
  7881. if (!Dependent
  7882. && RequireCompleteType(BuiltinLoc, ArgTy,
  7883. diag::err_offsetof_incomplete_type, TypeRange))
  7884. return ExprError();
  7885. // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
  7886. // GCC extension, diagnose them.
  7887. // FIXME: This diagnostic isn't actually visible because the location is in
  7888. // a system header!
  7889. if (NumComponents != 1)
  7890. Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
  7891. << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
  7892. bool DidWarnAboutNonPOD = false;
  7893. QualType CurrentType = ArgTy;
  7894. typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
  7895. SmallVector<OffsetOfNode, 4> Comps;
  7896. SmallVector<Expr*, 4> Exprs;
  7897. for (unsigned i = 0; i != NumComponents; ++i) {
  7898. const OffsetOfComponent &OC = CompPtr[i];
  7899. if (OC.isBrackets) {
  7900. // Offset of an array sub-field. TODO: Should we allow vector elements?
  7901. if (!CurrentType->isDependentType()) {
  7902. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  7903. if(!AT)
  7904. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  7905. << CurrentType);
  7906. CurrentType = AT->getElementType();
  7907. } else
  7908. CurrentType = Context.DependentTy;
  7909. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  7910. if (IdxRval.isInvalid())
  7911. return ExprError();
  7912. Expr *Idx = IdxRval.take();
  7913. // The expression must be an integral expression.
  7914. // FIXME: An integral constant expression?
  7915. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  7916. !Idx->getType()->isIntegerType())
  7917. return ExprError(Diag(Idx->getLocStart(),
  7918. diag::err_typecheck_subscript_not_integer)
  7919. << Idx->getSourceRange());
  7920. // Record this array index.
  7921. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  7922. Exprs.push_back(Idx);
  7923. continue;
  7924. }
  7925. // Offset of a field.
  7926. if (CurrentType->isDependentType()) {
  7927. // We have the offset of a field, but we can't look into the dependent
  7928. // type. Just record the identifier of the field.
  7929. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  7930. CurrentType = Context.DependentTy;
  7931. continue;
  7932. }
  7933. // We need to have a complete type to look into.
  7934. if (RequireCompleteType(OC.LocStart, CurrentType,
  7935. diag::err_offsetof_incomplete_type))
  7936. return ExprError();
  7937. // Look for the designated field.
  7938. const RecordType *RC = CurrentType->getAs<RecordType>();
  7939. if (!RC)
  7940. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  7941. << CurrentType);
  7942. RecordDecl *RD = RC->getDecl();
  7943. // C++ [lib.support.types]p5:
  7944. // The macro offsetof accepts a restricted set of type arguments in this
  7945. // International Standard. type shall be a POD structure or a POD union
  7946. // (clause 9).
  7947. // C++11 [support.types]p4:
  7948. // If type is not a standard-layout class (Clause 9), the results are
  7949. // undefined.
  7950. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  7951. bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
  7952. unsigned DiagID =
  7953. LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
  7954. : diag::warn_offsetof_non_pod_type;
  7955. if (!IsSafe && !DidWarnAboutNonPOD &&
  7956. DiagRuntimeBehavior(BuiltinLoc, 0,
  7957. PDiag(DiagID)
  7958. << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
  7959. << CurrentType))
  7960. DidWarnAboutNonPOD = true;
  7961. }
  7962. // Look for the field.
  7963. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  7964. LookupQualifiedName(R, RD);
  7965. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  7966. IndirectFieldDecl *IndirectMemberDecl = 0;
  7967. if (!MemberDecl) {
  7968. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  7969. MemberDecl = IndirectMemberDecl->getAnonField();
  7970. }
  7971. if (!MemberDecl)
  7972. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  7973. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  7974. OC.LocEnd));
  7975. // C99 7.17p3:
  7976. // (If the specified member is a bit-field, the behavior is undefined.)
  7977. //
  7978. // We diagnose this as an error.
  7979. if (MemberDecl->isBitField()) {
  7980. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  7981. << MemberDecl->getDeclName()
  7982. << SourceRange(BuiltinLoc, RParenLoc);
  7983. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  7984. return ExprError();
  7985. }
  7986. RecordDecl *Parent = MemberDecl->getParent();
  7987. if (IndirectMemberDecl)
  7988. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  7989. // If the member was found in a base class, introduce OffsetOfNodes for
  7990. // the base class indirections.
  7991. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  7992. /*DetectVirtual=*/false);
  7993. if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
  7994. CXXBasePath &Path = Paths.front();
  7995. for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
  7996. B != BEnd; ++B)
  7997. Comps.push_back(OffsetOfNode(B->Base));
  7998. }
  7999. if (IndirectMemberDecl) {
  8000. for (IndirectFieldDecl::chain_iterator FI =
  8001. IndirectMemberDecl->chain_begin(),
  8002. FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
  8003. assert(isa<FieldDecl>(*FI));
  8004. Comps.push_back(OffsetOfNode(OC.LocStart,
  8005. cast<FieldDecl>(*FI), OC.LocEnd));
  8006. }
  8007. } else
  8008. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  8009. CurrentType = MemberDecl->getType().getNonReferenceType();
  8010. }
  8011. return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
  8012. TInfo, Comps.data(), Comps.size(),
  8013. Exprs.data(), Exprs.size(), RParenLoc));
  8014. }
  8015. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  8016. SourceLocation BuiltinLoc,
  8017. SourceLocation TypeLoc,
  8018. ParsedType ParsedArgTy,
  8019. OffsetOfComponent *CompPtr,
  8020. unsigned NumComponents,
  8021. SourceLocation RParenLoc) {
  8022. TypeSourceInfo *ArgTInfo;
  8023. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  8024. if (ArgTy.isNull())
  8025. return ExprError();
  8026. if (!ArgTInfo)
  8027. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  8028. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
  8029. RParenLoc);
  8030. }
  8031. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  8032. Expr *CondExpr,
  8033. Expr *LHSExpr, Expr *RHSExpr,
  8034. SourceLocation RPLoc) {
  8035. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  8036. ExprValueKind VK = VK_RValue;
  8037. ExprObjectKind OK = OK_Ordinary;
  8038. QualType resType;
  8039. bool ValueDependent = false;
  8040. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  8041. resType = Context.DependentTy;
  8042. ValueDependent = true;
  8043. } else {
  8044. // The conditional expression is required to be a constant expression.
  8045. llvm::APSInt condEval(32);
  8046. ExprResult CondICE
  8047. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  8048. diag::err_typecheck_choose_expr_requires_constant, false);
  8049. if (CondICE.isInvalid())
  8050. return ExprError();
  8051. CondExpr = CondICE.take();
  8052. // If the condition is > zero, then the AST type is the same as the LSHExpr.
  8053. Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
  8054. resType = ActiveExpr->getType();
  8055. ValueDependent = ActiveExpr->isValueDependent();
  8056. VK = ActiveExpr->getValueKind();
  8057. OK = ActiveExpr->getObjectKind();
  8058. }
  8059. return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
  8060. resType, VK, OK, RPLoc,
  8061. resType->isDependentType(),
  8062. ValueDependent));
  8063. }
  8064. //===----------------------------------------------------------------------===//
  8065. // Clang Extensions.
  8066. //===----------------------------------------------------------------------===//
  8067. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  8068. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  8069. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  8070. PushBlockScope(CurScope, Block);
  8071. CurContext->addDecl(Block);
  8072. if (CurScope)
  8073. PushDeclContext(CurScope, Block);
  8074. else
  8075. CurContext = Block;
  8076. getCurBlock()->HasImplicitReturnType = true;
  8077. // Enter a new evaluation context to insulate the block from any
  8078. // cleanups from the enclosing full-expression.
  8079. PushExpressionEvaluationContext(PotentiallyEvaluated);
  8080. }
  8081. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  8082. Scope *CurScope) {
  8083. assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
  8084. assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
  8085. BlockScopeInfo *CurBlock = getCurBlock();
  8086. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  8087. QualType T = Sig->getType();
  8088. // FIXME: We should allow unexpanded parameter packs here, but that would,
  8089. // in turn, make the block expression contain unexpanded parameter packs.
  8090. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  8091. // Drop the parameters.
  8092. FunctionProtoType::ExtProtoInfo EPI;
  8093. EPI.HasTrailingReturn = false;
  8094. EPI.TypeQuals |= DeclSpec::TQ_const;
  8095. T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
  8096. EPI);
  8097. Sig = Context.getTrivialTypeSourceInfo(T);
  8098. }
  8099. // GetTypeForDeclarator always produces a function type for a block
  8100. // literal signature. Furthermore, it is always a FunctionProtoType
  8101. // unless the function was written with a typedef.
  8102. assert(T->isFunctionType() &&
  8103. "GetTypeForDeclarator made a non-function block signature");
  8104. // Look for an explicit signature in that function type.
  8105. FunctionProtoTypeLoc ExplicitSignature;
  8106. TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
  8107. if (isa<FunctionProtoTypeLoc>(tmp)) {
  8108. ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
  8109. // Check whether that explicit signature was synthesized by
  8110. // GetTypeForDeclarator. If so, don't save that as part of the
  8111. // written signature.
  8112. if (ExplicitSignature.getLocalRangeBegin() ==
  8113. ExplicitSignature.getLocalRangeEnd()) {
  8114. // This would be much cheaper if we stored TypeLocs instead of
  8115. // TypeSourceInfos.
  8116. TypeLoc Result = ExplicitSignature.getResultLoc();
  8117. unsigned Size = Result.getFullDataSize();
  8118. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  8119. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  8120. ExplicitSignature = FunctionProtoTypeLoc();
  8121. }
  8122. }
  8123. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  8124. CurBlock->FunctionType = T;
  8125. const FunctionType *Fn = T->getAs<FunctionType>();
  8126. QualType RetTy = Fn->getResultType();
  8127. bool isVariadic =
  8128. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  8129. CurBlock->TheDecl->setIsVariadic(isVariadic);
  8130. // Don't allow returning a objc interface by value.
  8131. if (RetTy->isObjCObjectType()) {
  8132. Diag(ParamInfo.getLocStart(),
  8133. diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
  8134. return;
  8135. }
  8136. // Context.DependentTy is used as a placeholder for a missing block
  8137. // return type. TODO: what should we do with declarators like:
  8138. // ^ * { ... }
  8139. // If the answer is "apply template argument deduction"....
  8140. if (RetTy != Context.DependentTy) {
  8141. CurBlock->ReturnType = RetTy;
  8142. CurBlock->TheDecl->setBlockMissingReturnType(false);
  8143. CurBlock->HasImplicitReturnType = false;
  8144. }
  8145. // Push block parameters from the declarator if we had them.
  8146. SmallVector<ParmVarDecl*, 8> Params;
  8147. if (ExplicitSignature) {
  8148. for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
  8149. ParmVarDecl *Param = ExplicitSignature.getArg(I);
  8150. if (Param->getIdentifier() == 0 &&
  8151. !Param->isImplicit() &&
  8152. !Param->isInvalidDecl() &&
  8153. !getLangOpts().CPlusPlus)
  8154. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  8155. Params.push_back(Param);
  8156. }
  8157. // Fake up parameter variables if we have a typedef, like
  8158. // ^ fntype { ... }
  8159. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  8160. for (FunctionProtoType::arg_type_iterator
  8161. I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
  8162. ParmVarDecl *Param =
  8163. BuildParmVarDeclForTypedef(CurBlock->TheDecl,
  8164. ParamInfo.getLocStart(),
  8165. *I);
  8166. Params.push_back(Param);
  8167. }
  8168. }
  8169. // Set the parameters on the block decl.
  8170. if (!Params.empty()) {
  8171. CurBlock->TheDecl->setParams(Params);
  8172. CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
  8173. CurBlock->TheDecl->param_end(),
  8174. /*CheckParameterNames=*/false);
  8175. }
  8176. // Finally we can process decl attributes.
  8177. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  8178. // Put the parameter variables in scope. We can bail out immediately
  8179. // if we don't have any.
  8180. if (Params.empty())
  8181. return;
  8182. for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
  8183. E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
  8184. (*AI)->setOwningFunction(CurBlock->TheDecl);
  8185. // If this has an identifier, add it to the scope stack.
  8186. if ((*AI)->getIdentifier()) {
  8187. CheckShadow(CurBlock->TheScope, *AI);
  8188. PushOnScopeChains(*AI, CurBlock->TheScope);
  8189. }
  8190. }
  8191. }
  8192. /// ActOnBlockError - If there is an error parsing a block, this callback
  8193. /// is invoked to pop the information about the block from the action impl.
  8194. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  8195. // Leave the expression-evaluation context.
  8196. DiscardCleanupsInEvaluationContext();
  8197. PopExpressionEvaluationContext();
  8198. // Pop off CurBlock, handle nested blocks.
  8199. PopDeclContext();
  8200. PopFunctionScopeInfo();
  8201. }
  8202. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  8203. /// literal was successfully completed. ^(int x){...}
  8204. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  8205. Stmt *Body, Scope *CurScope) {
  8206. // If blocks are disabled, emit an error.
  8207. if (!LangOpts.Blocks)
  8208. Diag(CaretLoc, diag::err_blocks_disable);
  8209. // Leave the expression-evaluation context.
  8210. if (hasAnyUnrecoverableErrorsInThisFunction())
  8211. DiscardCleanupsInEvaluationContext();
  8212. assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
  8213. PopExpressionEvaluationContext();
  8214. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  8215. if (BSI->HasImplicitReturnType)
  8216. deduceClosureReturnType(*BSI);
  8217. PopDeclContext();
  8218. QualType RetTy = Context.VoidTy;
  8219. if (!BSI->ReturnType.isNull())
  8220. RetTy = BSI->ReturnType;
  8221. bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
  8222. QualType BlockTy;
  8223. // Set the captured variables on the block.
  8224. // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
  8225. SmallVector<BlockDecl::Capture, 4> Captures;
  8226. for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
  8227. CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
  8228. if (Cap.isThisCapture())
  8229. continue;
  8230. BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
  8231. Cap.isNested(), Cap.getCopyExpr());
  8232. Captures.push_back(NewCap);
  8233. }
  8234. BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
  8235. BSI->CXXThisCaptureIndex != 0);
  8236. // If the user wrote a function type in some form, try to use that.
  8237. if (!BSI->FunctionType.isNull()) {
  8238. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  8239. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  8240. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  8241. // Turn protoless block types into nullary block types.
  8242. if (isa<FunctionNoProtoType>(FTy)) {
  8243. FunctionProtoType::ExtProtoInfo EPI;
  8244. EPI.ExtInfo = Ext;
  8245. BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
  8246. // Otherwise, if we don't need to change anything about the function type,
  8247. // preserve its sugar structure.
  8248. } else if (FTy->getResultType() == RetTy &&
  8249. (!NoReturn || FTy->getNoReturnAttr())) {
  8250. BlockTy = BSI->FunctionType;
  8251. // Otherwise, make the minimal modifications to the function type.
  8252. } else {
  8253. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  8254. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8255. EPI.TypeQuals = 0; // FIXME: silently?
  8256. EPI.ExtInfo = Ext;
  8257. BlockTy = Context.getFunctionType(RetTy,
  8258. FPT->arg_type_begin(),
  8259. FPT->getNumArgs(),
  8260. EPI);
  8261. }
  8262. // If we don't have a function type, just build one from nothing.
  8263. } else {
  8264. FunctionProtoType::ExtProtoInfo EPI;
  8265. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  8266. BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
  8267. }
  8268. DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
  8269. BSI->TheDecl->param_end());
  8270. BlockTy = Context.getBlockPointerType(BlockTy);
  8271. // If needed, diagnose invalid gotos and switches in the block.
  8272. if (getCurFunction()->NeedsScopeChecking() &&
  8273. !hasAnyUnrecoverableErrorsInThisFunction() &&
  8274. !PP.isCodeCompletionEnabled())
  8275. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  8276. BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
  8277. // Try to apply the named return value optimization. We have to check again
  8278. // if we can do this, though, because blocks keep return statements around
  8279. // to deduce an implicit return type.
  8280. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  8281. !BSI->TheDecl->isDependentContext())
  8282. computeNRVO(Body, getCurBlock());
  8283. BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
  8284. const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
  8285. PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
  8286. // If the block isn't obviously global, i.e. it captures anything at
  8287. // all, then we need to do a few things in the surrounding context:
  8288. if (Result->getBlockDecl()->hasCaptures()) {
  8289. // First, this expression has a new cleanup object.
  8290. ExprCleanupObjects.push_back(Result->getBlockDecl());
  8291. ExprNeedsCleanups = true;
  8292. // It also gets a branch-protected scope if any of the captured
  8293. // variables needs destruction.
  8294. for (BlockDecl::capture_const_iterator
  8295. ci = Result->getBlockDecl()->capture_begin(),
  8296. ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
  8297. const VarDecl *var = ci->getVariable();
  8298. if (var->getType().isDestructedType() != QualType::DK_none) {
  8299. getCurFunction()->setHasBranchProtectedScope();
  8300. break;
  8301. }
  8302. }
  8303. }
  8304. return Owned(Result);
  8305. }
  8306. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
  8307. Expr *E, ParsedType Ty,
  8308. SourceLocation RPLoc) {
  8309. TypeSourceInfo *TInfo;
  8310. GetTypeFromParser(Ty, &TInfo);
  8311. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  8312. }
  8313. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  8314. Expr *E, TypeSourceInfo *TInfo,
  8315. SourceLocation RPLoc) {
  8316. Expr *OrigExpr = E;
  8317. // Get the va_list type
  8318. QualType VaListType = Context.getBuiltinVaListType();
  8319. if (VaListType->isArrayType()) {
  8320. // Deal with implicit array decay; for example, on x86-64,
  8321. // va_list is an array, but it's supposed to decay to
  8322. // a pointer for va_arg.
  8323. VaListType = Context.getArrayDecayedType(VaListType);
  8324. // Make sure the input expression also decays appropriately.
  8325. ExprResult Result = UsualUnaryConversions(E);
  8326. if (Result.isInvalid())
  8327. return ExprError();
  8328. E = Result.take();
  8329. } else {
  8330. // Otherwise, the va_list argument must be an l-value because
  8331. // it is modified by va_arg.
  8332. if (!E->isTypeDependent() &&
  8333. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  8334. return ExprError();
  8335. }
  8336. if (!E->isTypeDependent() &&
  8337. !Context.hasSameType(VaListType, E->getType())) {
  8338. return ExprError(Diag(E->getLocStart(),
  8339. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  8340. << OrigExpr->getType() << E->getSourceRange());
  8341. }
  8342. if (!TInfo->getType()->isDependentType()) {
  8343. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  8344. diag::err_second_parameter_to_va_arg_incomplete,
  8345. TInfo->getTypeLoc()))
  8346. return ExprError();
  8347. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  8348. TInfo->getType(),
  8349. diag::err_second_parameter_to_va_arg_abstract,
  8350. TInfo->getTypeLoc()))
  8351. return ExprError();
  8352. if (!TInfo->getType().isPODType(Context)) {
  8353. Diag(TInfo->getTypeLoc().getBeginLoc(),
  8354. TInfo->getType()->isObjCLifetimeType()
  8355. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  8356. : diag::warn_second_parameter_to_va_arg_not_pod)
  8357. << TInfo->getType()
  8358. << TInfo->getTypeLoc().getSourceRange();
  8359. }
  8360. // Check for va_arg where arguments of the given type will be promoted
  8361. // (i.e. this va_arg is guaranteed to have undefined behavior).
  8362. QualType PromoteType;
  8363. if (TInfo->getType()->isPromotableIntegerType()) {
  8364. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  8365. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  8366. PromoteType = QualType();
  8367. }
  8368. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  8369. PromoteType = Context.DoubleTy;
  8370. if (!PromoteType.isNull())
  8371. Diag(TInfo->getTypeLoc().getBeginLoc(),
  8372. diag::warn_second_parameter_to_va_arg_never_compatible)
  8373. << TInfo->getType()
  8374. << PromoteType
  8375. << TInfo->getTypeLoc().getSourceRange();
  8376. }
  8377. QualType T = TInfo->getType().getNonLValueExprType(Context);
  8378. return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
  8379. }
  8380. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  8381. // The type of __null will be int or long, depending on the size of
  8382. // pointers on the target.
  8383. QualType Ty;
  8384. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  8385. if (pw == Context.getTargetInfo().getIntWidth())
  8386. Ty = Context.IntTy;
  8387. else if (pw == Context.getTargetInfo().getLongWidth())
  8388. Ty = Context.LongTy;
  8389. else if (pw == Context.getTargetInfo().getLongLongWidth())
  8390. Ty = Context.LongLongTy;
  8391. else {
  8392. llvm_unreachable("I don't know size of pointer!");
  8393. }
  8394. return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
  8395. }
  8396. static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
  8397. Expr *SrcExpr, FixItHint &Hint) {
  8398. if (!SemaRef.getLangOpts().ObjC1)
  8399. return;
  8400. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  8401. if (!PT)
  8402. return;
  8403. // Check if the destination is of type 'id'.
  8404. if (!PT->isObjCIdType()) {
  8405. // Check if the destination is the 'NSString' interface.
  8406. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  8407. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  8408. return;
  8409. }
  8410. // Ignore any parens, implicit casts (should only be
  8411. // array-to-pointer decays), and not-so-opaque values. The last is
  8412. // important for making this trigger for property assignments.
  8413. SrcExpr = SrcExpr->IgnoreParenImpCasts();
  8414. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  8415. if (OV->getSourceExpr())
  8416. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  8417. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  8418. if (!SL || !SL->isAscii())
  8419. return;
  8420. Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
  8421. }
  8422. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  8423. SourceLocation Loc,
  8424. QualType DstType, QualType SrcType,
  8425. Expr *SrcExpr, AssignmentAction Action,
  8426. bool *Complained) {
  8427. if (Complained)
  8428. *Complained = false;
  8429. // Decode the result (notice that AST's are still created for extensions).
  8430. bool CheckInferredResultType = false;
  8431. bool isInvalid = false;
  8432. unsigned DiagKind = 0;
  8433. FixItHint Hint;
  8434. ConversionFixItGenerator ConvHints;
  8435. bool MayHaveConvFixit = false;
  8436. bool MayHaveFunctionDiff = false;
  8437. switch (ConvTy) {
  8438. case Compatible:
  8439. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  8440. return false;
  8441. case PointerToInt:
  8442. DiagKind = diag::ext_typecheck_convert_pointer_int;
  8443. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  8444. MayHaveConvFixit = true;
  8445. break;
  8446. case IntToPointer:
  8447. DiagKind = diag::ext_typecheck_convert_int_pointer;
  8448. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  8449. MayHaveConvFixit = true;
  8450. break;
  8451. case IncompatiblePointer:
  8452. MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
  8453. DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
  8454. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  8455. SrcType->isObjCObjectPointerType();
  8456. if (Hint.isNull() && !CheckInferredResultType) {
  8457. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  8458. }
  8459. MayHaveConvFixit = true;
  8460. break;
  8461. case IncompatiblePointerSign:
  8462. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  8463. break;
  8464. case FunctionVoidPointer:
  8465. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  8466. break;
  8467. case IncompatiblePointerDiscardsQualifiers: {
  8468. // Perform array-to-pointer decay if necessary.
  8469. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  8470. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  8471. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  8472. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  8473. DiagKind = diag::err_typecheck_incompatible_address_space;
  8474. break;
  8475. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  8476. DiagKind = diag::err_typecheck_incompatible_ownership;
  8477. break;
  8478. }
  8479. llvm_unreachable("unknown error case for discarding qualifiers!");
  8480. // fallthrough
  8481. }
  8482. case CompatiblePointerDiscardsQualifiers:
  8483. // If the qualifiers lost were because we were applying the
  8484. // (deprecated) C++ conversion from a string literal to a char*
  8485. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  8486. // Ideally, this check would be performed in
  8487. // checkPointerTypesForAssignment. However, that would require a
  8488. // bit of refactoring (so that the second argument is an
  8489. // expression, rather than a type), which should be done as part
  8490. // of a larger effort to fix checkPointerTypesForAssignment for
  8491. // C++ semantics.
  8492. if (getLangOpts().CPlusPlus &&
  8493. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  8494. return false;
  8495. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  8496. break;
  8497. case IncompatibleNestedPointerQualifiers:
  8498. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  8499. break;
  8500. case IntToBlockPointer:
  8501. DiagKind = diag::err_int_to_block_pointer;
  8502. break;
  8503. case IncompatibleBlockPointer:
  8504. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  8505. break;
  8506. case IncompatibleObjCQualifiedId:
  8507. // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
  8508. // it can give a more specific diagnostic.
  8509. DiagKind = diag::warn_incompatible_qualified_id;
  8510. break;
  8511. case IncompatibleVectors:
  8512. DiagKind = diag::warn_incompatible_vectors;
  8513. break;
  8514. case IncompatibleObjCWeakRef:
  8515. DiagKind = diag::err_arc_weak_unavailable_assign;
  8516. break;
  8517. case Incompatible:
  8518. DiagKind = diag::err_typecheck_convert_incompatible;
  8519. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  8520. MayHaveConvFixit = true;
  8521. isInvalid = true;
  8522. MayHaveFunctionDiff = true;
  8523. break;
  8524. }
  8525. QualType FirstType, SecondType;
  8526. switch (Action) {
  8527. case AA_Assigning:
  8528. case AA_Initializing:
  8529. // The destination type comes first.
  8530. FirstType = DstType;
  8531. SecondType = SrcType;
  8532. break;
  8533. case AA_Returning:
  8534. case AA_Passing:
  8535. case AA_Converting:
  8536. case AA_Sending:
  8537. case AA_Casting:
  8538. // The source type comes first.
  8539. FirstType = SrcType;
  8540. SecondType = DstType;
  8541. break;
  8542. }
  8543. PartialDiagnostic FDiag = PDiag(DiagKind);
  8544. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  8545. // If we can fix the conversion, suggest the FixIts.
  8546. assert(ConvHints.isNull() || Hint.isNull());
  8547. if (!ConvHints.isNull()) {
  8548. for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
  8549. HE = ConvHints.Hints.end(); HI != HE; ++HI)
  8550. FDiag << *HI;
  8551. } else {
  8552. FDiag << Hint;
  8553. }
  8554. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  8555. if (MayHaveFunctionDiff)
  8556. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  8557. Diag(Loc, FDiag);
  8558. if (SecondType == Context.OverloadTy)
  8559. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  8560. FirstType);
  8561. if (CheckInferredResultType)
  8562. EmitRelatedResultTypeNote(SrcExpr);
  8563. if (Complained)
  8564. *Complained = true;
  8565. return isInvalid;
  8566. }
  8567. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  8568. llvm::APSInt *Result) {
  8569. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  8570. public:
  8571. virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
  8572. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  8573. }
  8574. } Diagnoser;
  8575. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  8576. }
  8577. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  8578. llvm::APSInt *Result,
  8579. unsigned DiagID,
  8580. bool AllowFold) {
  8581. class IDDiagnoser : public VerifyICEDiagnoser {
  8582. unsigned DiagID;
  8583. public:
  8584. IDDiagnoser(unsigned DiagID)
  8585. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  8586. virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
  8587. S.Diag(Loc, DiagID) << SR;
  8588. }
  8589. } Diagnoser(DiagID);
  8590. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  8591. }
  8592. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  8593. SourceRange SR) {
  8594. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  8595. }
  8596. ExprResult
  8597. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  8598. VerifyICEDiagnoser &Diagnoser,
  8599. bool AllowFold) {
  8600. SourceLocation DiagLoc = E->getLocStart();
  8601. if (getLangOpts().CPlusPlus0x) {
  8602. // C++11 [expr.const]p5:
  8603. // If an expression of literal class type is used in a context where an
  8604. // integral constant expression is required, then that class type shall
  8605. // have a single non-explicit conversion function to an integral or
  8606. // unscoped enumeration type
  8607. ExprResult Converted;
  8608. if (!Diagnoser.Suppress) {
  8609. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  8610. public:
  8611. CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
  8612. virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  8613. QualType T) {
  8614. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  8615. }
  8616. virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
  8617. SourceLocation Loc,
  8618. QualType T) {
  8619. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  8620. }
  8621. virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
  8622. SourceLocation Loc,
  8623. QualType T,
  8624. QualType ConvTy) {
  8625. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  8626. }
  8627. virtual DiagnosticBuilder noteExplicitConv(Sema &S,
  8628. CXXConversionDecl *Conv,
  8629. QualType ConvTy) {
  8630. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  8631. << ConvTy->isEnumeralType() << ConvTy;
  8632. }
  8633. virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  8634. QualType T) {
  8635. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  8636. }
  8637. virtual DiagnosticBuilder noteAmbiguous(Sema &S,
  8638. CXXConversionDecl *Conv,
  8639. QualType ConvTy) {
  8640. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  8641. << ConvTy->isEnumeralType() << ConvTy;
  8642. }
  8643. virtual DiagnosticBuilder diagnoseConversion(Sema &S,
  8644. SourceLocation Loc,
  8645. QualType T,
  8646. QualType ConvTy) {
  8647. return DiagnosticBuilder::getEmpty();
  8648. }
  8649. } ConvertDiagnoser;
  8650. Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
  8651. ConvertDiagnoser,
  8652. /*AllowScopedEnumerations*/ false);
  8653. } else {
  8654. // The caller wants to silently enquire whether this is an ICE. Don't
  8655. // produce any diagnostics if it isn't.
  8656. class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
  8657. public:
  8658. SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
  8659. virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  8660. QualType T) {
  8661. return DiagnosticBuilder::getEmpty();
  8662. }
  8663. virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
  8664. SourceLocation Loc,
  8665. QualType T) {
  8666. return DiagnosticBuilder::getEmpty();
  8667. }
  8668. virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
  8669. SourceLocation Loc,
  8670. QualType T,
  8671. QualType ConvTy) {
  8672. return DiagnosticBuilder::getEmpty();
  8673. }
  8674. virtual DiagnosticBuilder noteExplicitConv(Sema &S,
  8675. CXXConversionDecl *Conv,
  8676. QualType ConvTy) {
  8677. return DiagnosticBuilder::getEmpty();
  8678. }
  8679. virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  8680. QualType T) {
  8681. return DiagnosticBuilder::getEmpty();
  8682. }
  8683. virtual DiagnosticBuilder noteAmbiguous(Sema &S,
  8684. CXXConversionDecl *Conv,
  8685. QualType ConvTy) {
  8686. return DiagnosticBuilder::getEmpty();
  8687. }
  8688. virtual DiagnosticBuilder diagnoseConversion(Sema &S,
  8689. SourceLocation Loc,
  8690. QualType T,
  8691. QualType ConvTy) {
  8692. return DiagnosticBuilder::getEmpty();
  8693. }
  8694. } ConvertDiagnoser;
  8695. Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
  8696. ConvertDiagnoser, false);
  8697. }
  8698. if (Converted.isInvalid())
  8699. return Converted;
  8700. E = Converted.take();
  8701. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  8702. return ExprError();
  8703. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  8704. // An ICE must be of integral or unscoped enumeration type.
  8705. if (!Diagnoser.Suppress)
  8706. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  8707. return ExprError();
  8708. }
  8709. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  8710. // in the non-ICE case.
  8711. if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
  8712. if (Result)
  8713. *Result = E->EvaluateKnownConstInt(Context);
  8714. return Owned(E);
  8715. }
  8716. Expr::EvalResult EvalResult;
  8717. llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
  8718. EvalResult.Diag = &Notes;
  8719. // Try to evaluate the expression, and produce diagnostics explaining why it's
  8720. // not a constant expression as a side-effect.
  8721. bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
  8722. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  8723. // In C++11, we can rely on diagnostics being produced for any expression
  8724. // which is not a constant expression. If no diagnostics were produced, then
  8725. // this is a constant expression.
  8726. if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
  8727. if (Result)
  8728. *Result = EvalResult.Val.getInt();
  8729. return Owned(E);
  8730. }
  8731. // If our only note is the usual "invalid subexpression" note, just point
  8732. // the caret at its location rather than producing an essentially
  8733. // redundant note.
  8734. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  8735. diag::note_invalid_subexpr_in_const_expr) {
  8736. DiagLoc = Notes[0].first;
  8737. Notes.clear();
  8738. }
  8739. if (!Folded || !AllowFold) {
  8740. if (!Diagnoser.Suppress) {
  8741. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  8742. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  8743. Diag(Notes[I].first, Notes[I].second);
  8744. }
  8745. return ExprError();
  8746. }
  8747. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  8748. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  8749. Diag(Notes[I].first, Notes[I].second);
  8750. if (Result)
  8751. *Result = EvalResult.Val.getInt();
  8752. return Owned(E);
  8753. }
  8754. namespace {
  8755. // Handle the case where we conclude a expression which we speculatively
  8756. // considered to be unevaluated is actually evaluated.
  8757. class TransformToPE : public TreeTransform<TransformToPE> {
  8758. typedef TreeTransform<TransformToPE> BaseTransform;
  8759. public:
  8760. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  8761. // Make sure we redo semantic analysis
  8762. bool AlwaysRebuild() { return true; }
  8763. // Make sure we handle LabelStmts correctly.
  8764. // FIXME: This does the right thing, but maybe we need a more general
  8765. // fix to TreeTransform?
  8766. StmtResult TransformLabelStmt(LabelStmt *S) {
  8767. S->getDecl()->setStmt(0);
  8768. return BaseTransform::TransformLabelStmt(S);
  8769. }
  8770. // We need to special-case DeclRefExprs referring to FieldDecls which
  8771. // are not part of a member pointer formation; normal TreeTransforming
  8772. // doesn't catch this case because of the way we represent them in the AST.
  8773. // FIXME: This is a bit ugly; is it really the best way to handle this
  8774. // case?
  8775. //
  8776. // Error on DeclRefExprs referring to FieldDecls.
  8777. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  8778. if (isa<FieldDecl>(E->getDecl()) &&
  8779. !SemaRef.isUnevaluatedContext())
  8780. return SemaRef.Diag(E->getLocation(),
  8781. diag::err_invalid_non_static_member_use)
  8782. << E->getDecl() << E->getSourceRange();
  8783. return BaseTransform::TransformDeclRefExpr(E);
  8784. }
  8785. // Exception: filter out member pointer formation
  8786. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  8787. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  8788. return E;
  8789. return BaseTransform::TransformUnaryOperator(E);
  8790. }
  8791. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  8792. // Lambdas never need to be transformed.
  8793. return E;
  8794. }
  8795. };
  8796. }
  8797. ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
  8798. assert(ExprEvalContexts.back().Context == Unevaluated &&
  8799. "Should only transform unevaluated expressions");
  8800. ExprEvalContexts.back().Context =
  8801. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  8802. if (ExprEvalContexts.back().Context == Unevaluated)
  8803. return E;
  8804. return TransformToPE(*this).TransformExpr(E);
  8805. }
  8806. void
  8807. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  8808. Decl *LambdaContextDecl,
  8809. bool IsDecltype) {
  8810. ExprEvalContexts.push_back(
  8811. ExpressionEvaluationContextRecord(NewContext,
  8812. ExprCleanupObjects.size(),
  8813. ExprNeedsCleanups,
  8814. LambdaContextDecl,
  8815. IsDecltype));
  8816. ExprNeedsCleanups = false;
  8817. if (!MaybeODRUseExprs.empty())
  8818. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  8819. }
  8820. void Sema::PopExpressionEvaluationContext() {
  8821. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  8822. if (!Rec.Lambdas.empty()) {
  8823. if (Rec.Context == Unevaluated) {
  8824. // C++11 [expr.prim.lambda]p2:
  8825. // A lambda-expression shall not appear in an unevaluated operand
  8826. // (Clause 5).
  8827. for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
  8828. Diag(Rec.Lambdas[I]->getLocStart(),
  8829. diag::err_lambda_unevaluated_operand);
  8830. } else {
  8831. // Mark the capture expressions odr-used. This was deferred
  8832. // during lambda expression creation.
  8833. for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
  8834. LambdaExpr *Lambda = Rec.Lambdas[I];
  8835. for (LambdaExpr::capture_init_iterator
  8836. C = Lambda->capture_init_begin(),
  8837. CEnd = Lambda->capture_init_end();
  8838. C != CEnd; ++C) {
  8839. MarkDeclarationsReferencedInExpr(*C);
  8840. }
  8841. }
  8842. }
  8843. }
  8844. // When are coming out of an unevaluated context, clear out any
  8845. // temporaries that we may have created as part of the evaluation of
  8846. // the expression in that context: they aren't relevant because they
  8847. // will never be constructed.
  8848. if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
  8849. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  8850. ExprCleanupObjects.end());
  8851. ExprNeedsCleanups = Rec.ParentNeedsCleanups;
  8852. CleanupVarDeclMarking();
  8853. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  8854. // Otherwise, merge the contexts together.
  8855. } else {
  8856. ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
  8857. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  8858. Rec.SavedMaybeODRUseExprs.end());
  8859. }
  8860. // Pop the current expression evaluation context off the stack.
  8861. ExprEvalContexts.pop_back();
  8862. }
  8863. void Sema::DiscardCleanupsInEvaluationContext() {
  8864. ExprCleanupObjects.erase(
  8865. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  8866. ExprCleanupObjects.end());
  8867. ExprNeedsCleanups = false;
  8868. MaybeODRUseExprs.clear();
  8869. }
  8870. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  8871. if (!E->getType()->isVariablyModifiedType())
  8872. return E;
  8873. return TranformToPotentiallyEvaluated(E);
  8874. }
  8875. static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
  8876. // Do not mark anything as "used" within a dependent context; wait for
  8877. // an instantiation.
  8878. if (SemaRef.CurContext->isDependentContext())
  8879. return false;
  8880. switch (SemaRef.ExprEvalContexts.back().Context) {
  8881. case Sema::Unevaluated:
  8882. // We are in an expression that is not potentially evaluated; do nothing.
  8883. // (Depending on how you read the standard, we actually do need to do
  8884. // something here for null pointer constants, but the standard's
  8885. // definition of a null pointer constant is completely crazy.)
  8886. return false;
  8887. case Sema::ConstantEvaluated:
  8888. case Sema::PotentiallyEvaluated:
  8889. // We are in a potentially evaluated expression (or a constant-expression
  8890. // in C++03); we need to do implicit template instantiation, implicitly
  8891. // define class members, and mark most declarations as used.
  8892. return true;
  8893. case Sema::PotentiallyEvaluatedIfUsed:
  8894. // Referenced declarations will only be used if the construct in the
  8895. // containing expression is used.
  8896. return false;
  8897. }
  8898. llvm_unreachable("Invalid context");
  8899. }
  8900. /// \brief Mark a function referenced, and check whether it is odr-used
  8901. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  8902. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
  8903. assert(Func && "No function?");
  8904. Func->setReferenced();
  8905. // Don't mark this function as used multiple times, unless it's a constexpr
  8906. // function which we need to instantiate.
  8907. if (Func->isUsed(false) &&
  8908. !(Func->isConstexpr() && !Func->getBody() &&
  8909. Func->isImplicitlyInstantiable()))
  8910. return;
  8911. if (!IsPotentiallyEvaluatedContext(*this))
  8912. return;
  8913. // Note that this declaration has been used.
  8914. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  8915. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  8916. if (Constructor->isDefaultConstructor()) {
  8917. if (Constructor->isTrivial())
  8918. return;
  8919. if (!Constructor->isUsed(false))
  8920. DefineImplicitDefaultConstructor(Loc, Constructor);
  8921. } else if (Constructor->isCopyConstructor()) {
  8922. if (!Constructor->isUsed(false))
  8923. DefineImplicitCopyConstructor(Loc, Constructor);
  8924. } else if (Constructor->isMoveConstructor()) {
  8925. if (!Constructor->isUsed(false))
  8926. DefineImplicitMoveConstructor(Loc, Constructor);
  8927. }
  8928. }
  8929. MarkVTableUsed(Loc, Constructor->getParent());
  8930. } else if (CXXDestructorDecl *Destructor =
  8931. dyn_cast<CXXDestructorDecl>(Func)) {
  8932. if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
  8933. !Destructor->isUsed(false))
  8934. DefineImplicitDestructor(Loc, Destructor);
  8935. if (Destructor->isVirtual())
  8936. MarkVTableUsed(Loc, Destructor->getParent());
  8937. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  8938. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
  8939. MethodDecl->isOverloadedOperator() &&
  8940. MethodDecl->getOverloadedOperator() == OO_Equal) {
  8941. if (!MethodDecl->isUsed(false)) {
  8942. if (MethodDecl->isCopyAssignmentOperator())
  8943. DefineImplicitCopyAssignment(Loc, MethodDecl);
  8944. else
  8945. DefineImplicitMoveAssignment(Loc, MethodDecl);
  8946. }
  8947. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  8948. MethodDecl->getParent()->isLambda()) {
  8949. CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
  8950. if (Conversion->isLambdaToBlockPointerConversion())
  8951. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  8952. else
  8953. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  8954. } else if (MethodDecl->isVirtual())
  8955. MarkVTableUsed(Loc, MethodDecl->getParent());
  8956. }
  8957. // Recursive functions should be marked when used from another function.
  8958. // FIXME: Is this really right?
  8959. if (CurContext == Func) return;
  8960. // Resolve the exception specification for any function which is
  8961. // used: CodeGen will need it.
  8962. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  8963. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  8964. ResolveExceptionSpec(Loc, FPT);
  8965. // Implicit instantiation of function templates and member functions of
  8966. // class templates.
  8967. if (Func->isImplicitlyInstantiable()) {
  8968. bool AlreadyInstantiated = false;
  8969. SourceLocation PointOfInstantiation = Loc;
  8970. if (FunctionTemplateSpecializationInfo *SpecInfo
  8971. = Func->getTemplateSpecializationInfo()) {
  8972. if (SpecInfo->getPointOfInstantiation().isInvalid())
  8973. SpecInfo->setPointOfInstantiation(Loc);
  8974. else if (SpecInfo->getTemplateSpecializationKind()
  8975. == TSK_ImplicitInstantiation) {
  8976. AlreadyInstantiated = true;
  8977. PointOfInstantiation = SpecInfo->getPointOfInstantiation();
  8978. }
  8979. } else if (MemberSpecializationInfo *MSInfo
  8980. = Func->getMemberSpecializationInfo()) {
  8981. if (MSInfo->getPointOfInstantiation().isInvalid())
  8982. MSInfo->setPointOfInstantiation(Loc);
  8983. else if (MSInfo->getTemplateSpecializationKind()
  8984. == TSK_ImplicitInstantiation) {
  8985. AlreadyInstantiated = true;
  8986. PointOfInstantiation = MSInfo->getPointOfInstantiation();
  8987. }
  8988. }
  8989. if (!AlreadyInstantiated || Func->isConstexpr()) {
  8990. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  8991. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
  8992. PendingLocalImplicitInstantiations.push_back(
  8993. std::make_pair(Func, PointOfInstantiation));
  8994. else if (Func->isConstexpr())
  8995. // Do not defer instantiations of constexpr functions, to avoid the
  8996. // expression evaluator needing to call back into Sema if it sees a
  8997. // call to such a function.
  8998. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  8999. else {
  9000. PendingInstantiations.push_back(std::make_pair(Func,
  9001. PointOfInstantiation));
  9002. // Notify the consumer that a function was implicitly instantiated.
  9003. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  9004. }
  9005. }
  9006. } else {
  9007. // Walk redefinitions, as some of them may be instantiable.
  9008. for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
  9009. e(Func->redecls_end()); i != e; ++i) {
  9010. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  9011. MarkFunctionReferenced(Loc, *i);
  9012. }
  9013. }
  9014. // Keep track of used but undefined functions.
  9015. if (!Func->isPure() && !Func->hasBody() &&
  9016. Func->getLinkage() != ExternalLinkage) {
  9017. SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
  9018. if (old.isInvalid()) old = Loc;
  9019. }
  9020. Func->setUsed(true);
  9021. }
  9022. static void
  9023. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  9024. VarDecl *var, DeclContext *DC) {
  9025. DeclContext *VarDC = var->getDeclContext();
  9026. // If the parameter still belongs to the translation unit, then
  9027. // we're actually just using one parameter in the declaration of
  9028. // the next.
  9029. if (isa<ParmVarDecl>(var) &&
  9030. isa<TranslationUnitDecl>(VarDC))
  9031. return;
  9032. // For C code, don't diagnose about capture if we're not actually in code
  9033. // right now; it's impossible to write a non-constant expression outside of
  9034. // function context, so we'll get other (more useful) diagnostics later.
  9035. //
  9036. // For C++, things get a bit more nasty... it would be nice to suppress this
  9037. // diagnostic for certain cases like using a local variable in an array bound
  9038. // for a member of a local class, but the correct predicate is not obvious.
  9039. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  9040. return;
  9041. if (isa<CXXMethodDecl>(VarDC) &&
  9042. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  9043. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
  9044. << var->getIdentifier();
  9045. } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
  9046. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
  9047. << var->getIdentifier() << fn->getDeclName();
  9048. } else if (isa<BlockDecl>(VarDC)) {
  9049. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
  9050. << var->getIdentifier();
  9051. } else {
  9052. // FIXME: Is there any other context where a local variable can be
  9053. // declared?
  9054. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
  9055. << var->getIdentifier();
  9056. }
  9057. S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
  9058. << var->getIdentifier();
  9059. // FIXME: Add additional diagnostic info about class etc. which prevents
  9060. // capture.
  9061. }
  9062. /// \brief Capture the given variable in the given lambda expression.
  9063. static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
  9064. VarDecl *Var, QualType FieldType,
  9065. QualType DeclRefType,
  9066. SourceLocation Loc,
  9067. bool RefersToEnclosingLocal) {
  9068. CXXRecordDecl *Lambda = LSI->Lambda;
  9069. // Build the non-static data member.
  9070. FieldDecl *Field
  9071. = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
  9072. S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
  9073. 0, false, ICIS_NoInit);
  9074. Field->setImplicit(true);
  9075. Field->setAccess(AS_private);
  9076. Lambda->addDecl(Field);
  9077. // C++11 [expr.prim.lambda]p21:
  9078. // When the lambda-expression is evaluated, the entities that
  9079. // are captured by copy are used to direct-initialize each
  9080. // corresponding non-static data member of the resulting closure
  9081. // object. (For array members, the array elements are
  9082. // direct-initialized in increasing subscript order.) These
  9083. // initializations are performed in the (unspecified) order in
  9084. // which the non-static data members are declared.
  9085. // Introduce a new evaluation context for the initialization, so
  9086. // that temporaries introduced as part of the capture are retained
  9087. // to be re-"exported" from the lambda expression itself.
  9088. S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
  9089. // C++ [expr.prim.labda]p12:
  9090. // An entity captured by a lambda-expression is odr-used (3.2) in
  9091. // the scope containing the lambda-expression.
  9092. Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
  9093. DeclRefType, VK_LValue, Loc);
  9094. Var->setReferenced(true);
  9095. Var->setUsed(true);
  9096. // When the field has array type, create index variables for each
  9097. // dimension of the array. We use these index variables to subscript
  9098. // the source array, and other clients (e.g., CodeGen) will perform
  9099. // the necessary iteration with these index variables.
  9100. SmallVector<VarDecl *, 4> IndexVariables;
  9101. QualType BaseType = FieldType;
  9102. QualType SizeType = S.Context.getSizeType();
  9103. LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
  9104. while (const ConstantArrayType *Array
  9105. = S.Context.getAsConstantArrayType(BaseType)) {
  9106. // Create the iteration variable for this array index.
  9107. IdentifierInfo *IterationVarName = 0;
  9108. {
  9109. SmallString<8> Str;
  9110. llvm::raw_svector_ostream OS(Str);
  9111. OS << "__i" << IndexVariables.size();
  9112. IterationVarName = &S.Context.Idents.get(OS.str());
  9113. }
  9114. VarDecl *IterationVar
  9115. = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  9116. IterationVarName, SizeType,
  9117. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  9118. SC_None, SC_None);
  9119. IndexVariables.push_back(IterationVar);
  9120. LSI->ArrayIndexVars.push_back(IterationVar);
  9121. // Create a reference to the iteration variable.
  9122. ExprResult IterationVarRef
  9123. = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
  9124. assert(!IterationVarRef.isInvalid() &&
  9125. "Reference to invented variable cannot fail!");
  9126. IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
  9127. assert(!IterationVarRef.isInvalid() &&
  9128. "Conversion of invented variable cannot fail!");
  9129. // Subscript the array with this iteration variable.
  9130. ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
  9131. Ref, Loc, IterationVarRef.take(), Loc);
  9132. if (Subscript.isInvalid()) {
  9133. S.CleanupVarDeclMarking();
  9134. S.DiscardCleanupsInEvaluationContext();
  9135. S.PopExpressionEvaluationContext();
  9136. return ExprError();
  9137. }
  9138. Ref = Subscript.take();
  9139. BaseType = Array->getElementType();
  9140. }
  9141. // Construct the entity that we will be initializing. For an array, this
  9142. // will be first element in the array, which may require several levels
  9143. // of array-subscript entities.
  9144. SmallVector<InitializedEntity, 4> Entities;
  9145. Entities.reserve(1 + IndexVariables.size());
  9146. Entities.push_back(
  9147. InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
  9148. for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
  9149. Entities.push_back(InitializedEntity::InitializeElement(S.Context,
  9150. 0,
  9151. Entities.back()));
  9152. InitializationKind InitKind
  9153. = InitializationKind::CreateDirect(Loc, Loc, Loc);
  9154. InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
  9155. ExprResult Result(true);
  9156. if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
  9157. Result = Init.Perform(S, Entities.back(), InitKind,
  9158. MultiExprArg(S, &Ref, 1));
  9159. // If this initialization requires any cleanups (e.g., due to a
  9160. // default argument to a copy constructor), note that for the
  9161. // lambda.
  9162. if (S.ExprNeedsCleanups)
  9163. LSI->ExprNeedsCleanups = true;
  9164. // Exit the expression evaluation context used for the capture.
  9165. S.CleanupVarDeclMarking();
  9166. S.DiscardCleanupsInEvaluationContext();
  9167. S.PopExpressionEvaluationContext();
  9168. return Result;
  9169. }
  9170. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  9171. TryCaptureKind Kind, SourceLocation EllipsisLoc,
  9172. bool BuildAndDiagnose,
  9173. QualType &CaptureType,
  9174. QualType &DeclRefType) {
  9175. bool Nested = false;
  9176. DeclContext *DC = CurContext;
  9177. if (Var->getDeclContext() == DC) return true;
  9178. if (!Var->hasLocalStorage()) return true;
  9179. bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  9180. // Walk up the stack to determine whether we can capture the variable,
  9181. // performing the "simple" checks that don't depend on type. We stop when
  9182. // we've either hit the declared scope of the variable or find an existing
  9183. // capture of that variable.
  9184. CaptureType = Var->getType();
  9185. DeclRefType = CaptureType.getNonReferenceType();
  9186. bool Explicit = (Kind != TryCapture_Implicit);
  9187. unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
  9188. do {
  9189. // Only block literals and lambda expressions can capture; other
  9190. // scopes don't work.
  9191. DeclContext *ParentDC;
  9192. if (isa<BlockDecl>(DC))
  9193. ParentDC = DC->getParent();
  9194. else if (isa<CXXMethodDecl>(DC) &&
  9195. cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
  9196. cast<CXXRecordDecl>(DC->getParent())->isLambda())
  9197. ParentDC = DC->getParent()->getParent();
  9198. else {
  9199. if (BuildAndDiagnose)
  9200. diagnoseUncapturableValueReference(*this, Loc, Var, DC);
  9201. return true;
  9202. }
  9203. CapturingScopeInfo *CSI =
  9204. cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
  9205. // Check whether we've already captured it.
  9206. if (CSI->CaptureMap.count(Var)) {
  9207. // If we found a capture, any subcaptures are nested.
  9208. Nested = true;
  9209. // Retrieve the capture type for this variable.
  9210. CaptureType = CSI->getCapture(Var).getCaptureType();
  9211. // Compute the type of an expression that refers to this variable.
  9212. DeclRefType = CaptureType.getNonReferenceType();
  9213. const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
  9214. if (Cap.isCopyCapture() &&
  9215. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
  9216. DeclRefType.addConst();
  9217. break;
  9218. }
  9219. bool IsBlock = isa<BlockScopeInfo>(CSI);
  9220. bool IsLambda = !IsBlock;
  9221. // Lambdas are not allowed to capture unnamed variables
  9222. // (e.g. anonymous unions).
  9223. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  9224. // assuming that's the intent.
  9225. if (IsLambda && !Var->getDeclName()) {
  9226. if (BuildAndDiagnose) {
  9227. Diag(Loc, diag::err_lambda_capture_anonymous_var);
  9228. Diag(Var->getLocation(), diag::note_declared_at);
  9229. }
  9230. return true;
  9231. }
  9232. // Prohibit variably-modified types; they're difficult to deal with.
  9233. if (Var->getType()->isVariablyModifiedType()) {
  9234. if (BuildAndDiagnose) {
  9235. if (IsBlock)
  9236. Diag(Loc, diag::err_ref_vm_type);
  9237. else
  9238. Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
  9239. Diag(Var->getLocation(), diag::note_previous_decl)
  9240. << Var->getDeclName();
  9241. }
  9242. return true;
  9243. }
  9244. // Lambdas are not allowed to capture __block variables; they don't
  9245. // support the expected semantics.
  9246. if (IsLambda && HasBlocksAttr) {
  9247. if (BuildAndDiagnose) {
  9248. Diag(Loc, diag::err_lambda_capture_block)
  9249. << Var->getDeclName();
  9250. Diag(Var->getLocation(), diag::note_previous_decl)
  9251. << Var->getDeclName();
  9252. }
  9253. return true;
  9254. }
  9255. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  9256. // No capture-default
  9257. if (BuildAndDiagnose) {
  9258. Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
  9259. Diag(Var->getLocation(), diag::note_previous_decl)
  9260. << Var->getDeclName();
  9261. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
  9262. diag::note_lambda_decl);
  9263. }
  9264. return true;
  9265. }
  9266. FunctionScopesIndex--;
  9267. DC = ParentDC;
  9268. Explicit = false;
  9269. } while (!Var->getDeclContext()->Equals(DC));
  9270. // Walk back down the scope stack, computing the type of the capture at
  9271. // each step, checking type-specific requirements, and adding captures if
  9272. // requested.
  9273. for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
  9274. ++I) {
  9275. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  9276. // Compute the type of the capture and of a reference to the capture within
  9277. // this scope.
  9278. if (isa<BlockScopeInfo>(CSI)) {
  9279. Expr *CopyExpr = 0;
  9280. bool ByRef = false;
  9281. // Blocks are not allowed to capture arrays.
  9282. if (CaptureType->isArrayType()) {
  9283. if (BuildAndDiagnose) {
  9284. Diag(Loc, diag::err_ref_array_type);
  9285. Diag(Var->getLocation(), diag::note_previous_decl)
  9286. << Var->getDeclName();
  9287. }
  9288. return true;
  9289. }
  9290. // Forbid the block-capture of autoreleasing variables.
  9291. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  9292. if (BuildAndDiagnose) {
  9293. Diag(Loc, diag::err_arc_autoreleasing_capture)
  9294. << /*block*/ 0;
  9295. Diag(Var->getLocation(), diag::note_previous_decl)
  9296. << Var->getDeclName();
  9297. }
  9298. return true;
  9299. }
  9300. if (HasBlocksAttr || CaptureType->isReferenceType()) {
  9301. // Block capture by reference does not change the capture or
  9302. // declaration reference types.
  9303. ByRef = true;
  9304. } else {
  9305. // Block capture by copy introduces 'const'.
  9306. CaptureType = CaptureType.getNonReferenceType().withConst();
  9307. DeclRefType = CaptureType;
  9308. if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
  9309. if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
  9310. // The capture logic needs the destructor, so make sure we mark it.
  9311. // Usually this is unnecessary because most local variables have
  9312. // their destructors marked at declaration time, but parameters are
  9313. // an exception because it's technically only the call site that
  9314. // actually requires the destructor.
  9315. if (isa<ParmVarDecl>(Var))
  9316. FinalizeVarWithDestructor(Var, Record);
  9317. // According to the blocks spec, the capture of a variable from
  9318. // the stack requires a const copy constructor. This is not true
  9319. // of the copy/move done to move a __block variable to the heap.
  9320. Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
  9321. DeclRefType.withConst(),
  9322. VK_LValue, Loc);
  9323. ExprResult Result
  9324. = PerformCopyInitialization(
  9325. InitializedEntity::InitializeBlock(Var->getLocation(),
  9326. CaptureType, false),
  9327. Loc, Owned(DeclRef));
  9328. // Build a full-expression copy expression if initialization
  9329. // succeeded and used a non-trivial constructor. Recover from
  9330. // errors by pretending that the copy isn't necessary.
  9331. if (!Result.isInvalid() &&
  9332. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  9333. ->isTrivial()) {
  9334. Result = MaybeCreateExprWithCleanups(Result);
  9335. CopyExpr = Result.take();
  9336. }
  9337. }
  9338. }
  9339. }
  9340. // Actually capture the variable.
  9341. if (BuildAndDiagnose)
  9342. CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
  9343. SourceLocation(), CaptureType, CopyExpr);
  9344. Nested = true;
  9345. continue;
  9346. }
  9347. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  9348. // Determine whether we are capturing by reference or by value.
  9349. bool ByRef = false;
  9350. if (I == N - 1 && Kind != TryCapture_Implicit) {
  9351. ByRef = (Kind == TryCapture_ExplicitByRef);
  9352. } else {
  9353. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  9354. }
  9355. // Compute the type of the field that will capture this variable.
  9356. if (ByRef) {
  9357. // C++11 [expr.prim.lambda]p15:
  9358. // An entity is captured by reference if it is implicitly or
  9359. // explicitly captured but not captured by copy. It is
  9360. // unspecified whether additional unnamed non-static data
  9361. // members are declared in the closure type for entities
  9362. // captured by reference.
  9363. //
  9364. // FIXME: It is not clear whether we want to build an lvalue reference
  9365. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  9366. // to do the former, while EDG does the latter. Core issue 1249 will
  9367. // clarify, but for now we follow GCC because it's a more permissive and
  9368. // easily defensible position.
  9369. CaptureType = Context.getLValueReferenceType(DeclRefType);
  9370. } else {
  9371. // C++11 [expr.prim.lambda]p14:
  9372. // For each entity captured by copy, an unnamed non-static
  9373. // data member is declared in the closure type. The
  9374. // declaration order of these members is unspecified. The type
  9375. // of such a data member is the type of the corresponding
  9376. // captured entity if the entity is not a reference to an
  9377. // object, or the referenced type otherwise. [Note: If the
  9378. // captured entity is a reference to a function, the
  9379. // corresponding data member is also a reference to a
  9380. // function. - end note ]
  9381. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  9382. if (!RefType->getPointeeType()->isFunctionType())
  9383. CaptureType = RefType->getPointeeType();
  9384. }
  9385. // Forbid the lambda copy-capture of autoreleasing variables.
  9386. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  9387. if (BuildAndDiagnose) {
  9388. Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  9389. Diag(Var->getLocation(), diag::note_previous_decl)
  9390. << Var->getDeclName();
  9391. }
  9392. return true;
  9393. }
  9394. }
  9395. // Capture this variable in the lambda.
  9396. Expr *CopyExpr = 0;
  9397. if (BuildAndDiagnose) {
  9398. ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
  9399. DeclRefType, Loc,
  9400. I == N-1);
  9401. if (!Result.isInvalid())
  9402. CopyExpr = Result.take();
  9403. }
  9404. // Compute the type of a reference to this captured variable.
  9405. if (ByRef)
  9406. DeclRefType = CaptureType.getNonReferenceType();
  9407. else {
  9408. // C++ [expr.prim.lambda]p5:
  9409. // The closure type for a lambda-expression has a public inline
  9410. // function call operator [...]. This function call operator is
  9411. // declared const (9.3.1) if and only if the lambda-expression’s
  9412. // parameter-declaration-clause is not followed by mutable.
  9413. DeclRefType = CaptureType.getNonReferenceType();
  9414. if (!LSI->Mutable && !CaptureType->isReferenceType())
  9415. DeclRefType.addConst();
  9416. }
  9417. // Add the capture.
  9418. if (BuildAndDiagnose)
  9419. CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
  9420. EllipsisLoc, CaptureType, CopyExpr);
  9421. Nested = true;
  9422. }
  9423. return false;
  9424. }
  9425. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  9426. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  9427. QualType CaptureType;
  9428. QualType DeclRefType;
  9429. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  9430. /*BuildAndDiagnose=*/true, CaptureType,
  9431. DeclRefType);
  9432. }
  9433. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  9434. QualType CaptureType;
  9435. QualType DeclRefType;
  9436. // Determine whether we can capture this variable.
  9437. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  9438. /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
  9439. return QualType();
  9440. return DeclRefType;
  9441. }
  9442. static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
  9443. SourceLocation Loc) {
  9444. // Keep track of used but undefined variables.
  9445. // FIXME: We shouldn't suppress this warning for static data members.
  9446. if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
  9447. Var->getLinkage() != ExternalLinkage &&
  9448. !(Var->isStaticDataMember() && Var->hasInit())) {
  9449. SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
  9450. if (old.isInvalid()) old = Loc;
  9451. }
  9452. SemaRef.tryCaptureVariable(Var, Loc);
  9453. Var->setUsed(true);
  9454. }
  9455. void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
  9456. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  9457. // an object that satisfies the requirements for appearing in a
  9458. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  9459. // is immediately applied." This function handles the lvalue-to-rvalue
  9460. // conversion part.
  9461. MaybeODRUseExprs.erase(E->IgnoreParens());
  9462. }
  9463. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  9464. if (!Res.isUsable())
  9465. return Res;
  9466. // If a constant-expression is a reference to a variable where we delay
  9467. // deciding whether it is an odr-use, just assume we will apply the
  9468. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  9469. // (a non-type template argument), we have special handling anyway.
  9470. UpdateMarkingForLValueToRValue(Res.get());
  9471. return Res;
  9472. }
  9473. void Sema::CleanupVarDeclMarking() {
  9474. for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
  9475. e = MaybeODRUseExprs.end();
  9476. i != e; ++i) {
  9477. VarDecl *Var;
  9478. SourceLocation Loc;
  9479. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
  9480. Var = cast<VarDecl>(DRE->getDecl());
  9481. Loc = DRE->getLocation();
  9482. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
  9483. Var = cast<VarDecl>(ME->getMemberDecl());
  9484. Loc = ME->getMemberLoc();
  9485. } else {
  9486. llvm_unreachable("Unexpcted expression");
  9487. }
  9488. MarkVarDeclODRUsed(*this, Var, Loc);
  9489. }
  9490. MaybeODRUseExprs.clear();
  9491. }
  9492. // Mark a VarDecl referenced, and perform the necessary handling to compute
  9493. // odr-uses.
  9494. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  9495. VarDecl *Var, Expr *E) {
  9496. Var->setReferenced();
  9497. if (!IsPotentiallyEvaluatedContext(SemaRef))
  9498. return;
  9499. // Implicit instantiation of static data members of class templates.
  9500. if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
  9501. MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
  9502. assert(MSInfo && "Missing member specialization information?");
  9503. bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
  9504. if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
  9505. (!AlreadyInstantiated ||
  9506. Var->isUsableInConstantExpressions(SemaRef.Context))) {
  9507. if (!AlreadyInstantiated) {
  9508. // This is a modification of an existing AST node. Notify listeners.
  9509. if (ASTMutationListener *L = SemaRef.getASTMutationListener())
  9510. L->StaticDataMemberInstantiated(Var);
  9511. MSInfo->setPointOfInstantiation(Loc);
  9512. }
  9513. SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
  9514. if (Var->isUsableInConstantExpressions(SemaRef.Context))
  9515. // Do not defer instantiations of variables which could be used in a
  9516. // constant expression.
  9517. SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
  9518. else
  9519. SemaRef.PendingInstantiations.push_back(
  9520. std::make_pair(Var, PointOfInstantiation));
  9521. }
  9522. }
  9523. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  9524. // an object that satisfies the requirements for appearing in a
  9525. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  9526. // is immediately applied." We check the first part here, and
  9527. // Sema::UpdateMarkingForLValueToRValue deals with the second part.
  9528. // Note that we use the C++11 definition everywhere because nothing in
  9529. // C++03 depends on whether we get the C++03 version correct. This does not
  9530. // apply to references, since they are not objects.
  9531. const VarDecl *DefVD;
  9532. if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
  9533. Var->isUsableInConstantExpressions(SemaRef.Context) &&
  9534. Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
  9535. SemaRef.MaybeODRUseExprs.insert(E);
  9536. else
  9537. MarkVarDeclODRUsed(SemaRef, Var, Loc);
  9538. }
  9539. /// \brief Mark a variable referenced, and check whether it is odr-used
  9540. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  9541. /// used directly for normal expressions referring to VarDecl.
  9542. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  9543. DoMarkVarDeclReferenced(*this, Loc, Var, 0);
  9544. }
  9545. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  9546. Decl *D, Expr *E) {
  9547. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  9548. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  9549. return;
  9550. }
  9551. SemaRef.MarkAnyDeclReferenced(Loc, D);
  9552. // If this is a call to a method via a cast, also mark the method in the
  9553. // derived class used in case codegen can devirtualize the call.
  9554. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  9555. if (!ME)
  9556. return;
  9557. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  9558. if (!MD)
  9559. return;
  9560. const Expr *Base = ME->getBase();
  9561. const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
  9562. if (!MostDerivedClassDecl)
  9563. return;
  9564. CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
  9565. if (!DM)
  9566. return;
  9567. SemaRef.MarkAnyDeclReferenced(Loc, DM);
  9568. }
  9569. /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
  9570. void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
  9571. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
  9572. }
  9573. /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
  9574. void Sema::MarkMemberReferenced(MemberExpr *E) {
  9575. MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
  9576. }
  9577. /// \brief Perform marking for a reference to an arbitrary declaration. It
  9578. /// marks the declaration referenced, and performs odr-use checking for functions
  9579. /// and variables. This method should not be used when building an normal
  9580. /// expression which refers to a variable.
  9581. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
  9582. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  9583. MarkVariableReferenced(Loc, VD);
  9584. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  9585. MarkFunctionReferenced(Loc, FD);
  9586. else
  9587. D->setReferenced();
  9588. }
  9589. namespace {
  9590. // Mark all of the declarations referenced
  9591. // FIXME: Not fully implemented yet! We need to have a better understanding
  9592. // of when we're entering
  9593. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  9594. Sema &S;
  9595. SourceLocation Loc;
  9596. public:
  9597. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  9598. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  9599. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  9600. bool TraverseRecordType(RecordType *T);
  9601. };
  9602. }
  9603. bool MarkReferencedDecls::TraverseTemplateArgument(
  9604. const TemplateArgument &Arg) {
  9605. if (Arg.getKind() == TemplateArgument::Declaration) {
  9606. if (Decl *D = Arg.getAsDecl())
  9607. S.MarkAnyDeclReferenced(Loc, D);
  9608. }
  9609. return Inherited::TraverseTemplateArgument(Arg);
  9610. }
  9611. bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
  9612. if (ClassTemplateSpecializationDecl *Spec
  9613. = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
  9614. const TemplateArgumentList &Args = Spec->getTemplateArgs();
  9615. return TraverseTemplateArguments(Args.data(), Args.size());
  9616. }
  9617. return true;
  9618. }
  9619. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  9620. MarkReferencedDecls Marker(*this, Loc);
  9621. Marker.TraverseType(Context.getCanonicalType(T));
  9622. }
  9623. namespace {
  9624. /// \brief Helper class that marks all of the declarations referenced by
  9625. /// potentially-evaluated subexpressions as "referenced".
  9626. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  9627. Sema &S;
  9628. bool SkipLocalVariables;
  9629. public:
  9630. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  9631. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  9632. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  9633. void VisitDeclRefExpr(DeclRefExpr *E) {
  9634. // If we were asked not to visit local variables, don't.
  9635. if (SkipLocalVariables) {
  9636. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  9637. if (VD->hasLocalStorage())
  9638. return;
  9639. }
  9640. S.MarkDeclRefReferenced(E);
  9641. }
  9642. void VisitMemberExpr(MemberExpr *E) {
  9643. S.MarkMemberReferenced(E);
  9644. Inherited::VisitMemberExpr(E);
  9645. }
  9646. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  9647. S.MarkFunctionReferenced(E->getLocStart(),
  9648. const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
  9649. Visit(E->getSubExpr());
  9650. }
  9651. void VisitCXXNewExpr(CXXNewExpr *E) {
  9652. if (E->getOperatorNew())
  9653. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
  9654. if (E->getOperatorDelete())
  9655. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  9656. Inherited::VisitCXXNewExpr(E);
  9657. }
  9658. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  9659. if (E->getOperatorDelete())
  9660. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  9661. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  9662. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  9663. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  9664. S.MarkFunctionReferenced(E->getLocStart(),
  9665. S.LookupDestructor(Record));
  9666. }
  9667. Inherited::VisitCXXDeleteExpr(E);
  9668. }
  9669. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  9670. S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
  9671. Inherited::VisitCXXConstructExpr(E);
  9672. }
  9673. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  9674. Visit(E->getExpr());
  9675. }
  9676. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  9677. Inherited::VisitImplicitCastExpr(E);
  9678. if (E->getCastKind() == CK_LValueToRValue)
  9679. S.UpdateMarkingForLValueToRValue(E->getSubExpr());
  9680. }
  9681. };
  9682. }
  9683. /// \brief Mark any declarations that appear within this expression or any
  9684. /// potentially-evaluated subexpressions as "referenced".
  9685. ///
  9686. /// \param SkipLocalVariables If true, don't mark local variables as
  9687. /// 'referenced'.
  9688. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  9689. bool SkipLocalVariables) {
  9690. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  9691. }
  9692. /// \brief Emit a diagnostic that describes an effect on the run-time behavior
  9693. /// of the program being compiled.
  9694. ///
  9695. /// This routine emits the given diagnostic when the code currently being
  9696. /// type-checked is "potentially evaluated", meaning that there is a
  9697. /// possibility that the code will actually be executable. Code in sizeof()
  9698. /// expressions, code used only during overload resolution, etc., are not
  9699. /// potentially evaluated. This routine will suppress such diagnostics or,
  9700. /// in the absolutely nutty case of potentially potentially evaluated
  9701. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  9702. /// later.
  9703. ///
  9704. /// This routine should be used for all diagnostics that describe the run-time
  9705. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  9706. /// Failure to do so will likely result in spurious diagnostics or failures
  9707. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  9708. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  9709. const PartialDiagnostic &PD) {
  9710. switch (ExprEvalContexts.back().Context) {
  9711. case Unevaluated:
  9712. // The argument will never be evaluated, so don't complain.
  9713. break;
  9714. case ConstantEvaluated:
  9715. // Relevant diagnostics should be produced by constant evaluation.
  9716. break;
  9717. case PotentiallyEvaluated:
  9718. case PotentiallyEvaluatedIfUsed:
  9719. if (Statement && getCurFunctionOrMethodDecl()) {
  9720. FunctionScopes.back()->PossiblyUnreachableDiags.
  9721. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
  9722. }
  9723. else
  9724. Diag(Loc, PD);
  9725. return true;
  9726. }
  9727. return false;
  9728. }
  9729. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  9730. CallExpr *CE, FunctionDecl *FD) {
  9731. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  9732. return false;
  9733. // If we're inside a decltype's expression, don't check for a valid return
  9734. // type or construct temporaries until we know whether this is the last call.
  9735. if (ExprEvalContexts.back().IsDecltype) {
  9736. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  9737. return false;
  9738. }
  9739. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  9740. FunctionDecl *FD;
  9741. CallExpr *CE;
  9742. public:
  9743. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  9744. : FD(FD), CE(CE) { }
  9745. virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
  9746. if (!FD) {
  9747. S.Diag(Loc, diag::err_call_incomplete_return)
  9748. << T << CE->getSourceRange();
  9749. return;
  9750. }
  9751. S.Diag(Loc, diag::err_call_function_incomplete_return)
  9752. << CE->getSourceRange() << FD->getDeclName() << T;
  9753. S.Diag(FD->getLocation(),
  9754. diag::note_function_with_incomplete_return_type_declared_here)
  9755. << FD->getDeclName();
  9756. }
  9757. } Diagnoser(FD, CE);
  9758. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  9759. return true;
  9760. return false;
  9761. }
  9762. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  9763. // will prevent this condition from triggering, which is what we want.
  9764. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  9765. SourceLocation Loc;
  9766. unsigned diagnostic = diag::warn_condition_is_assignment;
  9767. bool IsOrAssign = false;
  9768. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  9769. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  9770. return;
  9771. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  9772. // Greylist some idioms by putting them into a warning subcategory.
  9773. if (ObjCMessageExpr *ME
  9774. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  9775. Selector Sel = ME->getSelector();
  9776. // self = [<foo> init...]
  9777. if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
  9778. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  9779. // <foo> = [<bar> nextObject]
  9780. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  9781. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  9782. }
  9783. Loc = Op->getOperatorLoc();
  9784. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  9785. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  9786. return;
  9787. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  9788. Loc = Op->getOperatorLoc();
  9789. } else {
  9790. // Not an assignment.
  9791. return;
  9792. }
  9793. Diag(Loc, diagnostic) << E->getSourceRange();
  9794. SourceLocation Open = E->getLocStart();
  9795. SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
  9796. Diag(Loc, diag::note_condition_assign_silence)
  9797. << FixItHint::CreateInsertion(Open, "(")
  9798. << FixItHint::CreateInsertion(Close, ")");
  9799. if (IsOrAssign)
  9800. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  9801. << FixItHint::CreateReplacement(Loc, "!=");
  9802. else
  9803. Diag(Loc, diag::note_condition_assign_to_comparison)
  9804. << FixItHint::CreateReplacement(Loc, "==");
  9805. }
  9806. /// \brief Redundant parentheses over an equality comparison can indicate
  9807. /// that the user intended an assignment used as condition.
  9808. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  9809. // Don't warn if the parens came from a macro.
  9810. SourceLocation parenLoc = ParenE->getLocStart();
  9811. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  9812. return;
  9813. // Don't warn for dependent expressions.
  9814. if (ParenE->isTypeDependent())
  9815. return;
  9816. Expr *E = ParenE->IgnoreParens();
  9817. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  9818. if (opE->getOpcode() == BO_EQ &&
  9819. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  9820. == Expr::MLV_Valid) {
  9821. SourceLocation Loc = opE->getOperatorLoc();
  9822. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  9823. SourceRange ParenERange = ParenE->getSourceRange();
  9824. Diag(Loc, diag::note_equality_comparison_silence)
  9825. << FixItHint::CreateRemoval(ParenERange.getBegin())
  9826. << FixItHint::CreateRemoval(ParenERange.getEnd());
  9827. Diag(Loc, diag::note_equality_comparison_to_assign)
  9828. << FixItHint::CreateReplacement(Loc, "=");
  9829. }
  9830. }
  9831. ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
  9832. DiagnoseAssignmentAsCondition(E);
  9833. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  9834. DiagnoseEqualityWithExtraParens(parenE);
  9835. ExprResult result = CheckPlaceholderExpr(E);
  9836. if (result.isInvalid()) return ExprError();
  9837. E = result.take();
  9838. if (!E->isTypeDependent()) {
  9839. if (getLangOpts().CPlusPlus)
  9840. return CheckCXXBooleanCondition(E); // C++ 6.4p4
  9841. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  9842. if (ERes.isInvalid())
  9843. return ExprError();
  9844. E = ERes.take();
  9845. QualType T = E->getType();
  9846. if (!T->isScalarType()) { // C99 6.8.4.1p1
  9847. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  9848. << T << E->getSourceRange();
  9849. return ExprError();
  9850. }
  9851. }
  9852. return Owned(E);
  9853. }
  9854. ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
  9855. Expr *SubExpr) {
  9856. if (!SubExpr)
  9857. return ExprError();
  9858. return CheckBooleanCondition(SubExpr, Loc);
  9859. }
  9860. namespace {
  9861. /// A visitor for rebuilding a call to an __unknown_any expression
  9862. /// to have an appropriate type.
  9863. struct RebuildUnknownAnyFunction
  9864. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  9865. Sema &S;
  9866. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  9867. ExprResult VisitStmt(Stmt *S) {
  9868. llvm_unreachable("unexpected statement!");
  9869. }
  9870. ExprResult VisitExpr(Expr *E) {
  9871. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  9872. << E->getSourceRange();
  9873. return ExprError();
  9874. }
  9875. /// Rebuild an expression which simply semantically wraps another
  9876. /// expression which it shares the type and value kind of.
  9877. template <class T> ExprResult rebuildSugarExpr(T *E) {
  9878. ExprResult SubResult = Visit(E->getSubExpr());
  9879. if (SubResult.isInvalid()) return ExprError();
  9880. Expr *SubExpr = SubResult.take();
  9881. E->setSubExpr(SubExpr);
  9882. E->setType(SubExpr->getType());
  9883. E->setValueKind(SubExpr->getValueKind());
  9884. assert(E->getObjectKind() == OK_Ordinary);
  9885. return E;
  9886. }
  9887. ExprResult VisitParenExpr(ParenExpr *E) {
  9888. return rebuildSugarExpr(E);
  9889. }
  9890. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  9891. return rebuildSugarExpr(E);
  9892. }
  9893. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  9894. ExprResult SubResult = Visit(E->getSubExpr());
  9895. if (SubResult.isInvalid()) return ExprError();
  9896. Expr *SubExpr = SubResult.take();
  9897. E->setSubExpr(SubExpr);
  9898. E->setType(S.Context.getPointerType(SubExpr->getType()));
  9899. assert(E->getValueKind() == VK_RValue);
  9900. assert(E->getObjectKind() == OK_Ordinary);
  9901. return E;
  9902. }
  9903. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  9904. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  9905. E->setType(VD->getType());
  9906. assert(E->getValueKind() == VK_RValue);
  9907. if (S.getLangOpts().CPlusPlus &&
  9908. !(isa<CXXMethodDecl>(VD) &&
  9909. cast<CXXMethodDecl>(VD)->isInstance()))
  9910. E->setValueKind(VK_LValue);
  9911. return E;
  9912. }
  9913. ExprResult VisitMemberExpr(MemberExpr *E) {
  9914. return resolveDecl(E, E->getMemberDecl());
  9915. }
  9916. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  9917. return resolveDecl(E, E->getDecl());
  9918. }
  9919. };
  9920. }
  9921. /// Given a function expression of unknown-any type, try to rebuild it
  9922. /// to have a function type.
  9923. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  9924. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  9925. if (Result.isInvalid()) return ExprError();
  9926. return S.DefaultFunctionArrayConversion(Result.take());
  9927. }
  9928. namespace {
  9929. /// A visitor for rebuilding an expression of type __unknown_anytype
  9930. /// into one which resolves the type directly on the referring
  9931. /// expression. Strict preservation of the original source
  9932. /// structure is not a goal.
  9933. struct RebuildUnknownAnyExpr
  9934. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  9935. Sema &S;
  9936. /// The current destination type.
  9937. QualType DestType;
  9938. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  9939. : S(S), DestType(CastType) {}
  9940. ExprResult VisitStmt(Stmt *S) {
  9941. llvm_unreachable("unexpected statement!");
  9942. }
  9943. ExprResult VisitExpr(Expr *E) {
  9944. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  9945. << E->getSourceRange();
  9946. return ExprError();
  9947. }
  9948. ExprResult VisitCallExpr(CallExpr *E);
  9949. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  9950. /// Rebuild an expression which simply semantically wraps another
  9951. /// expression which it shares the type and value kind of.
  9952. template <class T> ExprResult rebuildSugarExpr(T *E) {
  9953. ExprResult SubResult = Visit(E->getSubExpr());
  9954. if (SubResult.isInvalid()) return ExprError();
  9955. Expr *SubExpr = SubResult.take();
  9956. E->setSubExpr(SubExpr);
  9957. E->setType(SubExpr->getType());
  9958. E->setValueKind(SubExpr->getValueKind());
  9959. assert(E->getObjectKind() == OK_Ordinary);
  9960. return E;
  9961. }
  9962. ExprResult VisitParenExpr(ParenExpr *E) {
  9963. return rebuildSugarExpr(E);
  9964. }
  9965. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  9966. return rebuildSugarExpr(E);
  9967. }
  9968. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  9969. const PointerType *Ptr = DestType->getAs<PointerType>();
  9970. if (!Ptr) {
  9971. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  9972. << E->getSourceRange();
  9973. return ExprError();
  9974. }
  9975. assert(E->getValueKind() == VK_RValue);
  9976. assert(E->getObjectKind() == OK_Ordinary);
  9977. E->setType(DestType);
  9978. // Build the sub-expression as if it were an object of the pointee type.
  9979. DestType = Ptr->getPointeeType();
  9980. ExprResult SubResult = Visit(E->getSubExpr());
  9981. if (SubResult.isInvalid()) return ExprError();
  9982. E->setSubExpr(SubResult.take());
  9983. return E;
  9984. }
  9985. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  9986. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  9987. ExprResult VisitMemberExpr(MemberExpr *E) {
  9988. return resolveDecl(E, E->getMemberDecl());
  9989. }
  9990. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  9991. return resolveDecl(E, E->getDecl());
  9992. }
  9993. };
  9994. }
  9995. /// Rebuilds a call expression which yielded __unknown_anytype.
  9996. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  9997. Expr *CalleeExpr = E->getCallee();
  9998. enum FnKind {
  9999. FK_MemberFunction,
  10000. FK_FunctionPointer,
  10001. FK_BlockPointer
  10002. };
  10003. FnKind Kind;
  10004. QualType CalleeType = CalleeExpr->getType();
  10005. if (CalleeType == S.Context.BoundMemberTy) {
  10006. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  10007. Kind = FK_MemberFunction;
  10008. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  10009. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  10010. CalleeType = Ptr->getPointeeType();
  10011. Kind = FK_FunctionPointer;
  10012. } else {
  10013. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  10014. Kind = FK_BlockPointer;
  10015. }
  10016. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  10017. // Verify that this is a legal result type of a function.
  10018. if (DestType->isArrayType() || DestType->isFunctionType()) {
  10019. unsigned diagID = diag::err_func_returning_array_function;
  10020. if (Kind == FK_BlockPointer)
  10021. diagID = diag::err_block_returning_array_function;
  10022. S.Diag(E->getExprLoc(), diagID)
  10023. << DestType->isFunctionType() << DestType;
  10024. return ExprError();
  10025. }
  10026. // Otherwise, go ahead and set DestType as the call's result.
  10027. E->setType(DestType.getNonLValueExprType(S.Context));
  10028. E->setValueKind(Expr::getValueKindForType(DestType));
  10029. assert(E->getObjectKind() == OK_Ordinary);
  10030. // Rebuild the function type, replacing the result type with DestType.
  10031. if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
  10032. DestType = S.Context.getFunctionType(DestType,
  10033. Proto->arg_type_begin(),
  10034. Proto->getNumArgs(),
  10035. Proto->getExtProtoInfo());
  10036. else
  10037. DestType = S.Context.getFunctionNoProtoType(DestType,
  10038. FnType->getExtInfo());
  10039. // Rebuild the appropriate pointer-to-function type.
  10040. switch (Kind) {
  10041. case FK_MemberFunction:
  10042. // Nothing to do.
  10043. break;
  10044. case FK_FunctionPointer:
  10045. DestType = S.Context.getPointerType(DestType);
  10046. break;
  10047. case FK_BlockPointer:
  10048. DestType = S.Context.getBlockPointerType(DestType);
  10049. break;
  10050. }
  10051. // Finally, we can recurse.
  10052. ExprResult CalleeResult = Visit(CalleeExpr);
  10053. if (!CalleeResult.isUsable()) return ExprError();
  10054. E->setCallee(CalleeResult.take());
  10055. // Bind a temporary if necessary.
  10056. return S.MaybeBindToTemporary(E);
  10057. }
  10058. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  10059. // Verify that this is a legal result type of a call.
  10060. if (DestType->isArrayType() || DestType->isFunctionType()) {
  10061. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  10062. << DestType->isFunctionType() << DestType;
  10063. return ExprError();
  10064. }
  10065. // Rewrite the method result type if available.
  10066. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  10067. assert(Method->getResultType() == S.Context.UnknownAnyTy);
  10068. Method->setResultType(DestType);
  10069. }
  10070. // Change the type of the message.
  10071. E->setType(DestType.getNonReferenceType());
  10072. E->setValueKind(Expr::getValueKindForType(DestType));
  10073. return S.MaybeBindToTemporary(E);
  10074. }
  10075. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  10076. // The only case we should ever see here is a function-to-pointer decay.
  10077. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  10078. assert(E->getValueKind() == VK_RValue);
  10079. assert(E->getObjectKind() == OK_Ordinary);
  10080. E->setType(DestType);
  10081. // Rebuild the sub-expression as the pointee (function) type.
  10082. DestType = DestType->castAs<PointerType>()->getPointeeType();
  10083. ExprResult Result = Visit(E->getSubExpr());
  10084. if (!Result.isUsable()) return ExprError();
  10085. E->setSubExpr(Result.take());
  10086. return S.Owned(E);
  10087. } else if (E->getCastKind() == CK_LValueToRValue) {
  10088. assert(E->getValueKind() == VK_RValue);
  10089. assert(E->getObjectKind() == OK_Ordinary);
  10090. assert(isa<BlockPointerType>(E->getType()));
  10091. E->setType(DestType);
  10092. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  10093. DestType = S.Context.getLValueReferenceType(DestType);
  10094. ExprResult Result = Visit(E->getSubExpr());
  10095. if (!Result.isUsable()) return ExprError();
  10096. E->setSubExpr(Result.take());
  10097. return S.Owned(E);
  10098. } else {
  10099. llvm_unreachable("Unhandled cast type!");
  10100. }
  10101. }
  10102. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  10103. ExprValueKind ValueKind = VK_LValue;
  10104. QualType Type = DestType;
  10105. // We know how to make this work for certain kinds of decls:
  10106. // - functions
  10107. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  10108. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  10109. DestType = Ptr->getPointeeType();
  10110. ExprResult Result = resolveDecl(E, VD);
  10111. if (Result.isInvalid()) return ExprError();
  10112. return S.ImpCastExprToType(Result.take(), Type,
  10113. CK_FunctionToPointerDecay, VK_RValue);
  10114. }
  10115. if (!Type->isFunctionType()) {
  10116. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  10117. << VD << E->getSourceRange();
  10118. return ExprError();
  10119. }
  10120. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  10121. if (MD->isInstance()) {
  10122. ValueKind = VK_RValue;
  10123. Type = S.Context.BoundMemberTy;
  10124. }
  10125. // Function references aren't l-values in C.
  10126. if (!S.getLangOpts().CPlusPlus)
  10127. ValueKind = VK_RValue;
  10128. // - variables
  10129. } else if (isa<VarDecl>(VD)) {
  10130. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  10131. Type = RefTy->getPointeeType();
  10132. } else if (Type->isFunctionType()) {
  10133. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  10134. << VD << E->getSourceRange();
  10135. return ExprError();
  10136. }
  10137. // - nothing else
  10138. } else {
  10139. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  10140. << VD << E->getSourceRange();
  10141. return ExprError();
  10142. }
  10143. VD->setType(DestType);
  10144. E->setType(Type);
  10145. E->setValueKind(ValueKind);
  10146. return S.Owned(E);
  10147. }
  10148. /// Check a cast of an unknown-any type. We intentionally only
  10149. /// trigger this for C-style casts.
  10150. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  10151. Expr *CastExpr, CastKind &CastKind,
  10152. ExprValueKind &VK, CXXCastPath &Path) {
  10153. // Rewrite the casted expression from scratch.
  10154. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  10155. if (!result.isUsable()) return ExprError();
  10156. CastExpr = result.take();
  10157. VK = CastExpr->getValueKind();
  10158. CastKind = CK_NoOp;
  10159. return CastExpr;
  10160. }
  10161. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  10162. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  10163. }
  10164. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  10165. Expr *orig = E;
  10166. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  10167. while (true) {
  10168. E = E->IgnoreParenImpCasts();
  10169. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  10170. E = call->getCallee();
  10171. diagID = diag::err_uncasted_call_of_unknown_any;
  10172. } else {
  10173. break;
  10174. }
  10175. }
  10176. SourceLocation loc;
  10177. NamedDecl *d;
  10178. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  10179. loc = ref->getLocation();
  10180. d = ref->getDecl();
  10181. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  10182. loc = mem->getMemberLoc();
  10183. d = mem->getMemberDecl();
  10184. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  10185. diagID = diag::err_uncasted_call_of_unknown_any;
  10186. loc = msg->getSelectorStartLoc();
  10187. d = msg->getMethodDecl();
  10188. if (!d) {
  10189. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  10190. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  10191. << orig->getSourceRange();
  10192. return ExprError();
  10193. }
  10194. } else {
  10195. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  10196. << E->getSourceRange();
  10197. return ExprError();
  10198. }
  10199. S.Diag(loc, diagID) << d << orig->getSourceRange();
  10200. // Never recoverable.
  10201. return ExprError();
  10202. }
  10203. /// Check for operands with placeholder types and complain if found.
  10204. /// Returns true if there was an error and no recovery was possible.
  10205. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  10206. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  10207. if (!placeholderType) return Owned(E);
  10208. switch (placeholderType->getKind()) {
  10209. // Overloaded expressions.
  10210. case BuiltinType::Overload: {
  10211. // Try to resolve a single function template specialization.
  10212. // This is obligatory.
  10213. ExprResult result = Owned(E);
  10214. if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
  10215. return result;
  10216. // If that failed, try to recover with a call.
  10217. } else {
  10218. tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
  10219. /*complain*/ true);
  10220. return result;
  10221. }
  10222. }
  10223. // Bound member functions.
  10224. case BuiltinType::BoundMember: {
  10225. ExprResult result = Owned(E);
  10226. tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
  10227. /*complain*/ true);
  10228. return result;
  10229. }
  10230. // ARC unbridged casts.
  10231. case BuiltinType::ARCUnbridgedCast: {
  10232. Expr *realCast = stripARCUnbridgedCast(E);
  10233. diagnoseARCUnbridgedCast(realCast);
  10234. return Owned(realCast);
  10235. }
  10236. // Expressions of unknown type.
  10237. case BuiltinType::UnknownAny:
  10238. return diagnoseUnknownAnyExpr(*this, E);
  10239. // Pseudo-objects.
  10240. case BuiltinType::PseudoObject:
  10241. return checkPseudoObjectRValue(E);
  10242. // Everything else should be impossible.
  10243. #define BUILTIN_TYPE(Id, SingletonId) \
  10244. case BuiltinType::Id:
  10245. #define PLACEHOLDER_TYPE(Id, SingletonId)
  10246. #include "clang/AST/BuiltinTypes.def"
  10247. break;
  10248. }
  10249. llvm_unreachable("invalid placeholder type!");
  10250. }
  10251. bool Sema::CheckCaseExpression(Expr *E) {
  10252. if (E->isTypeDependent())
  10253. return true;
  10254. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  10255. return E->getType()->isIntegralOrEnumerationType();
  10256. return false;
  10257. }
  10258. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  10259. ExprResult
  10260. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  10261. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  10262. "Unknown Objective-C Boolean value!");
  10263. return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
  10264. Context.ObjCBuiltinBoolTy, OpLoc));
  10265. }