SemaChecking.cpp 291 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049
  1. //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
  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 extra semantic analysis beyond what is enforced
  11. // by the C type system.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Sema/SemaInternal.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/CharUnits.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/EvaluatedExprVisitor.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/ExprObjC.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/AST/StmtObjC.h"
  25. #include "clang/Analysis/Analyses/FormatString.h"
  26. #include "clang/Basic/CharInfo.h"
  27. #include "clang/Basic/TargetBuiltins.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  30. #include "clang/Sema/Initialization.h"
  31. #include "clang/Sema/Lookup.h"
  32. #include "clang/Sema/ScopeInfo.h"
  33. #include "clang/Sema/Sema.h"
  34. #include "llvm/ADT/STLExtras.h"
  35. #include "llvm/ADT/SmallBitVector.h"
  36. #include "llvm/ADT/SmallString.h"
  37. #include "llvm/Support/ConvertUTF.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include <limits>
  40. using namespace clang;
  41. using namespace sema;
  42. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  43. unsigned ByteNo) const {
  44. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  45. Context.getTargetInfo());
  46. }
  47. /// Checks that a call expression's argument count is the desired number.
  48. /// This is useful when doing custom type-checking. Returns true on error.
  49. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  50. unsigned argCount = call->getNumArgs();
  51. if (argCount == desiredArgCount) return false;
  52. if (argCount < desiredArgCount)
  53. return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
  54. << 0 /*function call*/ << desiredArgCount << argCount
  55. << call->getSourceRange();
  56. // Highlight all the excess arguments.
  57. SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
  58. call->getArg(argCount - 1)->getLocEnd());
  59. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  60. << 0 /*function call*/ << desiredArgCount << argCount
  61. << call->getArg(1)->getSourceRange();
  62. }
  63. /// Check that the first argument to __builtin_annotation is an integer
  64. /// and the second argument is a non-wide string literal.
  65. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  66. if (checkArgCount(S, TheCall, 2))
  67. return true;
  68. // First argument should be an integer.
  69. Expr *ValArg = TheCall->getArg(0);
  70. QualType Ty = ValArg->getType();
  71. if (!Ty->isIntegerType()) {
  72. S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
  73. << ValArg->getSourceRange();
  74. return true;
  75. }
  76. // Second argument should be a constant string.
  77. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  78. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  79. if (!Literal || !Literal->isAscii()) {
  80. S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
  81. << StrArg->getSourceRange();
  82. return true;
  83. }
  84. TheCall->setType(Ty);
  85. return false;
  86. }
  87. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  88. /// result type to the corresponding pointer type.
  89. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  90. if (checkArgCount(S, TheCall, 1))
  91. return true;
  92. ExprResult Arg(S.Owned(TheCall->getArg(0)));
  93. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
  94. if (ResultType.isNull())
  95. return true;
  96. TheCall->setArg(0, Arg.take());
  97. TheCall->setType(ResultType);
  98. return false;
  99. }
  100. ExprResult
  101. Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  102. ExprResult TheCallResult(Owned(TheCall));
  103. // Find out if any arguments are required to be integer constant expressions.
  104. unsigned ICEArguments = 0;
  105. ASTContext::GetBuiltinTypeError Error;
  106. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  107. if (Error != ASTContext::GE_None)
  108. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  109. // If any arguments are required to be ICE's, check and diagnose.
  110. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  111. // Skip arguments not required to be ICE's.
  112. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  113. llvm::APSInt Result;
  114. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  115. return true;
  116. ICEArguments &= ~(1 << ArgNo);
  117. }
  118. switch (BuiltinID) {
  119. case Builtin::BI__builtin___CFStringMakeConstantString:
  120. assert(TheCall->getNumArgs() == 1 &&
  121. "Wrong # arguments to builtin CFStringMakeConstantString");
  122. if (CheckObjCString(TheCall->getArg(0)))
  123. return ExprError();
  124. break;
  125. case Builtin::BI__builtin_stdarg_start:
  126. case Builtin::BI__builtin_va_start:
  127. case Builtin::BI__va_start:
  128. if (SemaBuiltinVAStart(TheCall))
  129. return ExprError();
  130. break;
  131. case Builtin::BI__builtin_isgreater:
  132. case Builtin::BI__builtin_isgreaterequal:
  133. case Builtin::BI__builtin_isless:
  134. case Builtin::BI__builtin_islessequal:
  135. case Builtin::BI__builtin_islessgreater:
  136. case Builtin::BI__builtin_isunordered:
  137. if (SemaBuiltinUnorderedCompare(TheCall))
  138. return ExprError();
  139. break;
  140. case Builtin::BI__builtin_fpclassify:
  141. if (SemaBuiltinFPClassification(TheCall, 6))
  142. return ExprError();
  143. break;
  144. case Builtin::BI__builtin_isfinite:
  145. case Builtin::BI__builtin_isinf:
  146. case Builtin::BI__builtin_isinf_sign:
  147. case Builtin::BI__builtin_isnan:
  148. case Builtin::BI__builtin_isnormal:
  149. if (SemaBuiltinFPClassification(TheCall, 1))
  150. return ExprError();
  151. break;
  152. case Builtin::BI__builtin_shufflevector:
  153. return SemaBuiltinShuffleVector(TheCall);
  154. // TheCall will be freed by the smart pointer here, but that's fine, since
  155. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  156. case Builtin::BI__builtin_prefetch:
  157. if (SemaBuiltinPrefetch(TheCall))
  158. return ExprError();
  159. break;
  160. case Builtin::BI__builtin_object_size:
  161. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  162. return ExprError();
  163. break;
  164. case Builtin::BI__builtin_longjmp:
  165. if (SemaBuiltinLongjmp(TheCall))
  166. return ExprError();
  167. break;
  168. case Builtin::BI__builtin_classify_type:
  169. if (checkArgCount(*this, TheCall, 1)) return true;
  170. TheCall->setType(Context.IntTy);
  171. break;
  172. case Builtin::BI__builtin_constant_p:
  173. if (checkArgCount(*this, TheCall, 1)) return true;
  174. TheCall->setType(Context.IntTy);
  175. break;
  176. case Builtin::BI__sync_fetch_and_add:
  177. case Builtin::BI__sync_fetch_and_add_1:
  178. case Builtin::BI__sync_fetch_and_add_2:
  179. case Builtin::BI__sync_fetch_and_add_4:
  180. case Builtin::BI__sync_fetch_and_add_8:
  181. case Builtin::BI__sync_fetch_and_add_16:
  182. case Builtin::BI__sync_fetch_and_sub:
  183. case Builtin::BI__sync_fetch_and_sub_1:
  184. case Builtin::BI__sync_fetch_and_sub_2:
  185. case Builtin::BI__sync_fetch_and_sub_4:
  186. case Builtin::BI__sync_fetch_and_sub_8:
  187. case Builtin::BI__sync_fetch_and_sub_16:
  188. case Builtin::BI__sync_fetch_and_or:
  189. case Builtin::BI__sync_fetch_and_or_1:
  190. case Builtin::BI__sync_fetch_and_or_2:
  191. case Builtin::BI__sync_fetch_and_or_4:
  192. case Builtin::BI__sync_fetch_and_or_8:
  193. case Builtin::BI__sync_fetch_and_or_16:
  194. case Builtin::BI__sync_fetch_and_and:
  195. case Builtin::BI__sync_fetch_and_and_1:
  196. case Builtin::BI__sync_fetch_and_and_2:
  197. case Builtin::BI__sync_fetch_and_and_4:
  198. case Builtin::BI__sync_fetch_and_and_8:
  199. case Builtin::BI__sync_fetch_and_and_16:
  200. case Builtin::BI__sync_fetch_and_xor:
  201. case Builtin::BI__sync_fetch_and_xor_1:
  202. case Builtin::BI__sync_fetch_and_xor_2:
  203. case Builtin::BI__sync_fetch_and_xor_4:
  204. case Builtin::BI__sync_fetch_and_xor_8:
  205. case Builtin::BI__sync_fetch_and_xor_16:
  206. case Builtin::BI__sync_add_and_fetch:
  207. case Builtin::BI__sync_add_and_fetch_1:
  208. case Builtin::BI__sync_add_and_fetch_2:
  209. case Builtin::BI__sync_add_and_fetch_4:
  210. case Builtin::BI__sync_add_and_fetch_8:
  211. case Builtin::BI__sync_add_and_fetch_16:
  212. case Builtin::BI__sync_sub_and_fetch:
  213. case Builtin::BI__sync_sub_and_fetch_1:
  214. case Builtin::BI__sync_sub_and_fetch_2:
  215. case Builtin::BI__sync_sub_and_fetch_4:
  216. case Builtin::BI__sync_sub_and_fetch_8:
  217. case Builtin::BI__sync_sub_and_fetch_16:
  218. case Builtin::BI__sync_and_and_fetch:
  219. case Builtin::BI__sync_and_and_fetch_1:
  220. case Builtin::BI__sync_and_and_fetch_2:
  221. case Builtin::BI__sync_and_and_fetch_4:
  222. case Builtin::BI__sync_and_and_fetch_8:
  223. case Builtin::BI__sync_and_and_fetch_16:
  224. case Builtin::BI__sync_or_and_fetch:
  225. case Builtin::BI__sync_or_and_fetch_1:
  226. case Builtin::BI__sync_or_and_fetch_2:
  227. case Builtin::BI__sync_or_and_fetch_4:
  228. case Builtin::BI__sync_or_and_fetch_8:
  229. case Builtin::BI__sync_or_and_fetch_16:
  230. case Builtin::BI__sync_xor_and_fetch:
  231. case Builtin::BI__sync_xor_and_fetch_1:
  232. case Builtin::BI__sync_xor_and_fetch_2:
  233. case Builtin::BI__sync_xor_and_fetch_4:
  234. case Builtin::BI__sync_xor_and_fetch_8:
  235. case Builtin::BI__sync_xor_and_fetch_16:
  236. case Builtin::BI__sync_val_compare_and_swap:
  237. case Builtin::BI__sync_val_compare_and_swap_1:
  238. case Builtin::BI__sync_val_compare_and_swap_2:
  239. case Builtin::BI__sync_val_compare_and_swap_4:
  240. case Builtin::BI__sync_val_compare_and_swap_8:
  241. case Builtin::BI__sync_val_compare_and_swap_16:
  242. case Builtin::BI__sync_bool_compare_and_swap:
  243. case Builtin::BI__sync_bool_compare_and_swap_1:
  244. case Builtin::BI__sync_bool_compare_and_swap_2:
  245. case Builtin::BI__sync_bool_compare_and_swap_4:
  246. case Builtin::BI__sync_bool_compare_and_swap_8:
  247. case Builtin::BI__sync_bool_compare_and_swap_16:
  248. case Builtin::BI__sync_lock_test_and_set:
  249. case Builtin::BI__sync_lock_test_and_set_1:
  250. case Builtin::BI__sync_lock_test_and_set_2:
  251. case Builtin::BI__sync_lock_test_and_set_4:
  252. case Builtin::BI__sync_lock_test_and_set_8:
  253. case Builtin::BI__sync_lock_test_and_set_16:
  254. case Builtin::BI__sync_lock_release:
  255. case Builtin::BI__sync_lock_release_1:
  256. case Builtin::BI__sync_lock_release_2:
  257. case Builtin::BI__sync_lock_release_4:
  258. case Builtin::BI__sync_lock_release_8:
  259. case Builtin::BI__sync_lock_release_16:
  260. case Builtin::BI__sync_swap:
  261. case Builtin::BI__sync_swap_1:
  262. case Builtin::BI__sync_swap_2:
  263. case Builtin::BI__sync_swap_4:
  264. case Builtin::BI__sync_swap_8:
  265. case Builtin::BI__sync_swap_16:
  266. return SemaBuiltinAtomicOverloaded(TheCallResult);
  267. #define BUILTIN(ID, TYPE, ATTRS)
  268. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  269. case Builtin::BI##ID: \
  270. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  271. #include "clang/Basic/Builtins.def"
  272. case Builtin::BI__builtin_annotation:
  273. if (SemaBuiltinAnnotation(*this, TheCall))
  274. return ExprError();
  275. break;
  276. case Builtin::BI__builtin_addressof:
  277. if (SemaBuiltinAddressof(*this, TheCall))
  278. return ExprError();
  279. break;
  280. }
  281. // Since the target specific builtins for each arch overlap, only check those
  282. // of the arch we are compiling for.
  283. if (BuiltinID >= Builtin::FirstTSBuiltin) {
  284. switch (Context.getTargetInfo().getTriple().getArch()) {
  285. case llvm::Triple::arm:
  286. case llvm::Triple::armeb:
  287. case llvm::Triple::thumb:
  288. case llvm::Triple::thumbeb:
  289. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  290. return ExprError();
  291. break;
  292. case llvm::Triple::aarch64:
  293. case llvm::Triple::aarch64_be:
  294. case llvm::Triple::arm64:
  295. case llvm::Triple::arm64_be:
  296. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  297. return ExprError();
  298. break;
  299. case llvm::Triple::mips:
  300. case llvm::Triple::mipsel:
  301. case llvm::Triple::mips64:
  302. case llvm::Triple::mips64el:
  303. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  304. return ExprError();
  305. break;
  306. case llvm::Triple::x86:
  307. case llvm::Triple::x86_64:
  308. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  309. return ExprError();
  310. break;
  311. default:
  312. break;
  313. }
  314. }
  315. return TheCallResult;
  316. }
  317. // Get the valid immediate range for the specified NEON type code.
  318. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  319. NeonTypeFlags Type(t);
  320. int IsQuad = ForceQuad ? true : Type.isQuad();
  321. switch (Type.getEltType()) {
  322. case NeonTypeFlags::Int8:
  323. case NeonTypeFlags::Poly8:
  324. return shift ? 7 : (8 << IsQuad) - 1;
  325. case NeonTypeFlags::Int16:
  326. case NeonTypeFlags::Poly16:
  327. return shift ? 15 : (4 << IsQuad) - 1;
  328. case NeonTypeFlags::Int32:
  329. return shift ? 31 : (2 << IsQuad) - 1;
  330. case NeonTypeFlags::Int64:
  331. case NeonTypeFlags::Poly64:
  332. return shift ? 63 : (1 << IsQuad) - 1;
  333. case NeonTypeFlags::Poly128:
  334. return shift ? 127 : (1 << IsQuad) - 1;
  335. case NeonTypeFlags::Float16:
  336. assert(!shift && "cannot shift float types!");
  337. return (4 << IsQuad) - 1;
  338. case NeonTypeFlags::Float32:
  339. assert(!shift && "cannot shift float types!");
  340. return (2 << IsQuad) - 1;
  341. case NeonTypeFlags::Float64:
  342. assert(!shift && "cannot shift float types!");
  343. return (1 << IsQuad) - 1;
  344. }
  345. llvm_unreachable("Invalid NeonTypeFlag!");
  346. }
  347. /// getNeonEltType - Return the QualType corresponding to the elements of
  348. /// the vector type specified by the NeonTypeFlags. This is used to check
  349. /// the pointer arguments for Neon load/store intrinsics.
  350. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  351. bool IsPolyUnsigned, bool IsInt64Long) {
  352. switch (Flags.getEltType()) {
  353. case NeonTypeFlags::Int8:
  354. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  355. case NeonTypeFlags::Int16:
  356. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  357. case NeonTypeFlags::Int32:
  358. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  359. case NeonTypeFlags::Int64:
  360. if (IsInt64Long)
  361. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  362. else
  363. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  364. : Context.LongLongTy;
  365. case NeonTypeFlags::Poly8:
  366. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  367. case NeonTypeFlags::Poly16:
  368. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  369. case NeonTypeFlags::Poly64:
  370. return Context.UnsignedLongTy;
  371. case NeonTypeFlags::Poly128:
  372. break;
  373. case NeonTypeFlags::Float16:
  374. return Context.HalfTy;
  375. case NeonTypeFlags::Float32:
  376. return Context.FloatTy;
  377. case NeonTypeFlags::Float64:
  378. return Context.DoubleTy;
  379. }
  380. llvm_unreachable("Invalid NeonTypeFlag!");
  381. }
  382. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  383. llvm::APSInt Result;
  384. uint64_t mask = 0;
  385. unsigned TV = 0;
  386. int PtrArgNum = -1;
  387. bool HasConstPtr = false;
  388. switch (BuiltinID) {
  389. #define GET_NEON_OVERLOAD_CHECK
  390. #include "clang/Basic/arm_neon.inc"
  391. #undef GET_NEON_OVERLOAD_CHECK
  392. }
  393. // For NEON intrinsics which are overloaded on vector element type, validate
  394. // the immediate which specifies which variant to emit.
  395. unsigned ImmArg = TheCall->getNumArgs()-1;
  396. if (mask) {
  397. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  398. return true;
  399. TV = Result.getLimitedValue(64);
  400. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  401. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  402. << TheCall->getArg(ImmArg)->getSourceRange();
  403. }
  404. if (PtrArgNum >= 0) {
  405. // Check that pointer arguments have the specified type.
  406. Expr *Arg = TheCall->getArg(PtrArgNum);
  407. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  408. Arg = ICE->getSubExpr();
  409. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  410. QualType RHSTy = RHS.get()->getType();
  411. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  412. bool IsPolyUnsigned =
  413. Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::arm64;
  414. bool IsInt64Long =
  415. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  416. QualType EltTy =
  417. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  418. if (HasConstPtr)
  419. EltTy = EltTy.withConst();
  420. QualType LHSTy = Context.getPointerType(EltTy);
  421. AssignConvertType ConvTy;
  422. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  423. if (RHS.isInvalid())
  424. return true;
  425. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  426. RHS.get(), AA_Assigning))
  427. return true;
  428. }
  429. // For NEON intrinsics which take an immediate value as part of the
  430. // instruction, range check them here.
  431. unsigned i = 0, l = 0, u = 0;
  432. switch (BuiltinID) {
  433. default:
  434. return false;
  435. #define GET_NEON_IMMEDIATE_CHECK
  436. #include "clang/Basic/arm_neon.inc"
  437. #undef GET_NEON_IMMEDIATE_CHECK
  438. }
  439. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  440. }
  441. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  442. unsigned MaxWidth) {
  443. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  444. BuiltinID == ARM::BI__builtin_arm_strex ||
  445. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  446. BuiltinID == AArch64::BI__builtin_arm_strex) &&
  447. "unexpected ARM builtin");
  448. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  449. BuiltinID == AArch64::BI__builtin_arm_ldrex;
  450. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  451. // Ensure that we have the proper number of arguments.
  452. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  453. return true;
  454. // Inspect the pointer argument of the atomic builtin. This should always be
  455. // a pointer type, whose element is an integral scalar or pointer type.
  456. // Because it is a pointer type, we don't have to worry about any implicit
  457. // casts here.
  458. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  459. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  460. if (PointerArgRes.isInvalid())
  461. return true;
  462. PointerArg = PointerArgRes.take();
  463. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  464. if (!pointerType) {
  465. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  466. << PointerArg->getType() << PointerArg->getSourceRange();
  467. return true;
  468. }
  469. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  470. // task is to insert the appropriate casts into the AST. First work out just
  471. // what the appropriate type is.
  472. QualType ValType = pointerType->getPointeeType();
  473. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  474. if (IsLdrex)
  475. AddrType.addConst();
  476. // Issue a warning if the cast is dodgy.
  477. CastKind CastNeeded = CK_NoOp;
  478. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  479. CastNeeded = CK_BitCast;
  480. Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
  481. << PointerArg->getType()
  482. << Context.getPointerType(AddrType)
  483. << AA_Passing << PointerArg->getSourceRange();
  484. }
  485. // Finally, do the cast and replace the argument with the corrected version.
  486. AddrType = Context.getPointerType(AddrType);
  487. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  488. if (PointerArgRes.isInvalid())
  489. return true;
  490. PointerArg = PointerArgRes.take();
  491. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  492. // In general, we allow ints, floats and pointers to be loaded and stored.
  493. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  494. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  495. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  496. << PointerArg->getType() << PointerArg->getSourceRange();
  497. return true;
  498. }
  499. // But ARM doesn't have instructions to deal with 128-bit versions.
  500. if (Context.getTypeSize(ValType) > MaxWidth) {
  501. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  502. Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
  503. << PointerArg->getType() << PointerArg->getSourceRange();
  504. return true;
  505. }
  506. switch (ValType.getObjCLifetime()) {
  507. case Qualifiers::OCL_None:
  508. case Qualifiers::OCL_ExplicitNone:
  509. // okay
  510. break;
  511. case Qualifiers::OCL_Weak:
  512. case Qualifiers::OCL_Strong:
  513. case Qualifiers::OCL_Autoreleasing:
  514. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  515. << ValType << PointerArg->getSourceRange();
  516. return true;
  517. }
  518. if (IsLdrex) {
  519. TheCall->setType(ValType);
  520. return false;
  521. }
  522. // Initialize the argument to be stored.
  523. ExprResult ValArg = TheCall->getArg(0);
  524. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  525. Context, ValType, /*consume*/ false);
  526. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  527. if (ValArg.isInvalid())
  528. return true;
  529. TheCall->setArg(0, ValArg.get());
  530. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  531. // but the custom checker bypasses all default analysis.
  532. TheCall->setType(Context.IntTy);
  533. return false;
  534. }
  535. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  536. llvm::APSInt Result;
  537. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  538. BuiltinID == ARM::BI__builtin_arm_strex) {
  539. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  540. }
  541. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  542. return true;
  543. // For NEON intrinsics which take an immediate value as part of the
  544. // instruction, range check them here.
  545. unsigned i = 0, l = 0, u = 0;
  546. switch (BuiltinID) {
  547. default: return false;
  548. case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
  549. case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
  550. case ARM::BI__builtin_arm_vcvtr_f:
  551. case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
  552. case ARM::BI__builtin_arm_dmb:
  553. case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
  554. }
  555. // FIXME: VFP Intrinsics should error if VFP not present.
  556. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  557. }
  558. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  559. CallExpr *TheCall) {
  560. llvm::APSInt Result;
  561. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  562. BuiltinID == AArch64::BI__builtin_arm_strex) {
  563. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  564. }
  565. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  566. return true;
  567. return false;
  568. }
  569. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  570. unsigned i = 0, l = 0, u = 0;
  571. switch (BuiltinID) {
  572. default: return false;
  573. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  574. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  575. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  576. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  577. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  578. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  579. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  580. }
  581. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  582. }
  583. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  584. switch (BuiltinID) {
  585. case X86::BI_mm_prefetch:
  586. // This is declared to take (const char*, int)
  587. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
  588. }
  589. return false;
  590. }
  591. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  592. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  593. /// Returns true when the format fits the function and the FormatStringInfo has
  594. /// been populated.
  595. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  596. FormatStringInfo *FSI) {
  597. FSI->HasVAListArg = Format->getFirstArg() == 0;
  598. FSI->FormatIdx = Format->getFormatIdx() - 1;
  599. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  600. // The way the format attribute works in GCC, the implicit this argument
  601. // of member functions is counted. However, it doesn't appear in our own
  602. // lists, so decrement format_idx in that case.
  603. if (IsCXXMember) {
  604. if(FSI->FormatIdx == 0)
  605. return false;
  606. --FSI->FormatIdx;
  607. if (FSI->FirstDataArg != 0)
  608. --FSI->FirstDataArg;
  609. }
  610. return true;
  611. }
  612. /// Checks if a the given expression evaluates to null.
  613. ///
  614. /// \brief Returns true if the value evaluates to null.
  615. static bool CheckNonNullExpr(Sema &S,
  616. const Expr *Expr) {
  617. // As a special case, transparent unions initialized with zero are
  618. // considered null for the purposes of the nonnull attribute.
  619. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  620. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  621. if (const CompoundLiteralExpr *CLE =
  622. dyn_cast<CompoundLiteralExpr>(Expr))
  623. if (const InitListExpr *ILE =
  624. dyn_cast<InitListExpr>(CLE->getInitializer()))
  625. Expr = ILE->getInit(0);
  626. }
  627. bool Result;
  628. return (!Expr->isValueDependent() &&
  629. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  630. !Result);
  631. }
  632. static void CheckNonNullArgument(Sema &S,
  633. const Expr *ArgExpr,
  634. SourceLocation CallSiteLoc) {
  635. if (CheckNonNullExpr(S, ArgExpr))
  636. S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  637. }
  638. static void CheckNonNullArguments(Sema &S,
  639. const NamedDecl *FDecl,
  640. const Expr * const *ExprArgs,
  641. SourceLocation CallSiteLoc) {
  642. // Check the attributes attached to the method/function itself.
  643. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  644. for (const auto &Val : NonNull->args())
  645. CheckNonNullArgument(S, ExprArgs[Val], CallSiteLoc);
  646. }
  647. // Check the attributes on the parameters.
  648. ArrayRef<ParmVarDecl*> parms;
  649. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  650. parms = FD->parameters();
  651. else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
  652. parms = MD->parameters();
  653. unsigned argIndex = 0;
  654. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  655. I != E; ++I, ++argIndex) {
  656. const ParmVarDecl *PVD = *I;
  657. if (PVD->hasAttr<NonNullAttr>())
  658. CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
  659. }
  660. }
  661. /// Handles the checks for format strings, non-POD arguments to vararg
  662. /// functions, and NULL arguments passed to non-NULL parameters.
  663. void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
  664. unsigned NumParams, bool IsMemberFunction,
  665. SourceLocation Loc, SourceRange Range,
  666. VariadicCallType CallType) {
  667. // FIXME: We should check as much as we can in the template definition.
  668. if (CurContext->isDependentContext())
  669. return;
  670. // Printf and scanf checking.
  671. llvm::SmallBitVector CheckedVarArgs;
  672. if (FDecl) {
  673. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  674. // Only create vector if there are format attributes.
  675. CheckedVarArgs.resize(Args.size());
  676. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  677. CheckedVarArgs);
  678. }
  679. }
  680. // Refuse POD arguments that weren't caught by the format string
  681. // checks above.
  682. if (CallType != VariadicDoesNotApply) {
  683. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  684. // Args[ArgIdx] can be null in malformed code.
  685. if (const Expr *Arg = Args[ArgIdx]) {
  686. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  687. checkVariadicArgument(Arg, CallType);
  688. }
  689. }
  690. }
  691. if (FDecl) {
  692. CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
  693. // Type safety checking.
  694. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  695. CheckArgumentWithTypeTag(I, Args.data());
  696. }
  697. }
  698. /// CheckConstructorCall - Check a constructor call for correctness and safety
  699. /// properties not enforced by the C type system.
  700. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  701. ArrayRef<const Expr *> Args,
  702. const FunctionProtoType *Proto,
  703. SourceLocation Loc) {
  704. VariadicCallType CallType =
  705. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  706. checkCall(FDecl, Args, Proto->getNumParams(),
  707. /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
  708. }
  709. /// CheckFunctionCall - Check a direct function call for various correctness
  710. /// and safety properties not strictly enforced by the C type system.
  711. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  712. const FunctionProtoType *Proto) {
  713. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  714. isa<CXXMethodDecl>(FDecl);
  715. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  716. IsMemberOperatorCall;
  717. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  718. TheCall->getCallee());
  719. unsigned NumParams = Proto ? Proto->getNumParams() : 0;
  720. Expr** Args = TheCall->getArgs();
  721. unsigned NumArgs = TheCall->getNumArgs();
  722. if (IsMemberOperatorCall) {
  723. // If this is a call to a member operator, hide the first argument
  724. // from checkCall.
  725. // FIXME: Our choice of AST representation here is less than ideal.
  726. ++Args;
  727. --NumArgs;
  728. }
  729. checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
  730. IsMemberFunction, TheCall->getRParenLoc(),
  731. TheCall->getCallee()->getSourceRange(), CallType);
  732. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  733. // None of the checks below are needed for functions that don't have
  734. // simple names (e.g., C++ conversion functions).
  735. if (!FnInfo)
  736. return false;
  737. CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
  738. unsigned CMId = FDecl->getMemoryFunctionKind();
  739. if (CMId == 0)
  740. return false;
  741. // Handle memory setting and copying functions.
  742. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  743. CheckStrlcpycatArguments(TheCall, FnInfo);
  744. else if (CMId == Builtin::BIstrncat)
  745. CheckStrncatArguments(TheCall, FnInfo);
  746. else
  747. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  748. return false;
  749. }
  750. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  751. ArrayRef<const Expr *> Args) {
  752. VariadicCallType CallType =
  753. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  754. checkCall(Method, Args, Method->param_size(),
  755. /*IsMemberFunction=*/false,
  756. lbrac, Method->getSourceRange(), CallType);
  757. return false;
  758. }
  759. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  760. const FunctionProtoType *Proto) {
  761. const VarDecl *V = dyn_cast<VarDecl>(NDecl);
  762. if (!V)
  763. return false;
  764. QualType Ty = V->getType();
  765. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
  766. return false;
  767. VariadicCallType CallType;
  768. if (!Proto || !Proto->isVariadic()) {
  769. CallType = VariadicDoesNotApply;
  770. } else if (Ty->isBlockPointerType()) {
  771. CallType = VariadicBlock;
  772. } else { // Ty->isFunctionPointerType()
  773. CallType = VariadicFunction;
  774. }
  775. unsigned NumParams = Proto ? Proto->getNumParams() : 0;
  776. checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
  777. TheCall->getNumArgs()),
  778. NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  779. TheCall->getCallee()->getSourceRange(), CallType);
  780. return false;
  781. }
  782. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  783. /// such as function pointers returned from functions.
  784. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  785. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  786. TheCall->getCallee());
  787. unsigned NumParams = Proto ? Proto->getNumParams() : 0;
  788. checkCall(/*FDecl=*/nullptr,
  789. llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
  790. TheCall->getNumArgs()),
  791. NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  792. TheCall->getCallee()->getSourceRange(), CallType);
  793. return false;
  794. }
  795. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  796. if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
  797. Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
  798. return false;
  799. switch (Op) {
  800. case AtomicExpr::AO__c11_atomic_init:
  801. llvm_unreachable("There is no ordering argument for an init");
  802. case AtomicExpr::AO__c11_atomic_load:
  803. case AtomicExpr::AO__atomic_load_n:
  804. case AtomicExpr::AO__atomic_load:
  805. return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
  806. Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
  807. case AtomicExpr::AO__c11_atomic_store:
  808. case AtomicExpr::AO__atomic_store:
  809. case AtomicExpr::AO__atomic_store_n:
  810. return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
  811. Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
  812. Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
  813. default:
  814. return true;
  815. }
  816. }
  817. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  818. AtomicExpr::AtomicOp Op) {
  819. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  820. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  821. // All these operations take one of the following forms:
  822. enum {
  823. // C __c11_atomic_init(A *, C)
  824. Init,
  825. // C __c11_atomic_load(A *, int)
  826. Load,
  827. // void __atomic_load(A *, CP, int)
  828. Copy,
  829. // C __c11_atomic_add(A *, M, int)
  830. Arithmetic,
  831. // C __atomic_exchange_n(A *, CP, int)
  832. Xchg,
  833. // void __atomic_exchange(A *, C *, CP, int)
  834. GNUXchg,
  835. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  836. C11CmpXchg,
  837. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  838. GNUCmpXchg
  839. } Form = Init;
  840. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
  841. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
  842. // where:
  843. // C is an appropriate type,
  844. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  845. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  846. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  847. // the int parameters are for orderings.
  848. assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  849. AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
  850. && "need to update code for modified C11 atomics");
  851. bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
  852. Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
  853. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  854. Op == AtomicExpr::AO__atomic_store_n ||
  855. Op == AtomicExpr::AO__atomic_exchange_n ||
  856. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  857. bool IsAddSub = false;
  858. switch (Op) {
  859. case AtomicExpr::AO__c11_atomic_init:
  860. Form = Init;
  861. break;
  862. case AtomicExpr::AO__c11_atomic_load:
  863. case AtomicExpr::AO__atomic_load_n:
  864. Form = Load;
  865. break;
  866. case AtomicExpr::AO__c11_atomic_store:
  867. case AtomicExpr::AO__atomic_load:
  868. case AtomicExpr::AO__atomic_store:
  869. case AtomicExpr::AO__atomic_store_n:
  870. Form = Copy;
  871. break;
  872. case AtomicExpr::AO__c11_atomic_fetch_add:
  873. case AtomicExpr::AO__c11_atomic_fetch_sub:
  874. case AtomicExpr::AO__atomic_fetch_add:
  875. case AtomicExpr::AO__atomic_fetch_sub:
  876. case AtomicExpr::AO__atomic_add_fetch:
  877. case AtomicExpr::AO__atomic_sub_fetch:
  878. IsAddSub = true;
  879. // Fall through.
  880. case AtomicExpr::AO__c11_atomic_fetch_and:
  881. case AtomicExpr::AO__c11_atomic_fetch_or:
  882. case AtomicExpr::AO__c11_atomic_fetch_xor:
  883. case AtomicExpr::AO__atomic_fetch_and:
  884. case AtomicExpr::AO__atomic_fetch_or:
  885. case AtomicExpr::AO__atomic_fetch_xor:
  886. case AtomicExpr::AO__atomic_fetch_nand:
  887. case AtomicExpr::AO__atomic_and_fetch:
  888. case AtomicExpr::AO__atomic_or_fetch:
  889. case AtomicExpr::AO__atomic_xor_fetch:
  890. case AtomicExpr::AO__atomic_nand_fetch:
  891. Form = Arithmetic;
  892. break;
  893. case AtomicExpr::AO__c11_atomic_exchange:
  894. case AtomicExpr::AO__atomic_exchange_n:
  895. Form = Xchg;
  896. break;
  897. case AtomicExpr::AO__atomic_exchange:
  898. Form = GNUXchg;
  899. break;
  900. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  901. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  902. Form = C11CmpXchg;
  903. break;
  904. case AtomicExpr::AO__atomic_compare_exchange:
  905. case AtomicExpr::AO__atomic_compare_exchange_n:
  906. Form = GNUCmpXchg;
  907. break;
  908. }
  909. // Check we have the right number of arguments.
  910. if (TheCall->getNumArgs() < NumArgs[Form]) {
  911. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  912. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  913. << TheCall->getCallee()->getSourceRange();
  914. return ExprError();
  915. } else if (TheCall->getNumArgs() > NumArgs[Form]) {
  916. Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
  917. diag::err_typecheck_call_too_many_args)
  918. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  919. << TheCall->getCallee()->getSourceRange();
  920. return ExprError();
  921. }
  922. // Inspect the first argument of the atomic operation.
  923. Expr *Ptr = TheCall->getArg(0);
  924. Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
  925. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  926. if (!pointerType) {
  927. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  928. << Ptr->getType() << Ptr->getSourceRange();
  929. return ExprError();
  930. }
  931. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  932. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  933. QualType ValType = AtomTy; // 'C'
  934. if (IsC11) {
  935. if (!AtomTy->isAtomicType()) {
  936. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  937. << Ptr->getType() << Ptr->getSourceRange();
  938. return ExprError();
  939. }
  940. if (AtomTy.isConstQualified()) {
  941. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
  942. << Ptr->getType() << Ptr->getSourceRange();
  943. return ExprError();
  944. }
  945. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  946. }
  947. // For an arithmetic operation, the implied arithmetic must be well-formed.
  948. if (Form == Arithmetic) {
  949. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  950. if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
  951. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  952. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  953. return ExprError();
  954. }
  955. if (!IsAddSub && !ValType->isIntegerType()) {
  956. Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
  957. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  958. return ExprError();
  959. }
  960. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  961. // For __atomic_*_n operations, the value type must be a scalar integral or
  962. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  963. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  964. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  965. return ExprError();
  966. }
  967. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  968. !AtomTy->isScalarType()) {
  969. // For GNU atomics, require a trivially-copyable type. This is not part of
  970. // the GNU atomics specification, but we enforce it for sanity.
  971. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
  972. << Ptr->getType() << Ptr->getSourceRange();
  973. return ExprError();
  974. }
  975. // FIXME: For any builtin other than a load, the ValType must not be
  976. // const-qualified.
  977. switch (ValType.getObjCLifetime()) {
  978. case Qualifiers::OCL_None:
  979. case Qualifiers::OCL_ExplicitNone:
  980. // okay
  981. break;
  982. case Qualifiers::OCL_Weak:
  983. case Qualifiers::OCL_Strong:
  984. case Qualifiers::OCL_Autoreleasing:
  985. // FIXME: Can this happen? By this point, ValType should be known
  986. // to be trivially copyable.
  987. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  988. << ValType << Ptr->getSourceRange();
  989. return ExprError();
  990. }
  991. QualType ResultType = ValType;
  992. if (Form == Copy || Form == GNUXchg || Form == Init)
  993. ResultType = Context.VoidTy;
  994. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  995. ResultType = Context.BoolTy;
  996. // The type of a parameter passed 'by value'. In the GNU atomics, such
  997. // arguments are actually passed as pointers.
  998. QualType ByValType = ValType; // 'CP'
  999. if (!IsC11 && !IsN)
  1000. ByValType = Ptr->getType();
  1001. // The first argument --- the pointer --- has a fixed type; we
  1002. // deduce the types of the rest of the arguments accordingly. Walk
  1003. // the remaining arguments, converting them to the deduced value type.
  1004. for (unsigned i = 1; i != NumArgs[Form]; ++i) {
  1005. QualType Ty;
  1006. if (i < NumVals[Form] + 1) {
  1007. switch (i) {
  1008. case 1:
  1009. // The second argument is the non-atomic operand. For arithmetic, this
  1010. // is always passed by value, and for a compare_exchange it is always
  1011. // passed by address. For the rest, GNU uses by-address and C11 uses
  1012. // by-value.
  1013. assert(Form != Load);
  1014. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  1015. Ty = ValType;
  1016. else if (Form == Copy || Form == Xchg)
  1017. Ty = ByValType;
  1018. else if (Form == Arithmetic)
  1019. Ty = Context.getPointerDiffType();
  1020. else
  1021. Ty = Context.getPointerType(ValType.getUnqualifiedType());
  1022. break;
  1023. case 2:
  1024. // The third argument to compare_exchange / GNU exchange is a
  1025. // (pointer to a) desired value.
  1026. Ty = ByValType;
  1027. break;
  1028. case 3:
  1029. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  1030. Ty = Context.BoolTy;
  1031. break;
  1032. }
  1033. } else {
  1034. // The order(s) are always converted to int.
  1035. Ty = Context.IntTy;
  1036. }
  1037. InitializedEntity Entity =
  1038. InitializedEntity::InitializeParameter(Context, Ty, false);
  1039. ExprResult Arg = TheCall->getArg(i);
  1040. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1041. if (Arg.isInvalid())
  1042. return true;
  1043. TheCall->setArg(i, Arg.get());
  1044. }
  1045. // Permute the arguments into a 'consistent' order.
  1046. SmallVector<Expr*, 5> SubExprs;
  1047. SubExprs.push_back(Ptr);
  1048. switch (Form) {
  1049. case Init:
  1050. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  1051. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1052. break;
  1053. case Load:
  1054. SubExprs.push_back(TheCall->getArg(1)); // Order
  1055. break;
  1056. case Copy:
  1057. case Arithmetic:
  1058. case Xchg:
  1059. SubExprs.push_back(TheCall->getArg(2)); // Order
  1060. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1061. break;
  1062. case GNUXchg:
  1063. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  1064. SubExprs.push_back(TheCall->getArg(3)); // Order
  1065. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1066. SubExprs.push_back(TheCall->getArg(2)); // Val2
  1067. break;
  1068. case C11CmpXchg:
  1069. SubExprs.push_back(TheCall->getArg(3)); // Order
  1070. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1071. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  1072. SubExprs.push_back(TheCall->getArg(2)); // Val2
  1073. break;
  1074. case GNUCmpXchg:
  1075. SubExprs.push_back(TheCall->getArg(4)); // Order
  1076. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1077. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  1078. SubExprs.push_back(TheCall->getArg(2)); // Val2
  1079. SubExprs.push_back(TheCall->getArg(3)); // Weak
  1080. break;
  1081. }
  1082. if (SubExprs.size() >= 2 && Form != Init) {
  1083. llvm::APSInt Result(32);
  1084. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  1085. !isValidOrderingForOp(Result.getSExtValue(), Op))
  1086. Diag(SubExprs[1]->getLocStart(),
  1087. diag::warn_atomic_op_has_invalid_memory_order)
  1088. << SubExprs[1]->getSourceRange();
  1089. }
  1090. AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  1091. SubExprs, ResultType, Op,
  1092. TheCall->getRParenLoc());
  1093. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  1094. (Op == AtomicExpr::AO__c11_atomic_store)) &&
  1095. Context.AtomicUsesUnsupportedLibcall(AE))
  1096. Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
  1097. ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
  1098. return Owned(AE);
  1099. }
  1100. /// checkBuiltinArgument - Given a call to a builtin function, perform
  1101. /// normal type-checking on the given argument, updating the call in
  1102. /// place. This is useful when a builtin function requires custom
  1103. /// type-checking for some of its arguments but not necessarily all of
  1104. /// them.
  1105. ///
  1106. /// Returns true on error.
  1107. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  1108. FunctionDecl *Fn = E->getDirectCallee();
  1109. assert(Fn && "builtin call without direct callee!");
  1110. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  1111. InitializedEntity Entity =
  1112. InitializedEntity::InitializeParameter(S.Context, Param);
  1113. ExprResult Arg = E->getArg(0);
  1114. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1115. if (Arg.isInvalid())
  1116. return true;
  1117. E->setArg(ArgIndex, Arg.take());
  1118. return false;
  1119. }
  1120. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  1121. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  1122. /// type of its first argument. The main ActOnCallExpr routines have already
  1123. /// promoted the types of arguments because all of these calls are prototyped as
  1124. /// void(...).
  1125. ///
  1126. /// This function goes through and does final semantic checking for these
  1127. /// builtins,
  1128. ExprResult
  1129. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  1130. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  1131. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1132. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  1133. // Ensure that we have at least one argument to do type inference from.
  1134. if (TheCall->getNumArgs() < 1) {
  1135. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  1136. << 0 << 1 << TheCall->getNumArgs()
  1137. << TheCall->getCallee()->getSourceRange();
  1138. return ExprError();
  1139. }
  1140. // Inspect the first argument of the atomic builtin. This should always be
  1141. // a pointer type, whose element is an integral scalar or pointer type.
  1142. // Because it is a pointer type, we don't have to worry about any implicit
  1143. // casts here.
  1144. // FIXME: We don't allow floating point scalars as input.
  1145. Expr *FirstArg = TheCall->getArg(0);
  1146. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  1147. if (FirstArgResult.isInvalid())
  1148. return ExprError();
  1149. FirstArg = FirstArgResult.take();
  1150. TheCall->setArg(0, FirstArg);
  1151. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  1152. if (!pointerType) {
  1153. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  1154. << FirstArg->getType() << FirstArg->getSourceRange();
  1155. return ExprError();
  1156. }
  1157. QualType ValType = pointerType->getPointeeType();
  1158. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1159. !ValType->isBlockPointerType()) {
  1160. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  1161. << FirstArg->getType() << FirstArg->getSourceRange();
  1162. return ExprError();
  1163. }
  1164. switch (ValType.getObjCLifetime()) {
  1165. case Qualifiers::OCL_None:
  1166. case Qualifiers::OCL_ExplicitNone:
  1167. // okay
  1168. break;
  1169. case Qualifiers::OCL_Weak:
  1170. case Qualifiers::OCL_Strong:
  1171. case Qualifiers::OCL_Autoreleasing:
  1172. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  1173. << ValType << FirstArg->getSourceRange();
  1174. return ExprError();
  1175. }
  1176. // Strip any qualifiers off ValType.
  1177. ValType = ValType.getUnqualifiedType();
  1178. // The majority of builtins return a value, but a few have special return
  1179. // types, so allow them to override appropriately below.
  1180. QualType ResultType = ValType;
  1181. // We need to figure out which concrete builtin this maps onto. For example,
  1182. // __sync_fetch_and_add with a 2 byte object turns into
  1183. // __sync_fetch_and_add_2.
  1184. #define BUILTIN_ROW(x) \
  1185. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  1186. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  1187. static const unsigned BuiltinIndices[][5] = {
  1188. BUILTIN_ROW(__sync_fetch_and_add),
  1189. BUILTIN_ROW(__sync_fetch_and_sub),
  1190. BUILTIN_ROW(__sync_fetch_and_or),
  1191. BUILTIN_ROW(__sync_fetch_and_and),
  1192. BUILTIN_ROW(__sync_fetch_and_xor),
  1193. BUILTIN_ROW(__sync_add_and_fetch),
  1194. BUILTIN_ROW(__sync_sub_and_fetch),
  1195. BUILTIN_ROW(__sync_and_and_fetch),
  1196. BUILTIN_ROW(__sync_or_and_fetch),
  1197. BUILTIN_ROW(__sync_xor_and_fetch),
  1198. BUILTIN_ROW(__sync_val_compare_and_swap),
  1199. BUILTIN_ROW(__sync_bool_compare_and_swap),
  1200. BUILTIN_ROW(__sync_lock_test_and_set),
  1201. BUILTIN_ROW(__sync_lock_release),
  1202. BUILTIN_ROW(__sync_swap)
  1203. };
  1204. #undef BUILTIN_ROW
  1205. // Determine the index of the size.
  1206. unsigned SizeIndex;
  1207. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  1208. case 1: SizeIndex = 0; break;
  1209. case 2: SizeIndex = 1; break;
  1210. case 4: SizeIndex = 2; break;
  1211. case 8: SizeIndex = 3; break;
  1212. case 16: SizeIndex = 4; break;
  1213. default:
  1214. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  1215. << FirstArg->getType() << FirstArg->getSourceRange();
  1216. return ExprError();
  1217. }
  1218. // Each of these builtins has one pointer argument, followed by some number of
  1219. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  1220. // that we ignore. Find out which row of BuiltinIndices to read from as well
  1221. // as the number of fixed args.
  1222. unsigned BuiltinID = FDecl->getBuiltinID();
  1223. unsigned BuiltinIndex, NumFixed = 1;
  1224. switch (BuiltinID) {
  1225. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  1226. case Builtin::BI__sync_fetch_and_add:
  1227. case Builtin::BI__sync_fetch_and_add_1:
  1228. case Builtin::BI__sync_fetch_and_add_2:
  1229. case Builtin::BI__sync_fetch_and_add_4:
  1230. case Builtin::BI__sync_fetch_and_add_8:
  1231. case Builtin::BI__sync_fetch_and_add_16:
  1232. BuiltinIndex = 0;
  1233. break;
  1234. case Builtin::BI__sync_fetch_and_sub:
  1235. case Builtin::BI__sync_fetch_and_sub_1:
  1236. case Builtin::BI__sync_fetch_and_sub_2:
  1237. case Builtin::BI__sync_fetch_and_sub_4:
  1238. case Builtin::BI__sync_fetch_and_sub_8:
  1239. case Builtin::BI__sync_fetch_and_sub_16:
  1240. BuiltinIndex = 1;
  1241. break;
  1242. case Builtin::BI__sync_fetch_and_or:
  1243. case Builtin::BI__sync_fetch_and_or_1:
  1244. case Builtin::BI__sync_fetch_and_or_2:
  1245. case Builtin::BI__sync_fetch_and_or_4:
  1246. case Builtin::BI__sync_fetch_and_or_8:
  1247. case Builtin::BI__sync_fetch_and_or_16:
  1248. BuiltinIndex = 2;
  1249. break;
  1250. case Builtin::BI__sync_fetch_and_and:
  1251. case Builtin::BI__sync_fetch_and_and_1:
  1252. case Builtin::BI__sync_fetch_and_and_2:
  1253. case Builtin::BI__sync_fetch_and_and_4:
  1254. case Builtin::BI__sync_fetch_and_and_8:
  1255. case Builtin::BI__sync_fetch_and_and_16:
  1256. BuiltinIndex = 3;
  1257. break;
  1258. case Builtin::BI__sync_fetch_and_xor:
  1259. case Builtin::BI__sync_fetch_and_xor_1:
  1260. case Builtin::BI__sync_fetch_and_xor_2:
  1261. case Builtin::BI__sync_fetch_and_xor_4:
  1262. case Builtin::BI__sync_fetch_and_xor_8:
  1263. case Builtin::BI__sync_fetch_and_xor_16:
  1264. BuiltinIndex = 4;
  1265. break;
  1266. case Builtin::BI__sync_add_and_fetch:
  1267. case Builtin::BI__sync_add_and_fetch_1:
  1268. case Builtin::BI__sync_add_and_fetch_2:
  1269. case Builtin::BI__sync_add_and_fetch_4:
  1270. case Builtin::BI__sync_add_and_fetch_8:
  1271. case Builtin::BI__sync_add_and_fetch_16:
  1272. BuiltinIndex = 5;
  1273. break;
  1274. case Builtin::BI__sync_sub_and_fetch:
  1275. case Builtin::BI__sync_sub_and_fetch_1:
  1276. case Builtin::BI__sync_sub_and_fetch_2:
  1277. case Builtin::BI__sync_sub_and_fetch_4:
  1278. case Builtin::BI__sync_sub_and_fetch_8:
  1279. case Builtin::BI__sync_sub_and_fetch_16:
  1280. BuiltinIndex = 6;
  1281. break;
  1282. case Builtin::BI__sync_and_and_fetch:
  1283. case Builtin::BI__sync_and_and_fetch_1:
  1284. case Builtin::BI__sync_and_and_fetch_2:
  1285. case Builtin::BI__sync_and_and_fetch_4:
  1286. case Builtin::BI__sync_and_and_fetch_8:
  1287. case Builtin::BI__sync_and_and_fetch_16:
  1288. BuiltinIndex = 7;
  1289. break;
  1290. case Builtin::BI__sync_or_and_fetch:
  1291. case Builtin::BI__sync_or_and_fetch_1:
  1292. case Builtin::BI__sync_or_and_fetch_2:
  1293. case Builtin::BI__sync_or_and_fetch_4:
  1294. case Builtin::BI__sync_or_and_fetch_8:
  1295. case Builtin::BI__sync_or_and_fetch_16:
  1296. BuiltinIndex = 8;
  1297. break;
  1298. case Builtin::BI__sync_xor_and_fetch:
  1299. case Builtin::BI__sync_xor_and_fetch_1:
  1300. case Builtin::BI__sync_xor_and_fetch_2:
  1301. case Builtin::BI__sync_xor_and_fetch_4:
  1302. case Builtin::BI__sync_xor_and_fetch_8:
  1303. case Builtin::BI__sync_xor_and_fetch_16:
  1304. BuiltinIndex = 9;
  1305. break;
  1306. case Builtin::BI__sync_val_compare_and_swap:
  1307. case Builtin::BI__sync_val_compare_and_swap_1:
  1308. case Builtin::BI__sync_val_compare_and_swap_2:
  1309. case Builtin::BI__sync_val_compare_and_swap_4:
  1310. case Builtin::BI__sync_val_compare_and_swap_8:
  1311. case Builtin::BI__sync_val_compare_and_swap_16:
  1312. BuiltinIndex = 10;
  1313. NumFixed = 2;
  1314. break;
  1315. case Builtin::BI__sync_bool_compare_and_swap:
  1316. case Builtin::BI__sync_bool_compare_and_swap_1:
  1317. case Builtin::BI__sync_bool_compare_and_swap_2:
  1318. case Builtin::BI__sync_bool_compare_and_swap_4:
  1319. case Builtin::BI__sync_bool_compare_and_swap_8:
  1320. case Builtin::BI__sync_bool_compare_and_swap_16:
  1321. BuiltinIndex = 11;
  1322. NumFixed = 2;
  1323. ResultType = Context.BoolTy;
  1324. break;
  1325. case Builtin::BI__sync_lock_test_and_set:
  1326. case Builtin::BI__sync_lock_test_and_set_1:
  1327. case Builtin::BI__sync_lock_test_and_set_2:
  1328. case Builtin::BI__sync_lock_test_and_set_4:
  1329. case Builtin::BI__sync_lock_test_and_set_8:
  1330. case Builtin::BI__sync_lock_test_and_set_16:
  1331. BuiltinIndex = 12;
  1332. break;
  1333. case Builtin::BI__sync_lock_release:
  1334. case Builtin::BI__sync_lock_release_1:
  1335. case Builtin::BI__sync_lock_release_2:
  1336. case Builtin::BI__sync_lock_release_4:
  1337. case Builtin::BI__sync_lock_release_8:
  1338. case Builtin::BI__sync_lock_release_16:
  1339. BuiltinIndex = 13;
  1340. NumFixed = 0;
  1341. ResultType = Context.VoidTy;
  1342. break;
  1343. case Builtin::BI__sync_swap:
  1344. case Builtin::BI__sync_swap_1:
  1345. case Builtin::BI__sync_swap_2:
  1346. case Builtin::BI__sync_swap_4:
  1347. case Builtin::BI__sync_swap_8:
  1348. case Builtin::BI__sync_swap_16:
  1349. BuiltinIndex = 14;
  1350. break;
  1351. }
  1352. // Now that we know how many fixed arguments we expect, first check that we
  1353. // have at least that many.
  1354. if (TheCall->getNumArgs() < 1+NumFixed) {
  1355. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  1356. << 0 << 1+NumFixed << TheCall->getNumArgs()
  1357. << TheCall->getCallee()->getSourceRange();
  1358. return ExprError();
  1359. }
  1360. // Get the decl for the concrete builtin from this, we can tell what the
  1361. // concrete integer type we should convert to is.
  1362. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  1363. const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
  1364. FunctionDecl *NewBuiltinDecl;
  1365. if (NewBuiltinID == BuiltinID)
  1366. NewBuiltinDecl = FDecl;
  1367. else {
  1368. // Perform builtin lookup to avoid redeclaring it.
  1369. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  1370. LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
  1371. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  1372. assert(Res.getFoundDecl());
  1373. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  1374. if (!NewBuiltinDecl)
  1375. return ExprError();
  1376. }
  1377. // The first argument --- the pointer --- has a fixed type; we
  1378. // deduce the types of the rest of the arguments accordingly. Walk
  1379. // the remaining arguments, converting them to the deduced value type.
  1380. for (unsigned i = 0; i != NumFixed; ++i) {
  1381. ExprResult Arg = TheCall->getArg(i+1);
  1382. // GCC does an implicit conversion to the pointer or integer ValType. This
  1383. // can fail in some cases (1i -> int**), check for this error case now.
  1384. // Initialize the argument.
  1385. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  1386. ValType, /*consume*/ false);
  1387. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1388. if (Arg.isInvalid())
  1389. return ExprError();
  1390. // Okay, we have something that *can* be converted to the right type. Check
  1391. // to see if there is a potentially weird extension going on here. This can
  1392. // happen when you do an atomic operation on something like an char* and
  1393. // pass in 42. The 42 gets converted to char. This is even more strange
  1394. // for things like 45.123 -> char, etc.
  1395. // FIXME: Do this check.
  1396. TheCall->setArg(i+1, Arg.take());
  1397. }
  1398. ASTContext& Context = this->getASTContext();
  1399. // Create a new DeclRefExpr to refer to the new decl.
  1400. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  1401. Context,
  1402. DRE->getQualifierLoc(),
  1403. SourceLocation(),
  1404. NewBuiltinDecl,
  1405. /*enclosing*/ false,
  1406. DRE->getLocation(),
  1407. Context.BuiltinFnTy,
  1408. DRE->getValueKind());
  1409. // Set the callee in the CallExpr.
  1410. // FIXME: This loses syntactic information.
  1411. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  1412. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  1413. CK_BuiltinFnToFnPtr);
  1414. TheCall->setCallee(PromotedCall.take());
  1415. // Change the result type of the call to match the original value type. This
  1416. // is arbitrary, but the codegen for these builtins ins design to handle it
  1417. // gracefully.
  1418. TheCall->setType(ResultType);
  1419. return TheCallResult;
  1420. }
  1421. /// CheckObjCString - Checks that the argument to the builtin
  1422. /// CFString constructor is correct
  1423. /// Note: It might also make sense to do the UTF-16 conversion here (would
  1424. /// simplify the backend).
  1425. bool Sema::CheckObjCString(Expr *Arg) {
  1426. Arg = Arg->IgnoreParenCasts();
  1427. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  1428. if (!Literal || !Literal->isAscii()) {
  1429. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  1430. << Arg->getSourceRange();
  1431. return true;
  1432. }
  1433. if (Literal->containsNonAsciiOrNull()) {
  1434. StringRef String = Literal->getString();
  1435. unsigned NumBytes = String.size();
  1436. SmallVector<UTF16, 128> ToBuf(NumBytes);
  1437. const UTF8 *FromPtr = (const UTF8 *)String.data();
  1438. UTF16 *ToPtr = &ToBuf[0];
  1439. ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1440. &ToPtr, ToPtr + NumBytes,
  1441. strictConversion);
  1442. // Check for conversion failure.
  1443. if (Result != conversionOK)
  1444. Diag(Arg->getLocStart(),
  1445. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  1446. }
  1447. return false;
  1448. }
  1449. /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
  1450. /// Emit an error and return true on failure, return false on success.
  1451. bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
  1452. Expr *Fn = TheCall->getCallee();
  1453. if (TheCall->getNumArgs() > 2) {
  1454. Diag(TheCall->getArg(2)->getLocStart(),
  1455. diag::err_typecheck_call_too_many_args)
  1456. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1457. << Fn->getSourceRange()
  1458. << SourceRange(TheCall->getArg(2)->getLocStart(),
  1459. (*(TheCall->arg_end()-1))->getLocEnd());
  1460. return true;
  1461. }
  1462. if (TheCall->getNumArgs() < 2) {
  1463. return Diag(TheCall->getLocEnd(),
  1464. diag::err_typecheck_call_too_few_args_at_least)
  1465. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  1466. }
  1467. // Type-check the first argument normally.
  1468. if (checkBuiltinArgument(*this, TheCall, 0))
  1469. return true;
  1470. // Determine whether the current function is variadic or not.
  1471. BlockScopeInfo *CurBlock = getCurBlock();
  1472. bool isVariadic;
  1473. if (CurBlock)
  1474. isVariadic = CurBlock->TheDecl->isVariadic();
  1475. else if (FunctionDecl *FD = getCurFunctionDecl())
  1476. isVariadic = FD->isVariadic();
  1477. else
  1478. isVariadic = getCurMethodDecl()->isVariadic();
  1479. if (!isVariadic) {
  1480. Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
  1481. return true;
  1482. }
  1483. // Verify that the second argument to the builtin is the last argument of the
  1484. // current function or method.
  1485. bool SecondArgIsLastNamedArgument = false;
  1486. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  1487. // These are valid if SecondArgIsLastNamedArgument is false after the next
  1488. // block.
  1489. QualType Type;
  1490. SourceLocation ParamLoc;
  1491. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  1492. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  1493. // FIXME: This isn't correct for methods (results in bogus warning).
  1494. // Get the last formal in the current function.
  1495. const ParmVarDecl *LastArg;
  1496. if (CurBlock)
  1497. LastArg = *(CurBlock->TheDecl->param_end()-1);
  1498. else if (FunctionDecl *FD = getCurFunctionDecl())
  1499. LastArg = *(FD->param_end()-1);
  1500. else
  1501. LastArg = *(getCurMethodDecl()->param_end()-1);
  1502. SecondArgIsLastNamedArgument = PV == LastArg;
  1503. Type = PV->getType();
  1504. ParamLoc = PV->getLocation();
  1505. }
  1506. }
  1507. if (!SecondArgIsLastNamedArgument)
  1508. Diag(TheCall->getArg(1)->getLocStart(),
  1509. diag::warn_second_parameter_of_va_start_not_last_named_argument);
  1510. else if (Type->isReferenceType()) {
  1511. Diag(Arg->getLocStart(),
  1512. diag::warn_va_start_of_reference_type_is_undefined);
  1513. Diag(ParamLoc, diag::note_parameter_type) << Type;
  1514. }
  1515. TheCall->setType(Context.VoidTy);
  1516. return false;
  1517. }
  1518. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  1519. /// friends. This is declared to take (...), so we have to check everything.
  1520. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  1521. if (TheCall->getNumArgs() < 2)
  1522. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1523. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  1524. if (TheCall->getNumArgs() > 2)
  1525. return Diag(TheCall->getArg(2)->getLocStart(),
  1526. diag::err_typecheck_call_too_many_args)
  1527. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1528. << SourceRange(TheCall->getArg(2)->getLocStart(),
  1529. (*(TheCall->arg_end()-1))->getLocEnd());
  1530. ExprResult OrigArg0 = TheCall->getArg(0);
  1531. ExprResult OrigArg1 = TheCall->getArg(1);
  1532. // Do standard promotions between the two arguments, returning their common
  1533. // type.
  1534. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  1535. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  1536. return true;
  1537. // Make sure any conversions are pushed back into the call; this is
  1538. // type safe since unordered compare builtins are declared as "_Bool
  1539. // foo(...)".
  1540. TheCall->setArg(0, OrigArg0.get());
  1541. TheCall->setArg(1, OrigArg1.get());
  1542. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  1543. return false;
  1544. // If the common type isn't a real floating type, then the arguments were
  1545. // invalid for this operation.
  1546. if (Res.isNull() || !Res->isRealFloatingType())
  1547. return Diag(OrigArg0.get()->getLocStart(),
  1548. diag::err_typecheck_call_invalid_ordered_compare)
  1549. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  1550. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  1551. return false;
  1552. }
  1553. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  1554. /// __builtin_isnan and friends. This is declared to take (...), so we have
  1555. /// to check everything. We expect the last argument to be a floating point
  1556. /// value.
  1557. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  1558. if (TheCall->getNumArgs() < NumArgs)
  1559. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1560. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  1561. if (TheCall->getNumArgs() > NumArgs)
  1562. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  1563. diag::err_typecheck_call_too_many_args)
  1564. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  1565. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  1566. (*(TheCall->arg_end()-1))->getLocEnd());
  1567. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  1568. if (OrigArg->isTypeDependent())
  1569. return false;
  1570. // This operation requires a non-_Complex floating-point number.
  1571. if (!OrigArg->getType()->isRealFloatingType())
  1572. return Diag(OrigArg->getLocStart(),
  1573. diag::err_typecheck_call_invalid_unary_fp)
  1574. << OrigArg->getType() << OrigArg->getSourceRange();
  1575. // If this is an implicit conversion from float -> double, remove it.
  1576. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  1577. Expr *CastArg = Cast->getSubExpr();
  1578. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  1579. assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
  1580. "promotion from float to double is the only expected cast here");
  1581. Cast->setSubExpr(nullptr);
  1582. TheCall->setArg(NumArgs-1, CastArg);
  1583. }
  1584. }
  1585. return false;
  1586. }
  1587. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  1588. // This is declared to take (...), so we have to check everything.
  1589. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  1590. if (TheCall->getNumArgs() < 2)
  1591. return ExprError(Diag(TheCall->getLocEnd(),
  1592. diag::err_typecheck_call_too_few_args_at_least)
  1593. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1594. << TheCall->getSourceRange());
  1595. // Determine which of the following types of shufflevector we're checking:
  1596. // 1) unary, vector mask: (lhs, mask)
  1597. // 2) binary, vector mask: (lhs, rhs, mask)
  1598. // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
  1599. QualType resType = TheCall->getArg(0)->getType();
  1600. unsigned numElements = 0;
  1601. if (!TheCall->getArg(0)->isTypeDependent() &&
  1602. !TheCall->getArg(1)->isTypeDependent()) {
  1603. QualType LHSType = TheCall->getArg(0)->getType();
  1604. QualType RHSType = TheCall->getArg(1)->getType();
  1605. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  1606. return ExprError(Diag(TheCall->getLocStart(),
  1607. diag::err_shufflevector_non_vector)
  1608. << SourceRange(TheCall->getArg(0)->getLocStart(),
  1609. TheCall->getArg(1)->getLocEnd()));
  1610. numElements = LHSType->getAs<VectorType>()->getNumElements();
  1611. unsigned numResElements = TheCall->getNumArgs() - 2;
  1612. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  1613. // with mask. If so, verify that RHS is an integer vector type with the
  1614. // same number of elts as lhs.
  1615. if (TheCall->getNumArgs() == 2) {
  1616. if (!RHSType->hasIntegerRepresentation() ||
  1617. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  1618. return ExprError(Diag(TheCall->getLocStart(),
  1619. diag::err_shufflevector_incompatible_vector)
  1620. << SourceRange(TheCall->getArg(1)->getLocStart(),
  1621. TheCall->getArg(1)->getLocEnd()));
  1622. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  1623. return ExprError(Diag(TheCall->getLocStart(),
  1624. diag::err_shufflevector_incompatible_vector)
  1625. << SourceRange(TheCall->getArg(0)->getLocStart(),
  1626. TheCall->getArg(1)->getLocEnd()));
  1627. } else if (numElements != numResElements) {
  1628. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  1629. resType = Context.getVectorType(eltType, numResElements,
  1630. VectorType::GenericVector);
  1631. }
  1632. }
  1633. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  1634. if (TheCall->getArg(i)->isTypeDependent() ||
  1635. TheCall->getArg(i)->isValueDependent())
  1636. continue;
  1637. llvm::APSInt Result(32);
  1638. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  1639. return ExprError(Diag(TheCall->getLocStart(),
  1640. diag::err_shufflevector_nonconstant_argument)
  1641. << TheCall->getArg(i)->getSourceRange());
  1642. // Allow -1 which will be translated to undef in the IR.
  1643. if (Result.isSigned() && Result.isAllOnesValue())
  1644. continue;
  1645. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  1646. return ExprError(Diag(TheCall->getLocStart(),
  1647. diag::err_shufflevector_argument_too_large)
  1648. << TheCall->getArg(i)->getSourceRange());
  1649. }
  1650. SmallVector<Expr*, 32> exprs;
  1651. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  1652. exprs.push_back(TheCall->getArg(i));
  1653. TheCall->setArg(i, nullptr);
  1654. }
  1655. return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
  1656. TheCall->getCallee()->getLocStart(),
  1657. TheCall->getRParenLoc()));
  1658. }
  1659. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  1660. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  1661. SourceLocation BuiltinLoc,
  1662. SourceLocation RParenLoc) {
  1663. ExprValueKind VK = VK_RValue;
  1664. ExprObjectKind OK = OK_Ordinary;
  1665. QualType DstTy = TInfo->getType();
  1666. QualType SrcTy = E->getType();
  1667. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  1668. return ExprError(Diag(BuiltinLoc,
  1669. diag::err_convertvector_non_vector)
  1670. << E->getSourceRange());
  1671. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  1672. return ExprError(Diag(BuiltinLoc,
  1673. diag::err_convertvector_non_vector_type));
  1674. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  1675. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  1676. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  1677. if (SrcElts != DstElts)
  1678. return ExprError(Diag(BuiltinLoc,
  1679. diag::err_convertvector_incompatible_vector)
  1680. << E->getSourceRange());
  1681. }
  1682. return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
  1683. BuiltinLoc, RParenLoc));
  1684. }
  1685. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  1686. // This is declared to take (const void*, ...) and can take two
  1687. // optional constant int args.
  1688. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  1689. unsigned NumArgs = TheCall->getNumArgs();
  1690. if (NumArgs > 3)
  1691. return Diag(TheCall->getLocEnd(),
  1692. diag::err_typecheck_call_too_many_args_at_most)
  1693. << 0 /*function call*/ << 3 << NumArgs
  1694. << TheCall->getSourceRange();
  1695. // Argument 0 is checked for us and the remaining arguments must be
  1696. // constant integers.
  1697. for (unsigned i = 1; i != NumArgs; ++i)
  1698. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  1699. return true;
  1700. return false;
  1701. }
  1702. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  1703. /// TheCall is a constant expression.
  1704. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  1705. llvm::APSInt &Result) {
  1706. Expr *Arg = TheCall->getArg(ArgNum);
  1707. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1708. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  1709. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  1710. if (!Arg->isIntegerConstantExpr(Result, Context))
  1711. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  1712. << FDecl->getDeclName() << Arg->getSourceRange();
  1713. return false;
  1714. }
  1715. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  1716. /// TheCall is a constant expression in the range [Low, High].
  1717. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  1718. int Low, int High) {
  1719. llvm::APSInt Result;
  1720. // We can't check the value of a dependent argument.
  1721. Expr *Arg = TheCall->getArg(ArgNum);
  1722. if (Arg->isTypeDependent() || Arg->isValueDependent())
  1723. return false;
  1724. // Check constant-ness first.
  1725. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  1726. return true;
  1727. if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
  1728. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1729. << Low << High << Arg->getSourceRange();
  1730. return false;
  1731. }
  1732. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  1733. /// This checks that val is a constant 1.
  1734. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  1735. Expr *Arg = TheCall->getArg(1);
  1736. llvm::APSInt Result;
  1737. // TODO: This is less than ideal. Overload this to take a value.
  1738. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  1739. return true;
  1740. if (Result != 1)
  1741. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  1742. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  1743. return false;
  1744. }
  1745. namespace {
  1746. enum StringLiteralCheckType {
  1747. SLCT_NotALiteral,
  1748. SLCT_UncheckedLiteral,
  1749. SLCT_CheckedLiteral
  1750. };
  1751. }
  1752. // Determine if an expression is a string literal or constant string.
  1753. // If this function returns false on the arguments to a function expecting a
  1754. // format string, we will usually need to emit a warning.
  1755. // True string literals are then checked by CheckFormatString.
  1756. static StringLiteralCheckType
  1757. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  1758. bool HasVAListArg, unsigned format_idx,
  1759. unsigned firstDataArg, Sema::FormatStringType Type,
  1760. Sema::VariadicCallType CallType, bool InFunctionCall,
  1761. llvm::SmallBitVector &CheckedVarArgs) {
  1762. tryAgain:
  1763. if (E->isTypeDependent() || E->isValueDependent())
  1764. return SLCT_NotALiteral;
  1765. E = E->IgnoreParenCasts();
  1766. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  1767. // Technically -Wformat-nonliteral does not warn about this case.
  1768. // The behavior of printf and friends in this case is implementation
  1769. // dependent. Ideally if the format string cannot be null then
  1770. // it should have a 'nonnull' attribute in the function prototype.
  1771. return SLCT_UncheckedLiteral;
  1772. switch (E->getStmtClass()) {
  1773. case Stmt::BinaryConditionalOperatorClass:
  1774. case Stmt::ConditionalOperatorClass: {
  1775. // The expression is a literal if both sub-expressions were, and it was
  1776. // completely checked only if both sub-expressions were checked.
  1777. const AbstractConditionalOperator *C =
  1778. cast<AbstractConditionalOperator>(E);
  1779. StringLiteralCheckType Left =
  1780. checkFormatStringExpr(S, C->getTrueExpr(), Args,
  1781. HasVAListArg, format_idx, firstDataArg,
  1782. Type, CallType, InFunctionCall, CheckedVarArgs);
  1783. if (Left == SLCT_NotALiteral)
  1784. return SLCT_NotALiteral;
  1785. StringLiteralCheckType Right =
  1786. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  1787. HasVAListArg, format_idx, firstDataArg,
  1788. Type, CallType, InFunctionCall, CheckedVarArgs);
  1789. return Left < Right ? Left : Right;
  1790. }
  1791. case Stmt::ImplicitCastExprClass: {
  1792. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  1793. goto tryAgain;
  1794. }
  1795. case Stmt::OpaqueValueExprClass:
  1796. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  1797. E = src;
  1798. goto tryAgain;
  1799. }
  1800. return SLCT_NotALiteral;
  1801. case Stmt::PredefinedExprClass:
  1802. // While __func__, etc., are technically not string literals, they
  1803. // cannot contain format specifiers and thus are not a security
  1804. // liability.
  1805. return SLCT_UncheckedLiteral;
  1806. case Stmt::DeclRefExprClass: {
  1807. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  1808. // As an exception, do not flag errors for variables binding to
  1809. // const string literals.
  1810. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1811. bool isConstant = false;
  1812. QualType T = DR->getType();
  1813. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  1814. isConstant = AT->getElementType().isConstant(S.Context);
  1815. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  1816. isConstant = T.isConstant(S.Context) &&
  1817. PT->getPointeeType().isConstant(S.Context);
  1818. } else if (T->isObjCObjectPointerType()) {
  1819. // In ObjC, there is usually no "const ObjectPointer" type,
  1820. // so don't check if the pointee type is constant.
  1821. isConstant = T.isConstant(S.Context);
  1822. }
  1823. if (isConstant) {
  1824. if (const Expr *Init = VD->getAnyInitializer()) {
  1825. // Look through initializers like const char c[] = { "foo" }
  1826. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  1827. if (InitList->isStringLiteralInit())
  1828. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  1829. }
  1830. return checkFormatStringExpr(S, Init, Args,
  1831. HasVAListArg, format_idx,
  1832. firstDataArg, Type, CallType,
  1833. /*InFunctionCall*/false, CheckedVarArgs);
  1834. }
  1835. }
  1836. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  1837. // special check to see if the format string is a function parameter
  1838. // of the function calling the printf function. If the function
  1839. // has an attribute indicating it is a printf-like function, then we
  1840. // should suppress warnings concerning non-literals being used in a call
  1841. // to a vprintf function. For example:
  1842. //
  1843. // void
  1844. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  1845. // va_list ap;
  1846. // va_start(ap, fmt);
  1847. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  1848. // ...
  1849. // }
  1850. if (HasVAListArg) {
  1851. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  1852. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  1853. int PVIndex = PV->getFunctionScopeIndex() + 1;
  1854. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  1855. // adjust for implicit parameter
  1856. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  1857. if (MD->isInstance())
  1858. ++PVIndex;
  1859. // We also check if the formats are compatible.
  1860. // We can't pass a 'scanf' string to a 'printf' function.
  1861. if (PVIndex == PVFormat->getFormatIdx() &&
  1862. Type == S.GetFormatStringType(PVFormat))
  1863. return SLCT_UncheckedLiteral;
  1864. }
  1865. }
  1866. }
  1867. }
  1868. }
  1869. return SLCT_NotALiteral;
  1870. }
  1871. case Stmt::CallExprClass:
  1872. case Stmt::CXXMemberCallExprClass: {
  1873. const CallExpr *CE = cast<CallExpr>(E);
  1874. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  1875. if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
  1876. unsigned ArgIndex = FA->getFormatIdx();
  1877. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  1878. if (MD->isInstance())
  1879. --ArgIndex;
  1880. const Expr *Arg = CE->getArg(ArgIndex - 1);
  1881. return checkFormatStringExpr(S, Arg, Args,
  1882. HasVAListArg, format_idx, firstDataArg,
  1883. Type, CallType, InFunctionCall,
  1884. CheckedVarArgs);
  1885. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  1886. unsigned BuiltinID = FD->getBuiltinID();
  1887. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  1888. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  1889. const Expr *Arg = CE->getArg(0);
  1890. return checkFormatStringExpr(S, Arg, Args,
  1891. HasVAListArg, format_idx,
  1892. firstDataArg, Type, CallType,
  1893. InFunctionCall, CheckedVarArgs);
  1894. }
  1895. }
  1896. }
  1897. return SLCT_NotALiteral;
  1898. }
  1899. case Stmt::ObjCStringLiteralClass:
  1900. case Stmt::StringLiteralClass: {
  1901. const StringLiteral *StrE = nullptr;
  1902. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  1903. StrE = ObjCFExpr->getString();
  1904. else
  1905. StrE = cast<StringLiteral>(E);
  1906. if (StrE) {
  1907. S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
  1908. Type, InFunctionCall, CallType, CheckedVarArgs);
  1909. return SLCT_CheckedLiteral;
  1910. }
  1911. return SLCT_NotALiteral;
  1912. }
  1913. default:
  1914. return SLCT_NotALiteral;
  1915. }
  1916. }
  1917. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  1918. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  1919. .Case("scanf", FST_Scanf)
  1920. .Cases("printf", "printf0", FST_Printf)
  1921. .Cases("NSString", "CFString", FST_NSString)
  1922. .Case("strftime", FST_Strftime)
  1923. .Case("strfmon", FST_Strfmon)
  1924. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  1925. .Default(FST_Unknown);
  1926. }
  1927. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  1928. /// functions) for correct use of format strings.
  1929. /// Returns true if a format string has been fully checked.
  1930. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  1931. ArrayRef<const Expr *> Args,
  1932. bool IsCXXMember,
  1933. VariadicCallType CallType,
  1934. SourceLocation Loc, SourceRange Range,
  1935. llvm::SmallBitVector &CheckedVarArgs) {
  1936. FormatStringInfo FSI;
  1937. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  1938. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  1939. FSI.FirstDataArg, GetFormatStringType(Format),
  1940. CallType, Loc, Range, CheckedVarArgs);
  1941. return false;
  1942. }
  1943. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  1944. bool HasVAListArg, unsigned format_idx,
  1945. unsigned firstDataArg, FormatStringType Type,
  1946. VariadicCallType CallType,
  1947. SourceLocation Loc, SourceRange Range,
  1948. llvm::SmallBitVector &CheckedVarArgs) {
  1949. // CHECK: printf/scanf-like function is called with no format string.
  1950. if (format_idx >= Args.size()) {
  1951. Diag(Loc, diag::warn_missing_format_string) << Range;
  1952. return false;
  1953. }
  1954. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  1955. // CHECK: format string is not a string literal.
  1956. //
  1957. // Dynamically generated format strings are difficult to
  1958. // automatically vet at compile time. Requiring that format strings
  1959. // are string literals: (1) permits the checking of format strings by
  1960. // the compiler and thereby (2) can practically remove the source of
  1961. // many format string exploits.
  1962. // Format string can be either ObjC string (e.g. @"%d") or
  1963. // C string (e.g. "%d")
  1964. // ObjC string uses the same format specifiers as C string, so we can use
  1965. // the same format string checking logic for both ObjC and C strings.
  1966. StringLiteralCheckType CT =
  1967. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  1968. format_idx, firstDataArg, Type, CallType,
  1969. /*IsFunctionCall*/true, CheckedVarArgs);
  1970. if (CT != SLCT_NotALiteral)
  1971. // Literal format string found, check done!
  1972. return CT == SLCT_CheckedLiteral;
  1973. // Strftime is particular as it always uses a single 'time' argument,
  1974. // so it is safe to pass a non-literal string.
  1975. if (Type == FST_Strftime)
  1976. return false;
  1977. // Do not emit diag when the string param is a macro expansion and the
  1978. // format is either NSString or CFString. This is a hack to prevent
  1979. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  1980. // which are usually used in place of NS and CF string literals.
  1981. if (Type == FST_NSString &&
  1982. SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
  1983. return false;
  1984. // If there are no arguments specified, warn with -Wformat-security, otherwise
  1985. // warn only with -Wformat-nonliteral.
  1986. if (Args.size() == firstDataArg)
  1987. Diag(Args[format_idx]->getLocStart(),
  1988. diag::warn_format_nonliteral_noargs)
  1989. << OrigFormatExpr->getSourceRange();
  1990. else
  1991. Diag(Args[format_idx]->getLocStart(),
  1992. diag::warn_format_nonliteral)
  1993. << OrigFormatExpr->getSourceRange();
  1994. return false;
  1995. }
  1996. namespace {
  1997. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  1998. protected:
  1999. Sema &S;
  2000. const StringLiteral *FExpr;
  2001. const Expr *OrigFormatExpr;
  2002. const unsigned FirstDataArg;
  2003. const unsigned NumDataArgs;
  2004. const char *Beg; // Start of format string.
  2005. const bool HasVAListArg;
  2006. ArrayRef<const Expr *> Args;
  2007. unsigned FormatIdx;
  2008. llvm::SmallBitVector CoveredArgs;
  2009. bool usesPositionalArgs;
  2010. bool atFirstArg;
  2011. bool inFunctionCall;
  2012. Sema::VariadicCallType CallType;
  2013. llvm::SmallBitVector &CheckedVarArgs;
  2014. public:
  2015. CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
  2016. const Expr *origFormatExpr, unsigned firstDataArg,
  2017. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  2018. ArrayRef<const Expr *> Args,
  2019. unsigned formatIdx, bool inFunctionCall,
  2020. Sema::VariadicCallType callType,
  2021. llvm::SmallBitVector &CheckedVarArgs)
  2022. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
  2023. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
  2024. Beg(beg), HasVAListArg(hasVAListArg),
  2025. Args(Args), FormatIdx(formatIdx),
  2026. usesPositionalArgs(false), atFirstArg(true),
  2027. inFunctionCall(inFunctionCall), CallType(callType),
  2028. CheckedVarArgs(CheckedVarArgs) {
  2029. CoveredArgs.resize(numDataArgs);
  2030. CoveredArgs.reset();
  2031. }
  2032. void DoneProcessing();
  2033. void HandleIncompleteSpecifier(const char *startSpecifier,
  2034. unsigned specifierLen) override;
  2035. void HandleInvalidLengthModifier(
  2036. const analyze_format_string::FormatSpecifier &FS,
  2037. const analyze_format_string::ConversionSpecifier &CS,
  2038. const char *startSpecifier, unsigned specifierLen,
  2039. unsigned DiagID);
  2040. void HandleNonStandardLengthModifier(
  2041. const analyze_format_string::FormatSpecifier &FS,
  2042. const char *startSpecifier, unsigned specifierLen);
  2043. void HandleNonStandardConversionSpecifier(
  2044. const analyze_format_string::ConversionSpecifier &CS,
  2045. const char *startSpecifier, unsigned specifierLen);
  2046. void HandlePosition(const char *startPos, unsigned posLen) override;
  2047. void HandleInvalidPosition(const char *startSpecifier,
  2048. unsigned specifierLen,
  2049. analyze_format_string::PositionContext p) override;
  2050. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  2051. void HandleNullChar(const char *nullCharacter) override;
  2052. template <typename Range>
  2053. static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
  2054. const Expr *ArgumentExpr,
  2055. PartialDiagnostic PDiag,
  2056. SourceLocation StringLoc,
  2057. bool IsStringLocation, Range StringRange,
  2058. ArrayRef<FixItHint> Fixit = None);
  2059. protected:
  2060. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  2061. const char *startSpec,
  2062. unsigned specifierLen,
  2063. const char *csStart, unsigned csLen);
  2064. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  2065. const char *startSpec,
  2066. unsigned specifierLen);
  2067. SourceRange getFormatStringRange();
  2068. CharSourceRange getSpecifierRange(const char *startSpecifier,
  2069. unsigned specifierLen);
  2070. SourceLocation getLocationOfByte(const char *x);
  2071. const Expr *getDataArg(unsigned i) const;
  2072. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  2073. const analyze_format_string::ConversionSpecifier &CS,
  2074. const char *startSpecifier, unsigned specifierLen,
  2075. unsigned argIndex);
  2076. template <typename Range>
  2077. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  2078. bool IsStringLocation, Range StringRange,
  2079. ArrayRef<FixItHint> Fixit = None);
  2080. };
  2081. }
  2082. SourceRange CheckFormatHandler::getFormatStringRange() {
  2083. return OrigFormatExpr->getSourceRange();
  2084. }
  2085. CharSourceRange CheckFormatHandler::
  2086. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  2087. SourceLocation Start = getLocationOfByte(startSpecifier);
  2088. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  2089. // Advance the end SourceLocation by one due to half-open ranges.
  2090. End = End.getLocWithOffset(1);
  2091. return CharSourceRange::getCharRange(Start, End);
  2092. }
  2093. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  2094. return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
  2095. }
  2096. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  2097. unsigned specifierLen){
  2098. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  2099. getLocationOfByte(startSpecifier),
  2100. /*IsStringLocation*/true,
  2101. getSpecifierRange(startSpecifier, specifierLen));
  2102. }
  2103. void CheckFormatHandler::HandleInvalidLengthModifier(
  2104. const analyze_format_string::FormatSpecifier &FS,
  2105. const analyze_format_string::ConversionSpecifier &CS,
  2106. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  2107. using namespace analyze_format_string;
  2108. const LengthModifier &LM = FS.getLengthModifier();
  2109. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  2110. // See if we know how to fix this length modifier.
  2111. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  2112. if (FixedLM) {
  2113. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  2114. getLocationOfByte(LM.getStart()),
  2115. /*IsStringLocation*/true,
  2116. getSpecifierRange(startSpecifier, specifierLen));
  2117. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  2118. << FixedLM->toString()
  2119. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  2120. } else {
  2121. FixItHint Hint;
  2122. if (DiagID == diag::warn_format_nonsensical_length)
  2123. Hint = FixItHint::CreateRemoval(LMRange);
  2124. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  2125. getLocationOfByte(LM.getStart()),
  2126. /*IsStringLocation*/true,
  2127. getSpecifierRange(startSpecifier, specifierLen),
  2128. Hint);
  2129. }
  2130. }
  2131. void CheckFormatHandler::HandleNonStandardLengthModifier(
  2132. const analyze_format_string::FormatSpecifier &FS,
  2133. const char *startSpecifier, unsigned specifierLen) {
  2134. using namespace analyze_format_string;
  2135. const LengthModifier &LM = FS.getLengthModifier();
  2136. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  2137. // See if we know how to fix this length modifier.
  2138. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  2139. if (FixedLM) {
  2140. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2141. << LM.toString() << 0,
  2142. getLocationOfByte(LM.getStart()),
  2143. /*IsStringLocation*/true,
  2144. getSpecifierRange(startSpecifier, specifierLen));
  2145. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  2146. << FixedLM->toString()
  2147. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  2148. } else {
  2149. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2150. << LM.toString() << 0,
  2151. getLocationOfByte(LM.getStart()),
  2152. /*IsStringLocation*/true,
  2153. getSpecifierRange(startSpecifier, specifierLen));
  2154. }
  2155. }
  2156. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  2157. const analyze_format_string::ConversionSpecifier &CS,
  2158. const char *startSpecifier, unsigned specifierLen) {
  2159. using namespace analyze_format_string;
  2160. // See if we know how to fix this conversion specifier.
  2161. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  2162. if (FixedCS) {
  2163. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2164. << CS.toString() << /*conversion specifier*/1,
  2165. getLocationOfByte(CS.getStart()),
  2166. /*IsStringLocation*/true,
  2167. getSpecifierRange(startSpecifier, specifierLen));
  2168. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  2169. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  2170. << FixedCS->toString()
  2171. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  2172. } else {
  2173. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2174. << CS.toString() << /*conversion specifier*/1,
  2175. getLocationOfByte(CS.getStart()),
  2176. /*IsStringLocation*/true,
  2177. getSpecifierRange(startSpecifier, specifierLen));
  2178. }
  2179. }
  2180. void CheckFormatHandler::HandlePosition(const char *startPos,
  2181. unsigned posLen) {
  2182. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  2183. getLocationOfByte(startPos),
  2184. /*IsStringLocation*/true,
  2185. getSpecifierRange(startPos, posLen));
  2186. }
  2187. void
  2188. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  2189. analyze_format_string::PositionContext p) {
  2190. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  2191. << (unsigned) p,
  2192. getLocationOfByte(startPos), /*IsStringLocation*/true,
  2193. getSpecifierRange(startPos, posLen));
  2194. }
  2195. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  2196. unsigned posLen) {
  2197. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  2198. getLocationOfByte(startPos),
  2199. /*IsStringLocation*/true,
  2200. getSpecifierRange(startPos, posLen));
  2201. }
  2202. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  2203. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  2204. // The presence of a null character is likely an error.
  2205. EmitFormatDiagnostic(
  2206. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  2207. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  2208. getFormatStringRange());
  2209. }
  2210. }
  2211. // Note that this may return NULL if there was an error parsing or building
  2212. // one of the argument expressions.
  2213. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  2214. return Args[FirstDataArg + i];
  2215. }
  2216. void CheckFormatHandler::DoneProcessing() {
  2217. // Does the number of data arguments exceed the number of
  2218. // format conversions in the format string?
  2219. if (!HasVAListArg) {
  2220. // Find any arguments that weren't covered.
  2221. CoveredArgs.flip();
  2222. signed notCoveredArg = CoveredArgs.find_first();
  2223. if (notCoveredArg >= 0) {
  2224. assert((unsigned)notCoveredArg < NumDataArgs);
  2225. if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
  2226. SourceLocation Loc = E->getLocStart();
  2227. if (!S.getSourceManager().isInSystemMacro(Loc)) {
  2228. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
  2229. Loc, /*IsStringLocation*/false,
  2230. getFormatStringRange());
  2231. }
  2232. }
  2233. }
  2234. }
  2235. }
  2236. bool
  2237. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  2238. SourceLocation Loc,
  2239. const char *startSpec,
  2240. unsigned specifierLen,
  2241. const char *csStart,
  2242. unsigned csLen) {
  2243. bool keepGoing = true;
  2244. if (argIndex < NumDataArgs) {
  2245. // Consider the argument coverered, even though the specifier doesn't
  2246. // make sense.
  2247. CoveredArgs.set(argIndex);
  2248. }
  2249. else {
  2250. // If argIndex exceeds the number of data arguments we
  2251. // don't issue a warning because that is just a cascade of warnings (and
  2252. // they may have intended '%%' anyway). We don't want to continue processing
  2253. // the format string after this point, however, as we will like just get
  2254. // gibberish when trying to match arguments.
  2255. keepGoing = false;
  2256. }
  2257. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
  2258. << StringRef(csStart, csLen),
  2259. Loc, /*IsStringLocation*/true,
  2260. getSpecifierRange(startSpec, specifierLen));
  2261. return keepGoing;
  2262. }
  2263. void
  2264. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  2265. const char *startSpec,
  2266. unsigned specifierLen) {
  2267. EmitFormatDiagnostic(
  2268. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  2269. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  2270. }
  2271. bool
  2272. CheckFormatHandler::CheckNumArgs(
  2273. const analyze_format_string::FormatSpecifier &FS,
  2274. const analyze_format_string::ConversionSpecifier &CS,
  2275. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  2276. if (argIndex >= NumDataArgs) {
  2277. PartialDiagnostic PDiag = FS.usesPositionalArg()
  2278. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  2279. << (argIndex+1) << NumDataArgs)
  2280. : S.PDiag(diag::warn_printf_insufficient_data_args);
  2281. EmitFormatDiagnostic(
  2282. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  2283. getSpecifierRange(startSpecifier, specifierLen));
  2284. return false;
  2285. }
  2286. return true;
  2287. }
  2288. template<typename Range>
  2289. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  2290. SourceLocation Loc,
  2291. bool IsStringLocation,
  2292. Range StringRange,
  2293. ArrayRef<FixItHint> FixIt) {
  2294. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  2295. Loc, IsStringLocation, StringRange, FixIt);
  2296. }
  2297. /// \brief If the format string is not within the funcion call, emit a note
  2298. /// so that the function call and string are in diagnostic messages.
  2299. ///
  2300. /// \param InFunctionCall if true, the format string is within the function
  2301. /// call and only one diagnostic message will be produced. Otherwise, an
  2302. /// extra note will be emitted pointing to location of the format string.
  2303. ///
  2304. /// \param ArgumentExpr the expression that is passed as the format string
  2305. /// argument in the function call. Used for getting locations when two
  2306. /// diagnostics are emitted.
  2307. ///
  2308. /// \param PDiag the callee should already have provided any strings for the
  2309. /// diagnostic message. This function only adds locations and fixits
  2310. /// to diagnostics.
  2311. ///
  2312. /// \param Loc primary location for diagnostic. If two diagnostics are
  2313. /// required, one will be at Loc and a new SourceLocation will be created for
  2314. /// the other one.
  2315. ///
  2316. /// \param IsStringLocation if true, Loc points to the format string should be
  2317. /// used for the note. Otherwise, Loc points to the argument list and will
  2318. /// be used with PDiag.
  2319. ///
  2320. /// \param StringRange some or all of the string to highlight. This is
  2321. /// templated so it can accept either a CharSourceRange or a SourceRange.
  2322. ///
  2323. /// \param FixIt optional fix it hint for the format string.
  2324. template<typename Range>
  2325. void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
  2326. const Expr *ArgumentExpr,
  2327. PartialDiagnostic PDiag,
  2328. SourceLocation Loc,
  2329. bool IsStringLocation,
  2330. Range StringRange,
  2331. ArrayRef<FixItHint> FixIt) {
  2332. if (InFunctionCall) {
  2333. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  2334. D << StringRange;
  2335. for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
  2336. I != E; ++I) {
  2337. D << *I;
  2338. }
  2339. } else {
  2340. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  2341. << ArgumentExpr->getSourceRange();
  2342. const Sema::SemaDiagnosticBuilder &Note =
  2343. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  2344. diag::note_format_string_defined);
  2345. Note << StringRange;
  2346. for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
  2347. I != E; ++I) {
  2348. Note << *I;
  2349. }
  2350. }
  2351. }
  2352. //===--- CHECK: Printf format string checking ------------------------------===//
  2353. namespace {
  2354. class CheckPrintfHandler : public CheckFormatHandler {
  2355. bool ObjCContext;
  2356. public:
  2357. CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
  2358. const Expr *origFormatExpr, unsigned firstDataArg,
  2359. unsigned numDataArgs, bool isObjC,
  2360. const char *beg, bool hasVAListArg,
  2361. ArrayRef<const Expr *> Args,
  2362. unsigned formatIdx, bool inFunctionCall,
  2363. Sema::VariadicCallType CallType,
  2364. llvm::SmallBitVector &CheckedVarArgs)
  2365. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  2366. numDataArgs, beg, hasVAListArg, Args,
  2367. formatIdx, inFunctionCall, CallType, CheckedVarArgs),
  2368. ObjCContext(isObjC)
  2369. {}
  2370. bool HandleInvalidPrintfConversionSpecifier(
  2371. const analyze_printf::PrintfSpecifier &FS,
  2372. const char *startSpecifier,
  2373. unsigned specifierLen) override;
  2374. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  2375. const char *startSpecifier,
  2376. unsigned specifierLen) override;
  2377. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  2378. const char *StartSpecifier,
  2379. unsigned SpecifierLen,
  2380. const Expr *E);
  2381. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  2382. const char *startSpecifier, unsigned specifierLen);
  2383. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  2384. const analyze_printf::OptionalAmount &Amt,
  2385. unsigned type,
  2386. const char *startSpecifier, unsigned specifierLen);
  2387. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  2388. const analyze_printf::OptionalFlag &flag,
  2389. const char *startSpecifier, unsigned specifierLen);
  2390. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  2391. const analyze_printf::OptionalFlag &ignoredFlag,
  2392. const analyze_printf::OptionalFlag &flag,
  2393. const char *startSpecifier, unsigned specifierLen);
  2394. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  2395. const Expr *E);
  2396. };
  2397. }
  2398. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  2399. const analyze_printf::PrintfSpecifier &FS,
  2400. const char *startSpecifier,
  2401. unsigned specifierLen) {
  2402. const analyze_printf::PrintfConversionSpecifier &CS =
  2403. FS.getConversionSpecifier();
  2404. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  2405. getLocationOfByte(CS.getStart()),
  2406. startSpecifier, specifierLen,
  2407. CS.getStart(), CS.getLength());
  2408. }
  2409. bool CheckPrintfHandler::HandleAmount(
  2410. const analyze_format_string::OptionalAmount &Amt,
  2411. unsigned k, const char *startSpecifier,
  2412. unsigned specifierLen) {
  2413. if (Amt.hasDataArgument()) {
  2414. if (!HasVAListArg) {
  2415. unsigned argIndex = Amt.getArgIndex();
  2416. if (argIndex >= NumDataArgs) {
  2417. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  2418. << k,
  2419. getLocationOfByte(Amt.getStart()),
  2420. /*IsStringLocation*/true,
  2421. getSpecifierRange(startSpecifier, specifierLen));
  2422. // Don't do any more checking. We will just emit
  2423. // spurious errors.
  2424. return false;
  2425. }
  2426. // Type check the data argument. It should be an 'int'.
  2427. // Although not in conformance with C99, we also allow the argument to be
  2428. // an 'unsigned int' as that is a reasonably safe case. GCC also
  2429. // doesn't emit a warning for that case.
  2430. CoveredArgs.set(argIndex);
  2431. const Expr *Arg = getDataArg(argIndex);
  2432. if (!Arg)
  2433. return false;
  2434. QualType T = Arg->getType();
  2435. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  2436. assert(AT.isValid());
  2437. if (!AT.matchesType(S.Context, T)) {
  2438. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  2439. << k << AT.getRepresentativeTypeName(S.Context)
  2440. << T << Arg->getSourceRange(),
  2441. getLocationOfByte(Amt.getStart()),
  2442. /*IsStringLocation*/true,
  2443. getSpecifierRange(startSpecifier, specifierLen));
  2444. // Don't do any more checking. We will just emit
  2445. // spurious errors.
  2446. return false;
  2447. }
  2448. }
  2449. }
  2450. return true;
  2451. }
  2452. void CheckPrintfHandler::HandleInvalidAmount(
  2453. const analyze_printf::PrintfSpecifier &FS,
  2454. const analyze_printf::OptionalAmount &Amt,
  2455. unsigned type,
  2456. const char *startSpecifier,
  2457. unsigned specifierLen) {
  2458. const analyze_printf::PrintfConversionSpecifier &CS =
  2459. FS.getConversionSpecifier();
  2460. FixItHint fixit =
  2461. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  2462. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  2463. Amt.getConstantLength()))
  2464. : FixItHint();
  2465. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  2466. << type << CS.toString(),
  2467. getLocationOfByte(Amt.getStart()),
  2468. /*IsStringLocation*/true,
  2469. getSpecifierRange(startSpecifier, specifierLen),
  2470. fixit);
  2471. }
  2472. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  2473. const analyze_printf::OptionalFlag &flag,
  2474. const char *startSpecifier,
  2475. unsigned specifierLen) {
  2476. // Warn about pointless flag with a fixit removal.
  2477. const analyze_printf::PrintfConversionSpecifier &CS =
  2478. FS.getConversionSpecifier();
  2479. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  2480. << flag.toString() << CS.toString(),
  2481. getLocationOfByte(flag.getPosition()),
  2482. /*IsStringLocation*/true,
  2483. getSpecifierRange(startSpecifier, specifierLen),
  2484. FixItHint::CreateRemoval(
  2485. getSpecifierRange(flag.getPosition(), 1)));
  2486. }
  2487. void CheckPrintfHandler::HandleIgnoredFlag(
  2488. const analyze_printf::PrintfSpecifier &FS,
  2489. const analyze_printf::OptionalFlag &ignoredFlag,
  2490. const analyze_printf::OptionalFlag &flag,
  2491. const char *startSpecifier,
  2492. unsigned specifierLen) {
  2493. // Warn about ignored flag with a fixit removal.
  2494. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  2495. << ignoredFlag.toString() << flag.toString(),
  2496. getLocationOfByte(ignoredFlag.getPosition()),
  2497. /*IsStringLocation*/true,
  2498. getSpecifierRange(startSpecifier, specifierLen),
  2499. FixItHint::CreateRemoval(
  2500. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  2501. }
  2502. // Determines if the specified is a C++ class or struct containing
  2503. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  2504. // "c_str()").
  2505. template<typename MemberKind>
  2506. static llvm::SmallPtrSet<MemberKind*, 1>
  2507. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  2508. const RecordType *RT = Ty->getAs<RecordType>();
  2509. llvm::SmallPtrSet<MemberKind*, 1> Results;
  2510. if (!RT)
  2511. return Results;
  2512. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  2513. if (!RD || !RD->getDefinition())
  2514. return Results;
  2515. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  2516. Sema::LookupMemberName);
  2517. R.suppressDiagnostics();
  2518. // We just need to include all members of the right kind turned up by the
  2519. // filter, at this point.
  2520. if (S.LookupQualifiedName(R, RT->getDecl()))
  2521. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2522. NamedDecl *decl = (*I)->getUnderlyingDecl();
  2523. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  2524. Results.insert(FK);
  2525. }
  2526. return Results;
  2527. }
  2528. /// Check if we could call '.c_str()' on an object.
  2529. ///
  2530. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  2531. /// allow the call, or if it would be ambiguous).
  2532. bool Sema::hasCStrMethod(const Expr *E) {
  2533. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  2534. MethodSet Results =
  2535. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  2536. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  2537. MI != ME; ++MI)
  2538. if ((*MI)->getMinRequiredArguments() == 0)
  2539. return true;
  2540. return false;
  2541. }
  2542. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  2543. // better diagnostic if so. AT is assumed to be valid.
  2544. // Returns true when a c_str() conversion method is found.
  2545. bool CheckPrintfHandler::checkForCStrMembers(
  2546. const analyze_printf::ArgType &AT, const Expr *E) {
  2547. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  2548. MethodSet Results =
  2549. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  2550. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  2551. MI != ME; ++MI) {
  2552. const CXXMethodDecl *Method = *MI;
  2553. if (Method->getMinRequiredArguments() == 0 &&
  2554. AT.matchesType(S.Context, Method->getReturnType())) {
  2555. // FIXME: Suggest parens if the expression needs them.
  2556. SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
  2557. S.Diag(E->getLocStart(), diag::note_printf_c_str)
  2558. << "c_str()"
  2559. << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  2560. return true;
  2561. }
  2562. }
  2563. return false;
  2564. }
  2565. bool
  2566. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  2567. &FS,
  2568. const char *startSpecifier,
  2569. unsigned specifierLen) {
  2570. using namespace analyze_format_string;
  2571. using namespace analyze_printf;
  2572. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  2573. if (FS.consumesDataArgument()) {
  2574. if (atFirstArg) {
  2575. atFirstArg = false;
  2576. usesPositionalArgs = FS.usesPositionalArg();
  2577. }
  2578. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  2579. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  2580. startSpecifier, specifierLen);
  2581. return false;
  2582. }
  2583. }
  2584. // First check if the field width, precision, and conversion specifier
  2585. // have matching data arguments.
  2586. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  2587. startSpecifier, specifierLen)) {
  2588. return false;
  2589. }
  2590. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  2591. startSpecifier, specifierLen)) {
  2592. return false;
  2593. }
  2594. if (!CS.consumesDataArgument()) {
  2595. // FIXME: Technically specifying a precision or field width here
  2596. // makes no sense. Worth issuing a warning at some point.
  2597. return true;
  2598. }
  2599. // Consume the argument.
  2600. unsigned argIndex = FS.getArgIndex();
  2601. if (argIndex < NumDataArgs) {
  2602. // The check to see if the argIndex is valid will come later.
  2603. // We set the bit here because we may exit early from this
  2604. // function if we encounter some other error.
  2605. CoveredArgs.set(argIndex);
  2606. }
  2607. // Check for using an Objective-C specific conversion specifier
  2608. // in a non-ObjC literal.
  2609. if (!ObjCContext && CS.isObjCArg()) {
  2610. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  2611. specifierLen);
  2612. }
  2613. // Check for invalid use of field width
  2614. if (!FS.hasValidFieldWidth()) {
  2615. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  2616. startSpecifier, specifierLen);
  2617. }
  2618. // Check for invalid use of precision
  2619. if (!FS.hasValidPrecision()) {
  2620. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  2621. startSpecifier, specifierLen);
  2622. }
  2623. // Check each flag does not conflict with any other component.
  2624. if (!FS.hasValidThousandsGroupingPrefix())
  2625. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  2626. if (!FS.hasValidLeadingZeros())
  2627. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  2628. if (!FS.hasValidPlusPrefix())
  2629. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  2630. if (!FS.hasValidSpacePrefix())
  2631. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  2632. if (!FS.hasValidAlternativeForm())
  2633. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  2634. if (!FS.hasValidLeftJustified())
  2635. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  2636. // Check that flags are not ignored by another flag
  2637. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  2638. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  2639. startSpecifier, specifierLen);
  2640. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  2641. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  2642. startSpecifier, specifierLen);
  2643. // Check the length modifier is valid with the given conversion specifier.
  2644. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  2645. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  2646. diag::warn_format_nonsensical_length);
  2647. else if (!FS.hasStandardLengthModifier())
  2648. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  2649. else if (!FS.hasStandardLengthConversionCombination())
  2650. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  2651. diag::warn_format_non_standard_conversion_spec);
  2652. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  2653. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  2654. // The remaining checks depend on the data arguments.
  2655. if (HasVAListArg)
  2656. return true;
  2657. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  2658. return false;
  2659. const Expr *Arg = getDataArg(argIndex);
  2660. if (!Arg)
  2661. return true;
  2662. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  2663. }
  2664. static bool requiresParensToAddCast(const Expr *E) {
  2665. // FIXME: We should have a general way to reason about operator
  2666. // precedence and whether parens are actually needed here.
  2667. // Take care of a few common cases where they aren't.
  2668. const Expr *Inside = E->IgnoreImpCasts();
  2669. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  2670. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  2671. switch (Inside->getStmtClass()) {
  2672. case Stmt::ArraySubscriptExprClass:
  2673. case Stmt::CallExprClass:
  2674. case Stmt::CharacterLiteralClass:
  2675. case Stmt::CXXBoolLiteralExprClass:
  2676. case Stmt::DeclRefExprClass:
  2677. case Stmt::FloatingLiteralClass:
  2678. case Stmt::IntegerLiteralClass:
  2679. case Stmt::MemberExprClass:
  2680. case Stmt::ObjCArrayLiteralClass:
  2681. case Stmt::ObjCBoolLiteralExprClass:
  2682. case Stmt::ObjCBoxedExprClass:
  2683. case Stmt::ObjCDictionaryLiteralClass:
  2684. case Stmt::ObjCEncodeExprClass:
  2685. case Stmt::ObjCIvarRefExprClass:
  2686. case Stmt::ObjCMessageExprClass:
  2687. case Stmt::ObjCPropertyRefExprClass:
  2688. case Stmt::ObjCStringLiteralClass:
  2689. case Stmt::ObjCSubscriptRefExprClass:
  2690. case Stmt::ParenExprClass:
  2691. case Stmt::StringLiteralClass:
  2692. case Stmt::UnaryOperatorClass:
  2693. return false;
  2694. default:
  2695. return true;
  2696. }
  2697. }
  2698. bool
  2699. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  2700. const char *StartSpecifier,
  2701. unsigned SpecifierLen,
  2702. const Expr *E) {
  2703. using namespace analyze_format_string;
  2704. using namespace analyze_printf;
  2705. // Now type check the data expression that matches the
  2706. // format specifier.
  2707. const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
  2708. ObjCContext);
  2709. if (!AT.isValid())
  2710. return true;
  2711. QualType ExprTy = E->getType();
  2712. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  2713. ExprTy = TET->getUnderlyingExpr()->getType();
  2714. }
  2715. if (AT.matchesType(S.Context, ExprTy))
  2716. return true;
  2717. // Look through argument promotions for our error message's reported type.
  2718. // This includes the integral and floating promotions, but excludes array
  2719. // and function pointer decay; seeing that an argument intended to be a
  2720. // string has type 'char [6]' is probably more confusing than 'char *'.
  2721. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  2722. if (ICE->getCastKind() == CK_IntegralCast ||
  2723. ICE->getCastKind() == CK_FloatingCast) {
  2724. E = ICE->getSubExpr();
  2725. ExprTy = E->getType();
  2726. // Check if we didn't match because of an implicit cast from a 'char'
  2727. // or 'short' to an 'int'. This is done because printf is a varargs
  2728. // function.
  2729. if (ICE->getType() == S.Context.IntTy ||
  2730. ICE->getType() == S.Context.UnsignedIntTy) {
  2731. // All further checking is done on the subexpression.
  2732. if (AT.matchesType(S.Context, ExprTy))
  2733. return true;
  2734. }
  2735. }
  2736. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  2737. // Special case for 'a', which has type 'int' in C.
  2738. // Note, however, that we do /not/ want to treat multibyte constants like
  2739. // 'MooV' as characters! This form is deprecated but still exists.
  2740. if (ExprTy == S.Context.IntTy)
  2741. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  2742. ExprTy = S.Context.CharTy;
  2743. }
  2744. // %C in an Objective-C context prints a unichar, not a wchar_t.
  2745. // If the argument is an integer of some kind, believe the %C and suggest
  2746. // a cast instead of changing the conversion specifier.
  2747. QualType IntendedTy = ExprTy;
  2748. if (ObjCContext &&
  2749. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  2750. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  2751. !ExprTy->isCharType()) {
  2752. // 'unichar' is defined as a typedef of unsigned short, but we should
  2753. // prefer using the typedef if it is visible.
  2754. IntendedTy = S.Context.UnsignedShortTy;
  2755. // While we are here, check if the value is an IntegerLiteral that happens
  2756. // to be within the valid range.
  2757. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  2758. const llvm::APInt &V = IL->getValue();
  2759. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  2760. return true;
  2761. }
  2762. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
  2763. Sema::LookupOrdinaryName);
  2764. if (S.LookupName(Result, S.getCurScope())) {
  2765. NamedDecl *ND = Result.getFoundDecl();
  2766. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  2767. if (TD->getUnderlyingType() == IntendedTy)
  2768. IntendedTy = S.Context.getTypedefType(TD);
  2769. }
  2770. }
  2771. }
  2772. // Special-case some of Darwin's platform-independence types by suggesting
  2773. // casts to primitive types that are known to be large enough.
  2774. bool ShouldNotPrintDirectly = false;
  2775. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  2776. // Use a 'while' to peel off layers of typedefs.
  2777. QualType TyTy = IntendedTy;
  2778. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  2779. StringRef Name = UserTy->getDecl()->getName();
  2780. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  2781. .Case("NSInteger", S.Context.LongTy)
  2782. .Case("NSUInteger", S.Context.UnsignedLongTy)
  2783. .Case("SInt32", S.Context.IntTy)
  2784. .Case("UInt32", S.Context.UnsignedIntTy)
  2785. .Default(QualType());
  2786. if (!CastTy.isNull()) {
  2787. ShouldNotPrintDirectly = true;
  2788. IntendedTy = CastTy;
  2789. break;
  2790. }
  2791. TyTy = UserTy->desugar();
  2792. }
  2793. }
  2794. // We may be able to offer a FixItHint if it is a supported type.
  2795. PrintfSpecifier fixedFS = FS;
  2796. bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
  2797. S.Context, ObjCContext);
  2798. if (success) {
  2799. // Get the fix string from the fixed format specifier
  2800. SmallString<16> buf;
  2801. llvm::raw_svector_ostream os(buf);
  2802. fixedFS.toString(os);
  2803. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  2804. if (IntendedTy == ExprTy) {
  2805. // In this case, the specifier is wrong and should be changed to match
  2806. // the argument.
  2807. EmitFormatDiagnostic(
  2808. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2809. << AT.getRepresentativeTypeName(S.Context) << IntendedTy
  2810. << E->getSourceRange(),
  2811. E->getLocStart(),
  2812. /*IsStringLocation*/false,
  2813. SpecRange,
  2814. FixItHint::CreateReplacement(SpecRange, os.str()));
  2815. } else {
  2816. // The canonical type for formatting this value is different from the
  2817. // actual type of the expression. (This occurs, for example, with Darwin's
  2818. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  2819. // should be printed as 'long' for 64-bit compatibility.)
  2820. // Rather than emitting a normal format/argument mismatch, we want to
  2821. // add a cast to the recommended type (and correct the format string
  2822. // if necessary).
  2823. SmallString<16> CastBuf;
  2824. llvm::raw_svector_ostream CastFix(CastBuf);
  2825. CastFix << "(";
  2826. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  2827. CastFix << ")";
  2828. SmallVector<FixItHint,4> Hints;
  2829. if (!AT.matchesType(S.Context, IntendedTy))
  2830. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  2831. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  2832. // If there's already a cast present, just replace it.
  2833. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  2834. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  2835. } else if (!requiresParensToAddCast(E)) {
  2836. // If the expression has high enough precedence,
  2837. // just write the C-style cast.
  2838. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  2839. CastFix.str()));
  2840. } else {
  2841. // Otherwise, add parens around the expression as well as the cast.
  2842. CastFix << "(";
  2843. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  2844. CastFix.str()));
  2845. SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
  2846. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  2847. }
  2848. if (ShouldNotPrintDirectly) {
  2849. // The expression has a type that should not be printed directly.
  2850. // We extract the name from the typedef because we don't want to show
  2851. // the underlying type in the diagnostic.
  2852. StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
  2853. EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
  2854. << Name << IntendedTy
  2855. << E->getSourceRange(),
  2856. E->getLocStart(), /*IsStringLocation=*/false,
  2857. SpecRange, Hints);
  2858. } else {
  2859. // In this case, the expression could be printed using a different
  2860. // specifier, but we've decided that the specifier is probably correct
  2861. // and we should cast instead. Just use the normal warning message.
  2862. EmitFormatDiagnostic(
  2863. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2864. << AT.getRepresentativeTypeName(S.Context) << ExprTy
  2865. << E->getSourceRange(),
  2866. E->getLocStart(), /*IsStringLocation*/false,
  2867. SpecRange, Hints);
  2868. }
  2869. }
  2870. } else {
  2871. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  2872. SpecifierLen);
  2873. // Since the warning for passing non-POD types to variadic functions
  2874. // was deferred until now, we emit a warning for non-POD
  2875. // arguments here.
  2876. switch (S.isValidVarArgType(ExprTy)) {
  2877. case Sema::VAK_Valid:
  2878. case Sema::VAK_ValidInCXX11:
  2879. EmitFormatDiagnostic(
  2880. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2881. << AT.getRepresentativeTypeName(S.Context) << ExprTy
  2882. << CSR
  2883. << E->getSourceRange(),
  2884. E->getLocStart(), /*IsStringLocation*/false, CSR);
  2885. break;
  2886. case Sema::VAK_Undefined:
  2887. EmitFormatDiagnostic(
  2888. S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  2889. << S.getLangOpts().CPlusPlus11
  2890. << ExprTy
  2891. << CallType
  2892. << AT.getRepresentativeTypeName(S.Context)
  2893. << CSR
  2894. << E->getSourceRange(),
  2895. E->getLocStart(), /*IsStringLocation*/false, CSR);
  2896. checkForCStrMembers(AT, E);
  2897. break;
  2898. case Sema::VAK_Invalid:
  2899. if (ExprTy->isObjCObjectType())
  2900. EmitFormatDiagnostic(
  2901. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  2902. << S.getLangOpts().CPlusPlus11
  2903. << ExprTy
  2904. << CallType
  2905. << AT.getRepresentativeTypeName(S.Context)
  2906. << CSR
  2907. << E->getSourceRange(),
  2908. E->getLocStart(), /*IsStringLocation*/false, CSR);
  2909. else
  2910. // FIXME: If this is an initializer list, suggest removing the braces
  2911. // or inserting a cast to the target type.
  2912. S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
  2913. << isa<InitListExpr>(E) << ExprTy << CallType
  2914. << AT.getRepresentativeTypeName(S.Context)
  2915. << E->getSourceRange();
  2916. break;
  2917. }
  2918. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  2919. "format string specifier index out of range");
  2920. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  2921. }
  2922. return true;
  2923. }
  2924. //===--- CHECK: Scanf format string checking ------------------------------===//
  2925. namespace {
  2926. class CheckScanfHandler : public CheckFormatHandler {
  2927. public:
  2928. CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
  2929. const Expr *origFormatExpr, unsigned firstDataArg,
  2930. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  2931. ArrayRef<const Expr *> Args,
  2932. unsigned formatIdx, bool inFunctionCall,
  2933. Sema::VariadicCallType CallType,
  2934. llvm::SmallBitVector &CheckedVarArgs)
  2935. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  2936. numDataArgs, beg, hasVAListArg,
  2937. Args, formatIdx, inFunctionCall, CallType,
  2938. CheckedVarArgs)
  2939. {}
  2940. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  2941. const char *startSpecifier,
  2942. unsigned specifierLen) override;
  2943. bool HandleInvalidScanfConversionSpecifier(
  2944. const analyze_scanf::ScanfSpecifier &FS,
  2945. const char *startSpecifier,
  2946. unsigned specifierLen) override;
  2947. void HandleIncompleteScanList(const char *start, const char *end) override;
  2948. };
  2949. }
  2950. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  2951. const char *end) {
  2952. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  2953. getLocationOfByte(end), /*IsStringLocation*/true,
  2954. getSpecifierRange(start, end - start));
  2955. }
  2956. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  2957. const analyze_scanf::ScanfSpecifier &FS,
  2958. const char *startSpecifier,
  2959. unsigned specifierLen) {
  2960. const analyze_scanf::ScanfConversionSpecifier &CS =
  2961. FS.getConversionSpecifier();
  2962. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  2963. getLocationOfByte(CS.getStart()),
  2964. startSpecifier, specifierLen,
  2965. CS.getStart(), CS.getLength());
  2966. }
  2967. bool CheckScanfHandler::HandleScanfSpecifier(
  2968. const analyze_scanf::ScanfSpecifier &FS,
  2969. const char *startSpecifier,
  2970. unsigned specifierLen) {
  2971. using namespace analyze_scanf;
  2972. using namespace analyze_format_string;
  2973. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  2974. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  2975. // be used to decide if we are using positional arguments consistently.
  2976. if (FS.consumesDataArgument()) {
  2977. if (atFirstArg) {
  2978. atFirstArg = false;
  2979. usesPositionalArgs = FS.usesPositionalArg();
  2980. }
  2981. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  2982. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  2983. startSpecifier, specifierLen);
  2984. return false;
  2985. }
  2986. }
  2987. // Check if the field with is non-zero.
  2988. const OptionalAmount &Amt = FS.getFieldWidth();
  2989. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  2990. if (Amt.getConstantAmount() == 0) {
  2991. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  2992. Amt.getConstantLength());
  2993. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  2994. getLocationOfByte(Amt.getStart()),
  2995. /*IsStringLocation*/true, R,
  2996. FixItHint::CreateRemoval(R));
  2997. }
  2998. }
  2999. if (!FS.consumesDataArgument()) {
  3000. // FIXME: Technically specifying a precision or field width here
  3001. // makes no sense. Worth issuing a warning at some point.
  3002. return true;
  3003. }
  3004. // Consume the argument.
  3005. unsigned argIndex = FS.getArgIndex();
  3006. if (argIndex < NumDataArgs) {
  3007. // The check to see if the argIndex is valid will come later.
  3008. // We set the bit here because we may exit early from this
  3009. // function if we encounter some other error.
  3010. CoveredArgs.set(argIndex);
  3011. }
  3012. // Check the length modifier is valid with the given conversion specifier.
  3013. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  3014. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3015. diag::warn_format_nonsensical_length);
  3016. else if (!FS.hasStandardLengthModifier())
  3017. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  3018. else if (!FS.hasStandardLengthConversionCombination())
  3019. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3020. diag::warn_format_non_standard_conversion_spec);
  3021. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  3022. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  3023. // The remaining checks depend on the data arguments.
  3024. if (HasVAListArg)
  3025. return true;
  3026. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  3027. return false;
  3028. // Check that the argument type matches the format specifier.
  3029. const Expr *Ex = getDataArg(argIndex);
  3030. if (!Ex)
  3031. return true;
  3032. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  3033. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
  3034. ScanfSpecifier fixedFS = FS;
  3035. bool success = fixedFS.fixType(Ex->getType(),
  3036. Ex->IgnoreImpCasts()->getType(),
  3037. S.getLangOpts(), S.Context);
  3038. if (success) {
  3039. // Get the fix string from the fixed format specifier.
  3040. SmallString<128> buf;
  3041. llvm::raw_svector_ostream os(buf);
  3042. fixedFS.toString(os);
  3043. EmitFormatDiagnostic(
  3044. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  3045. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  3046. << Ex->getSourceRange(),
  3047. Ex->getLocStart(),
  3048. /*IsStringLocation*/false,
  3049. getSpecifierRange(startSpecifier, specifierLen),
  3050. FixItHint::CreateReplacement(
  3051. getSpecifierRange(startSpecifier, specifierLen),
  3052. os.str()));
  3053. } else {
  3054. EmitFormatDiagnostic(
  3055. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  3056. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  3057. << Ex->getSourceRange(),
  3058. Ex->getLocStart(),
  3059. /*IsStringLocation*/false,
  3060. getSpecifierRange(startSpecifier, specifierLen));
  3061. }
  3062. }
  3063. return true;
  3064. }
  3065. void Sema::CheckFormatString(const StringLiteral *FExpr,
  3066. const Expr *OrigFormatExpr,
  3067. ArrayRef<const Expr *> Args,
  3068. bool HasVAListArg, unsigned format_idx,
  3069. unsigned firstDataArg, FormatStringType Type,
  3070. bool inFunctionCall, VariadicCallType CallType,
  3071. llvm::SmallBitVector &CheckedVarArgs) {
  3072. // CHECK: is the format string a wide literal?
  3073. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  3074. CheckFormatHandler::EmitFormatDiagnostic(
  3075. *this, inFunctionCall, Args[format_idx],
  3076. PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  3077. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  3078. return;
  3079. }
  3080. // Str - The format string. NOTE: this is NOT null-terminated!
  3081. StringRef StrRef = FExpr->getString();
  3082. const char *Str = StrRef.data();
  3083. // Account for cases where the string literal is truncated in a declaration.
  3084. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  3085. assert(T && "String literal not of constant array type!");
  3086. size_t TypeSize = T->getSize().getZExtValue();
  3087. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  3088. const unsigned numDataArgs = Args.size() - firstDataArg;
  3089. // Emit a warning if the string literal is truncated and does not contain an
  3090. // embedded null character.
  3091. if (TypeSize <= StrRef.size() &&
  3092. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  3093. CheckFormatHandler::EmitFormatDiagnostic(
  3094. *this, inFunctionCall, Args[format_idx],
  3095. PDiag(diag::warn_printf_format_string_not_null_terminated),
  3096. FExpr->getLocStart(),
  3097. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  3098. return;
  3099. }
  3100. // CHECK: empty format string?
  3101. if (StrLen == 0 && numDataArgs > 0) {
  3102. CheckFormatHandler::EmitFormatDiagnostic(
  3103. *this, inFunctionCall, Args[format_idx],
  3104. PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  3105. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  3106. return;
  3107. }
  3108. if (Type == FST_Printf || Type == FST_NSString) {
  3109. CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
  3110. numDataArgs, (Type == FST_NSString),
  3111. Str, HasVAListArg, Args, format_idx,
  3112. inFunctionCall, CallType, CheckedVarArgs);
  3113. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  3114. getLangOpts(),
  3115. Context.getTargetInfo()))
  3116. H.DoneProcessing();
  3117. } else if (Type == FST_Scanf) {
  3118. CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
  3119. Str, HasVAListArg, Args, format_idx,
  3120. inFunctionCall, CallType, CheckedVarArgs);
  3121. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  3122. getLangOpts(),
  3123. Context.getTargetInfo()))
  3124. H.DoneProcessing();
  3125. } // TODO: handle other formats
  3126. }
  3127. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  3128. // Returns the related absolute value function that is larger, of 0 if one
  3129. // does not exist.
  3130. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  3131. switch (AbsFunction) {
  3132. default:
  3133. return 0;
  3134. case Builtin::BI__builtin_abs:
  3135. return Builtin::BI__builtin_labs;
  3136. case Builtin::BI__builtin_labs:
  3137. return Builtin::BI__builtin_llabs;
  3138. case Builtin::BI__builtin_llabs:
  3139. return 0;
  3140. case Builtin::BI__builtin_fabsf:
  3141. return Builtin::BI__builtin_fabs;
  3142. case Builtin::BI__builtin_fabs:
  3143. return Builtin::BI__builtin_fabsl;
  3144. case Builtin::BI__builtin_fabsl:
  3145. return 0;
  3146. case Builtin::BI__builtin_cabsf:
  3147. return Builtin::BI__builtin_cabs;
  3148. case Builtin::BI__builtin_cabs:
  3149. return Builtin::BI__builtin_cabsl;
  3150. case Builtin::BI__builtin_cabsl:
  3151. return 0;
  3152. case Builtin::BIabs:
  3153. return Builtin::BIlabs;
  3154. case Builtin::BIlabs:
  3155. return Builtin::BIllabs;
  3156. case Builtin::BIllabs:
  3157. return 0;
  3158. case Builtin::BIfabsf:
  3159. return Builtin::BIfabs;
  3160. case Builtin::BIfabs:
  3161. return Builtin::BIfabsl;
  3162. case Builtin::BIfabsl:
  3163. return 0;
  3164. case Builtin::BIcabsf:
  3165. return Builtin::BIcabs;
  3166. case Builtin::BIcabs:
  3167. return Builtin::BIcabsl;
  3168. case Builtin::BIcabsl:
  3169. return 0;
  3170. }
  3171. }
  3172. // Returns the argument type of the absolute value function.
  3173. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  3174. unsigned AbsType) {
  3175. if (AbsType == 0)
  3176. return QualType();
  3177. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  3178. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  3179. if (Error != ASTContext::GE_None)
  3180. return QualType();
  3181. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  3182. if (!FT)
  3183. return QualType();
  3184. if (FT->getNumParams() != 1)
  3185. return QualType();
  3186. return FT->getParamType(0);
  3187. }
  3188. // Returns the best absolute value function, or zero, based on type and
  3189. // current absolute value function.
  3190. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  3191. unsigned AbsFunctionKind) {
  3192. unsigned BestKind = 0;
  3193. uint64_t ArgSize = Context.getTypeSize(ArgType);
  3194. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  3195. Kind = getLargerAbsoluteValueFunction(Kind)) {
  3196. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  3197. if (Context.getTypeSize(ParamType) >= ArgSize) {
  3198. if (BestKind == 0)
  3199. BestKind = Kind;
  3200. else if (Context.hasSameType(ParamType, ArgType)) {
  3201. BestKind = Kind;
  3202. break;
  3203. }
  3204. }
  3205. }
  3206. return BestKind;
  3207. }
  3208. enum AbsoluteValueKind {
  3209. AVK_Integer,
  3210. AVK_Floating,
  3211. AVK_Complex
  3212. };
  3213. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  3214. if (T->isIntegralOrEnumerationType())
  3215. return AVK_Integer;
  3216. if (T->isRealFloatingType())
  3217. return AVK_Floating;
  3218. if (T->isAnyComplexType())
  3219. return AVK_Complex;
  3220. llvm_unreachable("Type not integer, floating, or complex");
  3221. }
  3222. // Changes the absolute value function to a different type. Preserves whether
  3223. // the function is a builtin.
  3224. static unsigned changeAbsFunction(unsigned AbsKind,
  3225. AbsoluteValueKind ValueKind) {
  3226. switch (ValueKind) {
  3227. case AVK_Integer:
  3228. switch (AbsKind) {
  3229. default:
  3230. return 0;
  3231. case Builtin::BI__builtin_fabsf:
  3232. case Builtin::BI__builtin_fabs:
  3233. case Builtin::BI__builtin_fabsl:
  3234. case Builtin::BI__builtin_cabsf:
  3235. case Builtin::BI__builtin_cabs:
  3236. case Builtin::BI__builtin_cabsl:
  3237. return Builtin::BI__builtin_abs;
  3238. case Builtin::BIfabsf:
  3239. case Builtin::BIfabs:
  3240. case Builtin::BIfabsl:
  3241. case Builtin::BIcabsf:
  3242. case Builtin::BIcabs:
  3243. case Builtin::BIcabsl:
  3244. return Builtin::BIabs;
  3245. }
  3246. case AVK_Floating:
  3247. switch (AbsKind) {
  3248. default:
  3249. return 0;
  3250. case Builtin::BI__builtin_abs:
  3251. case Builtin::BI__builtin_labs:
  3252. case Builtin::BI__builtin_llabs:
  3253. case Builtin::BI__builtin_cabsf:
  3254. case Builtin::BI__builtin_cabs:
  3255. case Builtin::BI__builtin_cabsl:
  3256. return Builtin::BI__builtin_fabsf;
  3257. case Builtin::BIabs:
  3258. case Builtin::BIlabs:
  3259. case Builtin::BIllabs:
  3260. case Builtin::BIcabsf:
  3261. case Builtin::BIcabs:
  3262. case Builtin::BIcabsl:
  3263. return Builtin::BIfabsf;
  3264. }
  3265. case AVK_Complex:
  3266. switch (AbsKind) {
  3267. default:
  3268. return 0;
  3269. case Builtin::BI__builtin_abs:
  3270. case Builtin::BI__builtin_labs:
  3271. case Builtin::BI__builtin_llabs:
  3272. case Builtin::BI__builtin_fabsf:
  3273. case Builtin::BI__builtin_fabs:
  3274. case Builtin::BI__builtin_fabsl:
  3275. return Builtin::BI__builtin_cabsf;
  3276. case Builtin::BIabs:
  3277. case Builtin::BIlabs:
  3278. case Builtin::BIllabs:
  3279. case Builtin::BIfabsf:
  3280. case Builtin::BIfabs:
  3281. case Builtin::BIfabsl:
  3282. return Builtin::BIcabsf;
  3283. }
  3284. }
  3285. llvm_unreachable("Unable to convert function");
  3286. }
  3287. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  3288. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  3289. if (!FnInfo)
  3290. return 0;
  3291. switch (FDecl->getBuiltinID()) {
  3292. default:
  3293. return 0;
  3294. case Builtin::BI__builtin_abs:
  3295. case Builtin::BI__builtin_fabs:
  3296. case Builtin::BI__builtin_fabsf:
  3297. case Builtin::BI__builtin_fabsl:
  3298. case Builtin::BI__builtin_labs:
  3299. case Builtin::BI__builtin_llabs:
  3300. case Builtin::BI__builtin_cabs:
  3301. case Builtin::BI__builtin_cabsf:
  3302. case Builtin::BI__builtin_cabsl:
  3303. case Builtin::BIabs:
  3304. case Builtin::BIlabs:
  3305. case Builtin::BIllabs:
  3306. case Builtin::BIfabs:
  3307. case Builtin::BIfabsf:
  3308. case Builtin::BIfabsl:
  3309. case Builtin::BIcabs:
  3310. case Builtin::BIcabsf:
  3311. case Builtin::BIcabsl:
  3312. return FDecl->getBuiltinID();
  3313. }
  3314. llvm_unreachable("Unknown Builtin type");
  3315. }
  3316. // If the replacement is valid, emit a note with replacement function.
  3317. // Additionally, suggest including the proper header if not already included.
  3318. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  3319. unsigned AbsKind, QualType ArgType) {
  3320. bool EmitHeaderHint = true;
  3321. const char *HeaderName = nullptr;
  3322. const char *FunctionName = nullptr;
  3323. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  3324. FunctionName = "std::abs";
  3325. if (ArgType->isIntegralOrEnumerationType()) {
  3326. HeaderName = "cstdlib";
  3327. } else if (ArgType->isRealFloatingType()) {
  3328. HeaderName = "cmath";
  3329. } else {
  3330. llvm_unreachable("Invalid Type");
  3331. }
  3332. // Lookup all std::abs
  3333. if (NamespaceDecl *Std = S.getStdNamespace()) {
  3334. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  3335. R.suppressDiagnostics();
  3336. S.LookupQualifiedName(R, Std);
  3337. for (const auto *I : R) {
  3338. const FunctionDecl *FDecl = nullptr;
  3339. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  3340. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  3341. } else {
  3342. FDecl = dyn_cast<FunctionDecl>(I);
  3343. }
  3344. if (!FDecl)
  3345. continue;
  3346. // Found std::abs(), check that they are the right ones.
  3347. if (FDecl->getNumParams() != 1)
  3348. continue;
  3349. // Check that the parameter type can handle the argument.
  3350. QualType ParamType = FDecl->getParamDecl(0)->getType();
  3351. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  3352. S.Context.getTypeSize(ArgType) <=
  3353. S.Context.getTypeSize(ParamType)) {
  3354. // Found a function, don't need the header hint.
  3355. EmitHeaderHint = false;
  3356. break;
  3357. }
  3358. }
  3359. }
  3360. } else {
  3361. FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
  3362. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  3363. if (HeaderName) {
  3364. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  3365. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  3366. R.suppressDiagnostics();
  3367. S.LookupName(R, S.getCurScope());
  3368. if (R.isSingleResult()) {
  3369. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  3370. if (FD && FD->getBuiltinID() == AbsKind) {
  3371. EmitHeaderHint = false;
  3372. } else {
  3373. return;
  3374. }
  3375. } else if (!R.empty()) {
  3376. return;
  3377. }
  3378. }
  3379. }
  3380. S.Diag(Loc, diag::note_replace_abs_function)
  3381. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  3382. if (!HeaderName)
  3383. return;
  3384. if (!EmitHeaderHint)
  3385. return;
  3386. S.Diag(Loc, diag::note_please_include_header) << HeaderName << FunctionName;
  3387. }
  3388. static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
  3389. if (!FDecl)
  3390. return false;
  3391. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
  3392. return false;
  3393. const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
  3394. while (ND && ND->isInlineNamespace()) {
  3395. ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
  3396. }
  3397. if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
  3398. return false;
  3399. if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
  3400. return false;
  3401. return true;
  3402. }
  3403. // Warn when using the wrong abs() function.
  3404. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  3405. const FunctionDecl *FDecl,
  3406. IdentifierInfo *FnInfo) {
  3407. if (Call->getNumArgs() != 1)
  3408. return;
  3409. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  3410. bool IsStdAbs = IsFunctionStdAbs(FDecl);
  3411. if (AbsKind == 0 && !IsStdAbs)
  3412. return;
  3413. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  3414. QualType ParamType = Call->getArg(0)->getType();
  3415. // Unsigned types can not be negative. Suggest to drop the absolute value
  3416. // function.
  3417. if (ArgType->isUnsignedIntegerType()) {
  3418. const char *FunctionName =
  3419. IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
  3420. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  3421. Diag(Call->getExprLoc(), diag::note_remove_abs)
  3422. << FunctionName
  3423. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  3424. return;
  3425. }
  3426. // std::abs has overloads which prevent most of the absolute value problems
  3427. // from occurring.
  3428. if (IsStdAbs)
  3429. return;
  3430. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  3431. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  3432. // The argument and parameter are the same kind. Check if they are the right
  3433. // size.
  3434. if (ArgValueKind == ParamValueKind) {
  3435. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  3436. return;
  3437. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  3438. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  3439. << FDecl << ArgType << ParamType;
  3440. if (NewAbsKind == 0)
  3441. return;
  3442. emitReplacement(*this, Call->getExprLoc(),
  3443. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  3444. return;
  3445. }
  3446. // ArgValueKind != ParamValueKind
  3447. // The wrong type of absolute value function was used. Attempt to find the
  3448. // proper one.
  3449. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  3450. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  3451. if (NewAbsKind == 0)
  3452. return;
  3453. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  3454. << FDecl << ParamValueKind << ArgValueKind;
  3455. emitReplacement(*this, Call->getExprLoc(),
  3456. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  3457. return;
  3458. }
  3459. //===--- CHECK: Standard memory functions ---------------------------------===//
  3460. /// \brief Takes the expression passed to the size_t parameter of functions
  3461. /// such as memcmp, strncat, etc and warns if it's a comparison.
  3462. ///
  3463. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  3464. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  3465. IdentifierInfo *FnName,
  3466. SourceLocation FnLoc,
  3467. SourceLocation RParenLoc) {
  3468. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  3469. if (!Size)
  3470. return false;
  3471. // if E is binop and op is >, <, >=, <=, ==, &&, ||:
  3472. if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
  3473. return false;
  3474. SourceRange SizeRange = Size->getSourceRange();
  3475. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  3476. << SizeRange << FnName;
  3477. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  3478. << FnName << FixItHint::CreateInsertion(
  3479. S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
  3480. << FixItHint::CreateRemoval(RParenLoc);
  3481. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  3482. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  3483. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  3484. ")");
  3485. return true;
  3486. }
  3487. /// \brief Determine whether the given type is a dynamic class type (e.g.,
  3488. /// whether it has a vtable).
  3489. static bool isDynamicClassType(QualType T) {
  3490. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
  3491. if (CXXRecordDecl *Definition = Record->getDefinition())
  3492. if (Definition->isDynamicClass())
  3493. return true;
  3494. return false;
  3495. }
  3496. /// \brief If E is a sizeof expression, returns its argument expression,
  3497. /// otherwise returns NULL.
  3498. static const Expr *getSizeOfExprArg(const Expr* E) {
  3499. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  3500. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  3501. if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
  3502. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  3503. return nullptr;
  3504. }
  3505. /// \brief If E is a sizeof expression, returns its argument type.
  3506. static QualType getSizeOfArgType(const Expr* E) {
  3507. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  3508. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  3509. if (SizeOf->getKind() == clang::UETT_SizeOf)
  3510. return SizeOf->getTypeOfArgument();
  3511. return QualType();
  3512. }
  3513. /// \brief Check for dangerous or invalid arguments to memset().
  3514. ///
  3515. /// This issues warnings on known problematic, dangerous or unspecified
  3516. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  3517. /// function calls.
  3518. ///
  3519. /// \param Call The call expression to diagnose.
  3520. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  3521. unsigned BId,
  3522. IdentifierInfo *FnName) {
  3523. assert(BId != 0);
  3524. // It is possible to have a non-standard definition of memset. Validate
  3525. // we have enough arguments, and if not, abort further checking.
  3526. unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
  3527. if (Call->getNumArgs() < ExpectedNumArgs)
  3528. return;
  3529. unsigned LastArg = (BId == Builtin::BImemset ||
  3530. BId == Builtin::BIstrndup ? 1 : 2);
  3531. unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
  3532. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  3533. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  3534. Call->getLocStart(), Call->getRParenLoc()))
  3535. return;
  3536. // We have special checking when the length is a sizeof expression.
  3537. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  3538. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  3539. llvm::FoldingSetNodeID SizeOfArgID;
  3540. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  3541. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  3542. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  3543. QualType DestTy = Dest->getType();
  3544. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  3545. QualType PointeeTy = DestPtrTy->getPointeeType();
  3546. // Never warn about void type pointers. This can be used to suppress
  3547. // false positives.
  3548. if (PointeeTy->isVoidType())
  3549. continue;
  3550. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  3551. // actually comparing the expressions for equality. Because computing the
  3552. // expression IDs can be expensive, we only do this if the diagnostic is
  3553. // enabled.
  3554. if (SizeOfArg &&
  3555. Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
  3556. SizeOfArg->getExprLoc())) {
  3557. // We only compute IDs for expressions if the warning is enabled, and
  3558. // cache the sizeof arg's ID.
  3559. if (SizeOfArgID == llvm::FoldingSetNodeID())
  3560. SizeOfArg->Profile(SizeOfArgID, Context, true);
  3561. llvm::FoldingSetNodeID DestID;
  3562. Dest->Profile(DestID, Context, true);
  3563. if (DestID == SizeOfArgID) {
  3564. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  3565. // over sizeof(src) as well.
  3566. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  3567. StringRef ReadableName = FnName->getName();
  3568. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  3569. if (UnaryOp->getOpcode() == UO_AddrOf)
  3570. ActionIdx = 1; // If its an address-of operator, just remove it.
  3571. if (!PointeeTy->isIncompleteType() &&
  3572. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  3573. ActionIdx = 2; // If the pointee's size is sizeof(char),
  3574. // suggest an explicit length.
  3575. // If the function is defined as a builtin macro, do not show macro
  3576. // expansion.
  3577. SourceLocation SL = SizeOfArg->getExprLoc();
  3578. SourceRange DSR = Dest->getSourceRange();
  3579. SourceRange SSR = SizeOfArg->getSourceRange();
  3580. SourceManager &SM = getSourceManager();
  3581. if (SM.isMacroArgExpansion(SL)) {
  3582. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  3583. SL = SM.getSpellingLoc(SL);
  3584. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  3585. SM.getSpellingLoc(DSR.getEnd()));
  3586. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  3587. SM.getSpellingLoc(SSR.getEnd()));
  3588. }
  3589. DiagRuntimeBehavior(SL, SizeOfArg,
  3590. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  3591. << ReadableName
  3592. << PointeeTy
  3593. << DestTy
  3594. << DSR
  3595. << SSR);
  3596. DiagRuntimeBehavior(SL, SizeOfArg,
  3597. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  3598. << ActionIdx
  3599. << SSR);
  3600. break;
  3601. }
  3602. }
  3603. // Also check for cases where the sizeof argument is the exact same
  3604. // type as the memory argument, and where it points to a user-defined
  3605. // record type.
  3606. if (SizeOfArgTy != QualType()) {
  3607. if (PointeeTy->isRecordType() &&
  3608. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  3609. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  3610. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  3611. << FnName << SizeOfArgTy << ArgIdx
  3612. << PointeeTy << Dest->getSourceRange()
  3613. << LenExpr->getSourceRange());
  3614. break;
  3615. }
  3616. }
  3617. // Always complain about dynamic classes.
  3618. if (isDynamicClassType(PointeeTy)) {
  3619. unsigned OperationType = 0;
  3620. // "overwritten" if we're warning about the destination for any call
  3621. // but memcmp; otherwise a verb appropriate to the call.
  3622. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  3623. if (BId == Builtin::BImemcpy)
  3624. OperationType = 1;
  3625. else if(BId == Builtin::BImemmove)
  3626. OperationType = 2;
  3627. else if (BId == Builtin::BImemcmp)
  3628. OperationType = 3;
  3629. }
  3630. DiagRuntimeBehavior(
  3631. Dest->getExprLoc(), Dest,
  3632. PDiag(diag::warn_dyn_class_memaccess)
  3633. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  3634. << FnName << PointeeTy
  3635. << OperationType
  3636. << Call->getCallee()->getSourceRange());
  3637. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  3638. BId != Builtin::BImemset)
  3639. DiagRuntimeBehavior(
  3640. Dest->getExprLoc(), Dest,
  3641. PDiag(diag::warn_arc_object_memaccess)
  3642. << ArgIdx << FnName << PointeeTy
  3643. << Call->getCallee()->getSourceRange());
  3644. else
  3645. continue;
  3646. DiagRuntimeBehavior(
  3647. Dest->getExprLoc(), Dest,
  3648. PDiag(diag::note_bad_memaccess_silence)
  3649. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  3650. break;
  3651. }
  3652. }
  3653. }
  3654. // A little helper routine: ignore addition and subtraction of integer literals.
  3655. // This intentionally does not ignore all integer constant expressions because
  3656. // we don't want to remove sizeof().
  3657. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  3658. Ex = Ex->IgnoreParenCasts();
  3659. for (;;) {
  3660. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  3661. if (!BO || !BO->isAdditiveOp())
  3662. break;
  3663. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  3664. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  3665. if (isa<IntegerLiteral>(RHS))
  3666. Ex = LHS;
  3667. else if (isa<IntegerLiteral>(LHS))
  3668. Ex = RHS;
  3669. else
  3670. break;
  3671. }
  3672. return Ex;
  3673. }
  3674. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  3675. ASTContext &Context) {
  3676. // Only handle constant-sized or VLAs, but not flexible members.
  3677. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  3678. // Only issue the FIXIT for arrays of size > 1.
  3679. if (CAT->getSize().getSExtValue() <= 1)
  3680. return false;
  3681. } else if (!Ty->isVariableArrayType()) {
  3682. return false;
  3683. }
  3684. return true;
  3685. }
  3686. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  3687. // be the size of the source, instead of the destination.
  3688. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  3689. IdentifierInfo *FnName) {
  3690. // Don't crash if the user has the wrong number of arguments
  3691. if (Call->getNumArgs() != 3)
  3692. return;
  3693. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  3694. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  3695. const Expr *CompareWithSrc = nullptr;
  3696. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  3697. Call->getLocStart(), Call->getRParenLoc()))
  3698. return;
  3699. // Look for 'strlcpy(dst, x, sizeof(x))'
  3700. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  3701. CompareWithSrc = Ex;
  3702. else {
  3703. // Look for 'strlcpy(dst, x, strlen(x))'
  3704. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  3705. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  3706. SizeCall->getNumArgs() == 1)
  3707. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  3708. }
  3709. }
  3710. if (!CompareWithSrc)
  3711. return;
  3712. // Determine if the argument to sizeof/strlen is equal to the source
  3713. // argument. In principle there's all kinds of things you could do
  3714. // here, for instance creating an == expression and evaluating it with
  3715. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  3716. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  3717. if (!SrcArgDRE)
  3718. return;
  3719. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  3720. if (!CompareWithSrcDRE ||
  3721. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  3722. return;
  3723. const Expr *OriginalSizeArg = Call->getArg(2);
  3724. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  3725. << OriginalSizeArg->getSourceRange() << FnName;
  3726. // Output a FIXIT hint if the destination is an array (rather than a
  3727. // pointer to an array). This could be enhanced to handle some
  3728. // pointers if we know the actual size, like if DstArg is 'array+2'
  3729. // we could say 'sizeof(array)-2'.
  3730. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  3731. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  3732. return;
  3733. SmallString<128> sizeString;
  3734. llvm::raw_svector_ostream OS(sizeString);
  3735. OS << "sizeof(";
  3736. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  3737. OS << ")";
  3738. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  3739. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  3740. OS.str());
  3741. }
  3742. /// Check if two expressions refer to the same declaration.
  3743. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  3744. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  3745. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  3746. return D1->getDecl() == D2->getDecl();
  3747. return false;
  3748. }
  3749. static const Expr *getStrlenExprArg(const Expr *E) {
  3750. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  3751. const FunctionDecl *FD = CE->getDirectCallee();
  3752. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  3753. return nullptr;
  3754. return CE->getArg(0)->IgnoreParenCasts();
  3755. }
  3756. return nullptr;
  3757. }
  3758. // Warn on anti-patterns as the 'size' argument to strncat.
  3759. // The correct size argument should look like following:
  3760. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  3761. void Sema::CheckStrncatArguments(const CallExpr *CE,
  3762. IdentifierInfo *FnName) {
  3763. // Don't crash if the user has the wrong number of arguments.
  3764. if (CE->getNumArgs() < 3)
  3765. return;
  3766. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  3767. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  3768. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  3769. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
  3770. CE->getRParenLoc()))
  3771. return;
  3772. // Identify common expressions, which are wrongly used as the size argument
  3773. // to strncat and may lead to buffer overflows.
  3774. unsigned PatternType = 0;
  3775. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  3776. // - sizeof(dst)
  3777. if (referToTheSameDecl(SizeOfArg, DstArg))
  3778. PatternType = 1;
  3779. // - sizeof(src)
  3780. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  3781. PatternType = 2;
  3782. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  3783. if (BE->getOpcode() == BO_Sub) {
  3784. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  3785. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  3786. // - sizeof(dst) - strlen(dst)
  3787. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  3788. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  3789. PatternType = 1;
  3790. // - sizeof(src) - (anything)
  3791. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  3792. PatternType = 2;
  3793. }
  3794. }
  3795. if (PatternType == 0)
  3796. return;
  3797. // Generate the diagnostic.
  3798. SourceLocation SL = LenArg->getLocStart();
  3799. SourceRange SR = LenArg->getSourceRange();
  3800. SourceManager &SM = getSourceManager();
  3801. // If the function is defined as a builtin macro, do not show macro expansion.
  3802. if (SM.isMacroArgExpansion(SL)) {
  3803. SL = SM.getSpellingLoc(SL);
  3804. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  3805. SM.getSpellingLoc(SR.getEnd()));
  3806. }
  3807. // Check if the destination is an array (rather than a pointer to an array).
  3808. QualType DstTy = DstArg->getType();
  3809. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  3810. Context);
  3811. if (!isKnownSizeArray) {
  3812. if (PatternType == 1)
  3813. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  3814. else
  3815. Diag(SL, diag::warn_strncat_src_size) << SR;
  3816. return;
  3817. }
  3818. if (PatternType == 1)
  3819. Diag(SL, diag::warn_strncat_large_size) << SR;
  3820. else
  3821. Diag(SL, diag::warn_strncat_src_size) << SR;
  3822. SmallString<128> sizeString;
  3823. llvm::raw_svector_ostream OS(sizeString);
  3824. OS << "sizeof(";
  3825. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  3826. OS << ") - ";
  3827. OS << "strlen(";
  3828. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  3829. OS << ") - 1";
  3830. Diag(SL, diag::note_strncat_wrong_size)
  3831. << FixItHint::CreateReplacement(SR, OS.str());
  3832. }
  3833. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  3834. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  3835. Decl *ParentDecl);
  3836. static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
  3837. Decl *ParentDecl);
  3838. /// CheckReturnStackAddr - Check if a return statement returns the address
  3839. /// of a stack variable.
  3840. static void
  3841. CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
  3842. SourceLocation ReturnLoc) {
  3843. Expr *stackE = nullptr;
  3844. SmallVector<DeclRefExpr *, 8> refVars;
  3845. // Perform checking for returned stack addresses, local blocks,
  3846. // label addresses or references to temporaries.
  3847. if (lhsType->isPointerType() ||
  3848. (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  3849. stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
  3850. } else if (lhsType->isReferenceType()) {
  3851. stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
  3852. }
  3853. if (!stackE)
  3854. return; // Nothing suspicious was found.
  3855. SourceLocation diagLoc;
  3856. SourceRange diagRange;
  3857. if (refVars.empty()) {
  3858. diagLoc = stackE->getLocStart();
  3859. diagRange = stackE->getSourceRange();
  3860. } else {
  3861. // We followed through a reference variable. 'stackE' contains the
  3862. // problematic expression but we will warn at the return statement pointing
  3863. // at the reference variable. We will later display the "trail" of
  3864. // reference variables using notes.
  3865. diagLoc = refVars[0]->getLocStart();
  3866. diagRange = refVars[0]->getSourceRange();
  3867. }
  3868. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
  3869. S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
  3870. : diag::warn_ret_stack_addr)
  3871. << DR->getDecl()->getDeclName() << diagRange;
  3872. } else if (isa<BlockExpr>(stackE)) { // local block.
  3873. S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  3874. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  3875. S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  3876. } else { // local temporary.
  3877. S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
  3878. : diag::warn_ret_local_temp_addr)
  3879. << diagRange;
  3880. }
  3881. // Display the "trail" of reference variables that we followed until we
  3882. // found the problematic expression using notes.
  3883. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  3884. VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  3885. // If this var binds to another reference var, show the range of the next
  3886. // var, otherwise the var binds to the problematic expression, in which case
  3887. // show the range of the expression.
  3888. SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
  3889. : stackE->getSourceRange();
  3890. S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  3891. << VD->getDeclName() << range;
  3892. }
  3893. }
  3894. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  3895. /// check if the expression in a return statement evaluates to an address
  3896. /// to a location on the stack, a local block, an address of a label, or a
  3897. /// reference to local temporary. The recursion is used to traverse the
  3898. /// AST of the return expression, with recursion backtracking when we
  3899. /// encounter a subexpression that (1) clearly does not lead to one of the
  3900. /// above problematic expressions (2) is something we cannot determine leads to
  3901. /// a problematic expression based on such local checking.
  3902. ///
  3903. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  3904. /// the expression that they point to. Such variables are added to the
  3905. /// 'refVars' vector so that we know what the reference variable "trail" was.
  3906. ///
  3907. /// EvalAddr processes expressions that are pointers that are used as
  3908. /// references (and not L-values). EvalVal handles all other values.
  3909. /// At the base case of the recursion is a check for the above problematic
  3910. /// expressions.
  3911. ///
  3912. /// This implementation handles:
  3913. ///
  3914. /// * pointer-to-pointer casts
  3915. /// * implicit conversions from array references to pointers
  3916. /// * taking the address of fields
  3917. /// * arbitrary interplay between "&" and "*" operators
  3918. /// * pointer arithmetic from an address of a stack variable
  3919. /// * taking the address of an array element where the array is on the stack
  3920. static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  3921. Decl *ParentDecl) {
  3922. if (E->isTypeDependent())
  3923. return nullptr;
  3924. // We should only be called for evaluating pointer expressions.
  3925. assert((E->getType()->isAnyPointerType() ||
  3926. E->getType()->isBlockPointerType() ||
  3927. E->getType()->isObjCQualifiedIdType()) &&
  3928. "EvalAddr only works on pointers");
  3929. E = E->IgnoreParens();
  3930. // Our "symbolic interpreter" is just a dispatch off the currently
  3931. // viewed AST node. We then recursively traverse the AST by calling
  3932. // EvalAddr and EvalVal appropriately.
  3933. switch (E->getStmtClass()) {
  3934. case Stmt::DeclRefExprClass: {
  3935. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  3936. // If we leave the immediate function, the lifetime isn't about to end.
  3937. if (DR->refersToEnclosingLocal())
  3938. return nullptr;
  3939. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  3940. // If this is a reference variable, follow through to the expression that
  3941. // it points to.
  3942. if (V->hasLocalStorage() &&
  3943. V->getType()->isReferenceType() && V->hasInit()) {
  3944. // Add the reference variable to the "trail".
  3945. refVars.push_back(DR);
  3946. return EvalAddr(V->getInit(), refVars, ParentDecl);
  3947. }
  3948. return nullptr;
  3949. }
  3950. case Stmt::UnaryOperatorClass: {
  3951. // The only unary operator that make sense to handle here
  3952. // is AddrOf. All others don't make sense as pointers.
  3953. UnaryOperator *U = cast<UnaryOperator>(E);
  3954. if (U->getOpcode() == UO_AddrOf)
  3955. return EvalVal(U->getSubExpr(), refVars, ParentDecl);
  3956. else
  3957. return nullptr;
  3958. }
  3959. case Stmt::BinaryOperatorClass: {
  3960. // Handle pointer arithmetic. All other binary operators are not valid
  3961. // in this context.
  3962. BinaryOperator *B = cast<BinaryOperator>(E);
  3963. BinaryOperatorKind op = B->getOpcode();
  3964. if (op != BO_Add && op != BO_Sub)
  3965. return nullptr;
  3966. Expr *Base = B->getLHS();
  3967. // Determine which argument is the real pointer base. It could be
  3968. // the RHS argument instead of the LHS.
  3969. if (!Base->getType()->isPointerType()) Base = B->getRHS();
  3970. assert (Base->getType()->isPointerType());
  3971. return EvalAddr(Base, refVars, ParentDecl);
  3972. }
  3973. // For conditional operators we need to see if either the LHS or RHS are
  3974. // valid DeclRefExpr*s. If one of them is valid, we return it.
  3975. case Stmt::ConditionalOperatorClass: {
  3976. ConditionalOperator *C = cast<ConditionalOperator>(E);
  3977. // Handle the GNU extension for missing LHS.
  3978. // FIXME: That isn't a ConditionalOperator, so doesn't get here.
  3979. if (Expr *LHSExpr = C->getLHS()) {
  3980. // In C++, we can have a throw-expression, which has 'void' type.
  3981. if (!LHSExpr->getType()->isVoidType())
  3982. if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
  3983. return LHS;
  3984. }
  3985. // In C++, we can have a throw-expression, which has 'void' type.
  3986. if (C->getRHS()->getType()->isVoidType())
  3987. return nullptr;
  3988. return EvalAddr(C->getRHS(), refVars, ParentDecl);
  3989. }
  3990. case Stmt::BlockExprClass:
  3991. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  3992. return E; // local block.
  3993. return nullptr;
  3994. case Stmt::AddrLabelExprClass:
  3995. return E; // address of label.
  3996. case Stmt::ExprWithCleanupsClass:
  3997. return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  3998. ParentDecl);
  3999. // For casts, we need to handle conversions from arrays to
  4000. // pointer values, and pointer-to-pointer conversions.
  4001. case Stmt::ImplicitCastExprClass:
  4002. case Stmt::CStyleCastExprClass:
  4003. case Stmt::CXXFunctionalCastExprClass:
  4004. case Stmt::ObjCBridgedCastExprClass:
  4005. case Stmt::CXXStaticCastExprClass:
  4006. case Stmt::CXXDynamicCastExprClass:
  4007. case Stmt::CXXConstCastExprClass:
  4008. case Stmt::CXXReinterpretCastExprClass: {
  4009. Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  4010. switch (cast<CastExpr>(E)->getCastKind()) {
  4011. case CK_BitCast:
  4012. case CK_LValueToRValue:
  4013. case CK_NoOp:
  4014. case CK_BaseToDerived:
  4015. case CK_DerivedToBase:
  4016. case CK_UncheckedDerivedToBase:
  4017. case CK_Dynamic:
  4018. case CK_CPointerToObjCPointerCast:
  4019. case CK_BlockPointerToObjCPointerCast:
  4020. case CK_AnyPointerToBlockPointerCast:
  4021. return EvalAddr(SubExpr, refVars, ParentDecl);
  4022. case CK_ArrayToPointerDecay:
  4023. return EvalVal(SubExpr, refVars, ParentDecl);
  4024. default:
  4025. return nullptr;
  4026. }
  4027. }
  4028. case Stmt::MaterializeTemporaryExprClass:
  4029. if (Expr *Result = EvalAddr(
  4030. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  4031. refVars, ParentDecl))
  4032. return Result;
  4033. return E;
  4034. // Everything else: we simply don't reason about them.
  4035. default:
  4036. return nullptr;
  4037. }
  4038. }
  4039. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  4040. /// See the comments for EvalAddr for more details.
  4041. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  4042. Decl *ParentDecl) {
  4043. do {
  4044. // We should only be called for evaluating non-pointer expressions, or
  4045. // expressions with a pointer type that are not used as references but instead
  4046. // are l-values (e.g., DeclRefExpr with a pointer type).
  4047. // Our "symbolic interpreter" is just a dispatch off the currently
  4048. // viewed AST node. We then recursively traverse the AST by calling
  4049. // EvalAddr and EvalVal appropriately.
  4050. E = E->IgnoreParens();
  4051. switch (E->getStmtClass()) {
  4052. case Stmt::ImplicitCastExprClass: {
  4053. ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  4054. if (IE->getValueKind() == VK_LValue) {
  4055. E = IE->getSubExpr();
  4056. continue;
  4057. }
  4058. return nullptr;
  4059. }
  4060. case Stmt::ExprWithCleanupsClass:
  4061. return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
  4062. case Stmt::DeclRefExprClass: {
  4063. // When we hit a DeclRefExpr we are looking at code that refers to a
  4064. // variable's name. If it's not a reference variable we check if it has
  4065. // local storage within the function, and if so, return the expression.
  4066. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  4067. // If we leave the immediate function, the lifetime isn't about to end.
  4068. if (DR->refersToEnclosingLocal())
  4069. return nullptr;
  4070. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
  4071. // Check if it refers to itself, e.g. "int& i = i;".
  4072. if (V == ParentDecl)
  4073. return DR;
  4074. if (V->hasLocalStorage()) {
  4075. if (!V->getType()->isReferenceType())
  4076. return DR;
  4077. // Reference variable, follow through to the expression that
  4078. // it points to.
  4079. if (V->hasInit()) {
  4080. // Add the reference variable to the "trail".
  4081. refVars.push_back(DR);
  4082. return EvalVal(V->getInit(), refVars, V);
  4083. }
  4084. }
  4085. }
  4086. return nullptr;
  4087. }
  4088. case Stmt::UnaryOperatorClass: {
  4089. // The only unary operator that make sense to handle here
  4090. // is Deref. All others don't resolve to a "name." This includes
  4091. // handling all sorts of rvalues passed to a unary operator.
  4092. UnaryOperator *U = cast<UnaryOperator>(E);
  4093. if (U->getOpcode() == UO_Deref)
  4094. return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
  4095. return nullptr;
  4096. }
  4097. case Stmt::ArraySubscriptExprClass: {
  4098. // Array subscripts are potential references to data on the stack. We
  4099. // retrieve the DeclRefExpr* for the array variable if it indeed
  4100. // has local storage.
  4101. return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
  4102. }
  4103. case Stmt::ConditionalOperatorClass: {
  4104. // For conditional operators we need to see if either the LHS or RHS are
  4105. // non-NULL Expr's. If one is non-NULL, we return it.
  4106. ConditionalOperator *C = cast<ConditionalOperator>(E);
  4107. // Handle the GNU extension for missing LHS.
  4108. if (Expr *LHSExpr = C->getLHS()) {
  4109. // In C++, we can have a throw-expression, which has 'void' type.
  4110. if (!LHSExpr->getType()->isVoidType())
  4111. if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
  4112. return LHS;
  4113. }
  4114. // In C++, we can have a throw-expression, which has 'void' type.
  4115. if (C->getRHS()->getType()->isVoidType())
  4116. return nullptr;
  4117. return EvalVal(C->getRHS(), refVars, ParentDecl);
  4118. }
  4119. // Accesses to members are potential references to data on the stack.
  4120. case Stmt::MemberExprClass: {
  4121. MemberExpr *M = cast<MemberExpr>(E);
  4122. // Check for indirect access. We only want direct field accesses.
  4123. if (M->isArrow())
  4124. return nullptr;
  4125. // Check whether the member type is itself a reference, in which case
  4126. // we're not going to refer to the member, but to what the member refers to.
  4127. if (M->getMemberDecl()->getType()->isReferenceType())
  4128. return nullptr;
  4129. return EvalVal(M->getBase(), refVars, ParentDecl);
  4130. }
  4131. case Stmt::MaterializeTemporaryExprClass:
  4132. if (Expr *Result = EvalVal(
  4133. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  4134. refVars, ParentDecl))
  4135. return Result;
  4136. return E;
  4137. default:
  4138. // Check that we don't return or take the address of a reference to a
  4139. // temporary. This is only useful in C++.
  4140. if (!E->isTypeDependent() && E->isRValue())
  4141. return E;
  4142. // Everything else: we simply don't reason about them.
  4143. return nullptr;
  4144. }
  4145. } while (true);
  4146. }
  4147. void
  4148. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  4149. SourceLocation ReturnLoc,
  4150. bool isObjCMethod,
  4151. const AttrVec *Attrs,
  4152. const FunctionDecl *FD) {
  4153. CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
  4154. // Check if the return value is null but should not be.
  4155. if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
  4156. CheckNonNullExpr(*this, RetValExp))
  4157. Diag(ReturnLoc, diag::warn_null_ret)
  4158. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  4159. // C++11 [basic.stc.dynamic.allocation]p4:
  4160. // If an allocation function declared with a non-throwing
  4161. // exception-specification fails to allocate storage, it shall return
  4162. // a null pointer. Any other allocation function that fails to allocate
  4163. // storage shall indicate failure only by throwing an exception [...]
  4164. if (FD) {
  4165. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  4166. if (Op == OO_New || Op == OO_Array_New) {
  4167. const FunctionProtoType *Proto
  4168. = FD->getType()->castAs<FunctionProtoType>();
  4169. if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
  4170. CheckNonNullExpr(*this, RetValExp))
  4171. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  4172. << FD << getLangOpts().CPlusPlus11;
  4173. }
  4174. }
  4175. }
  4176. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  4177. /// Check for comparisons of floating point operands using != and ==.
  4178. /// Issue a warning if these are no self-comparisons, as they are not likely
  4179. /// to do what the programmer intended.
  4180. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  4181. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  4182. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  4183. // Special case: check for x == x (which is OK).
  4184. // Do not emit warnings for such cases.
  4185. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  4186. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  4187. if (DRL->getDecl() == DRR->getDecl())
  4188. return;
  4189. // Special case: check for comparisons against literals that can be exactly
  4190. // represented by APFloat. In such cases, do not emit a warning. This
  4191. // is a heuristic: often comparison against such literals are used to
  4192. // detect if a value in a variable has not changed. This clearly can
  4193. // lead to false negatives.
  4194. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  4195. if (FLL->isExact())
  4196. return;
  4197. } else
  4198. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  4199. if (FLR->isExact())
  4200. return;
  4201. // Check for comparisons with builtin types.
  4202. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  4203. if (CL->getBuiltinCallee())
  4204. return;
  4205. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  4206. if (CR->getBuiltinCallee())
  4207. return;
  4208. // Emit the diagnostic.
  4209. Diag(Loc, diag::warn_floatingpoint_eq)
  4210. << LHS->getSourceRange() << RHS->getSourceRange();
  4211. }
  4212. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  4213. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  4214. namespace {
  4215. /// Structure recording the 'active' range of an integer-valued
  4216. /// expression.
  4217. struct IntRange {
  4218. /// The number of bits active in the int.
  4219. unsigned Width;
  4220. /// True if the int is known not to have negative values.
  4221. bool NonNegative;
  4222. IntRange(unsigned Width, bool NonNegative)
  4223. : Width(Width), NonNegative(NonNegative)
  4224. {}
  4225. /// Returns the range of the bool type.
  4226. static IntRange forBoolType() {
  4227. return IntRange(1, true);
  4228. }
  4229. /// Returns the range of an opaque value of the given integral type.
  4230. static IntRange forValueOfType(ASTContext &C, QualType T) {
  4231. return forValueOfCanonicalType(C,
  4232. T->getCanonicalTypeInternal().getTypePtr());
  4233. }
  4234. /// Returns the range of an opaque value of a canonical integral type.
  4235. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  4236. assert(T->isCanonicalUnqualified());
  4237. if (const VectorType *VT = dyn_cast<VectorType>(T))
  4238. T = VT->getElementType().getTypePtr();
  4239. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  4240. T = CT->getElementType().getTypePtr();
  4241. // For enum types, use the known bit width of the enumerators.
  4242. if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  4243. EnumDecl *Enum = ET->getDecl();
  4244. if (!Enum->isCompleteDefinition())
  4245. return IntRange(C.getIntWidth(QualType(T, 0)), false);
  4246. unsigned NumPositive = Enum->getNumPositiveBits();
  4247. unsigned NumNegative = Enum->getNumNegativeBits();
  4248. if (NumNegative == 0)
  4249. return IntRange(NumPositive, true/*NonNegative*/);
  4250. else
  4251. return IntRange(std::max(NumPositive + 1, NumNegative),
  4252. false/*NonNegative*/);
  4253. }
  4254. const BuiltinType *BT = cast<BuiltinType>(T);
  4255. assert(BT->isInteger());
  4256. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  4257. }
  4258. /// Returns the "target" range of a canonical integral type, i.e.
  4259. /// the range of values expressible in the type.
  4260. ///
  4261. /// This matches forValueOfCanonicalType except that enums have the
  4262. /// full range of their type, not the range of their enumerators.
  4263. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  4264. assert(T->isCanonicalUnqualified());
  4265. if (const VectorType *VT = dyn_cast<VectorType>(T))
  4266. T = VT->getElementType().getTypePtr();
  4267. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  4268. T = CT->getElementType().getTypePtr();
  4269. if (const EnumType *ET = dyn_cast<EnumType>(T))
  4270. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  4271. const BuiltinType *BT = cast<BuiltinType>(T);
  4272. assert(BT->isInteger());
  4273. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  4274. }
  4275. /// Returns the supremum of two ranges: i.e. their conservative merge.
  4276. static IntRange join(IntRange L, IntRange R) {
  4277. return IntRange(std::max(L.Width, R.Width),
  4278. L.NonNegative && R.NonNegative);
  4279. }
  4280. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  4281. static IntRange meet(IntRange L, IntRange R) {
  4282. return IntRange(std::min(L.Width, R.Width),
  4283. L.NonNegative || R.NonNegative);
  4284. }
  4285. };
  4286. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  4287. unsigned MaxWidth) {
  4288. if (value.isSigned() && value.isNegative())
  4289. return IntRange(value.getMinSignedBits(), false);
  4290. if (value.getBitWidth() > MaxWidth)
  4291. value = value.trunc(MaxWidth);
  4292. // isNonNegative() just checks the sign bit without considering
  4293. // signedness.
  4294. return IntRange(value.getActiveBits(), true);
  4295. }
  4296. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  4297. unsigned MaxWidth) {
  4298. if (result.isInt())
  4299. return GetValueRange(C, result.getInt(), MaxWidth);
  4300. if (result.isVector()) {
  4301. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  4302. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  4303. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  4304. R = IntRange::join(R, El);
  4305. }
  4306. return R;
  4307. }
  4308. if (result.isComplexInt()) {
  4309. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  4310. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  4311. return IntRange::join(R, I);
  4312. }
  4313. // This can happen with lossless casts to intptr_t of "based" lvalues.
  4314. // Assume it might use arbitrary bits.
  4315. // FIXME: The only reason we need to pass the type in here is to get
  4316. // the sign right on this one case. It would be nice if APValue
  4317. // preserved this.
  4318. assert(result.isLValue() || result.isAddrLabelDiff());
  4319. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  4320. }
  4321. static QualType GetExprType(Expr *E) {
  4322. QualType Ty = E->getType();
  4323. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  4324. Ty = AtomicRHS->getValueType();
  4325. return Ty;
  4326. }
  4327. /// Pseudo-evaluate the given integer expression, estimating the
  4328. /// range of values it might take.
  4329. ///
  4330. /// \param MaxWidth - the width to which the value will be truncated
  4331. static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
  4332. E = E->IgnoreParens();
  4333. // Try a full evaluation first.
  4334. Expr::EvalResult result;
  4335. if (E->EvaluateAsRValue(result, C))
  4336. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  4337. // I think we only want to look through implicit casts here; if the
  4338. // user has an explicit widening cast, we should treat the value as
  4339. // being of the new, wider type.
  4340. if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
  4341. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  4342. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  4343. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  4344. bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
  4345. // Assume that non-integer casts can span the full range of the type.
  4346. if (!isIntegerCast)
  4347. return OutputTypeRange;
  4348. IntRange SubRange
  4349. = GetExprRange(C, CE->getSubExpr(),
  4350. std::min(MaxWidth, OutputTypeRange.Width));
  4351. // Bail out if the subexpr's range is as wide as the cast type.
  4352. if (SubRange.Width >= OutputTypeRange.Width)
  4353. return OutputTypeRange;
  4354. // Otherwise, we take the smaller width, and we're non-negative if
  4355. // either the output type or the subexpr is.
  4356. return IntRange(SubRange.Width,
  4357. SubRange.NonNegative || OutputTypeRange.NonNegative);
  4358. }
  4359. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  4360. // If we can fold the condition, just take that operand.
  4361. bool CondResult;
  4362. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  4363. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  4364. : CO->getFalseExpr(),
  4365. MaxWidth);
  4366. // Otherwise, conservatively merge.
  4367. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  4368. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  4369. return IntRange::join(L, R);
  4370. }
  4371. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  4372. switch (BO->getOpcode()) {
  4373. // Boolean-valued operations are single-bit and positive.
  4374. case BO_LAnd:
  4375. case BO_LOr:
  4376. case BO_LT:
  4377. case BO_GT:
  4378. case BO_LE:
  4379. case BO_GE:
  4380. case BO_EQ:
  4381. case BO_NE:
  4382. return IntRange::forBoolType();
  4383. // The type of the assignments is the type of the LHS, so the RHS
  4384. // is not necessarily the same type.
  4385. case BO_MulAssign:
  4386. case BO_DivAssign:
  4387. case BO_RemAssign:
  4388. case BO_AddAssign:
  4389. case BO_SubAssign:
  4390. case BO_XorAssign:
  4391. case BO_OrAssign:
  4392. // TODO: bitfields?
  4393. return IntRange::forValueOfType(C, GetExprType(E));
  4394. // Simple assignments just pass through the RHS, which will have
  4395. // been coerced to the LHS type.
  4396. case BO_Assign:
  4397. // TODO: bitfields?
  4398. return GetExprRange(C, BO->getRHS(), MaxWidth);
  4399. // Operations with opaque sources are black-listed.
  4400. case BO_PtrMemD:
  4401. case BO_PtrMemI:
  4402. return IntRange::forValueOfType(C, GetExprType(E));
  4403. // Bitwise-and uses the *infinum* of the two source ranges.
  4404. case BO_And:
  4405. case BO_AndAssign:
  4406. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  4407. GetExprRange(C, BO->getRHS(), MaxWidth));
  4408. // Left shift gets black-listed based on a judgement call.
  4409. case BO_Shl:
  4410. // ...except that we want to treat '1 << (blah)' as logically
  4411. // positive. It's an important idiom.
  4412. if (IntegerLiteral *I
  4413. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  4414. if (I->getValue() == 1) {
  4415. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  4416. return IntRange(R.Width, /*NonNegative*/ true);
  4417. }
  4418. }
  4419. // fallthrough
  4420. case BO_ShlAssign:
  4421. return IntRange::forValueOfType(C, GetExprType(E));
  4422. // Right shift by a constant can narrow its left argument.
  4423. case BO_Shr:
  4424. case BO_ShrAssign: {
  4425. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  4426. // If the shift amount is a positive constant, drop the width by
  4427. // that much.
  4428. llvm::APSInt shift;
  4429. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  4430. shift.isNonNegative()) {
  4431. unsigned zext = shift.getZExtValue();
  4432. if (zext >= L.Width)
  4433. L.Width = (L.NonNegative ? 0 : 1);
  4434. else
  4435. L.Width -= zext;
  4436. }
  4437. return L;
  4438. }
  4439. // Comma acts as its right operand.
  4440. case BO_Comma:
  4441. return GetExprRange(C, BO->getRHS(), MaxWidth);
  4442. // Black-list pointer subtractions.
  4443. case BO_Sub:
  4444. if (BO->getLHS()->getType()->isPointerType())
  4445. return IntRange::forValueOfType(C, GetExprType(E));
  4446. break;
  4447. // The width of a division result is mostly determined by the size
  4448. // of the LHS.
  4449. case BO_Div: {
  4450. // Don't 'pre-truncate' the operands.
  4451. unsigned opWidth = C.getIntWidth(GetExprType(E));
  4452. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  4453. // If the divisor is constant, use that.
  4454. llvm::APSInt divisor;
  4455. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  4456. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  4457. if (log2 >= L.Width)
  4458. L.Width = (L.NonNegative ? 0 : 1);
  4459. else
  4460. L.Width = std::min(L.Width - log2, MaxWidth);
  4461. return L;
  4462. }
  4463. // Otherwise, just use the LHS's width.
  4464. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  4465. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  4466. }
  4467. // The result of a remainder can't be larger than the result of
  4468. // either side.
  4469. case BO_Rem: {
  4470. // Don't 'pre-truncate' the operands.
  4471. unsigned opWidth = C.getIntWidth(GetExprType(E));
  4472. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  4473. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  4474. IntRange meet = IntRange::meet(L, R);
  4475. meet.Width = std::min(meet.Width, MaxWidth);
  4476. return meet;
  4477. }
  4478. // The default behavior is okay for these.
  4479. case BO_Mul:
  4480. case BO_Add:
  4481. case BO_Xor:
  4482. case BO_Or:
  4483. break;
  4484. }
  4485. // The default case is to treat the operation as if it were closed
  4486. // on the narrowest type that encompasses both operands.
  4487. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  4488. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  4489. return IntRange::join(L, R);
  4490. }
  4491. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  4492. switch (UO->getOpcode()) {
  4493. // Boolean-valued operations are white-listed.
  4494. case UO_LNot:
  4495. return IntRange::forBoolType();
  4496. // Operations with opaque sources are black-listed.
  4497. case UO_Deref:
  4498. case UO_AddrOf: // should be impossible
  4499. return IntRange::forValueOfType(C, GetExprType(E));
  4500. default:
  4501. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  4502. }
  4503. }
  4504. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
  4505. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
  4506. if (FieldDecl *BitField = E->getSourceBitField())
  4507. return IntRange(BitField->getBitWidthValue(C),
  4508. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  4509. return IntRange::forValueOfType(C, GetExprType(E));
  4510. }
  4511. static IntRange GetExprRange(ASTContext &C, Expr *E) {
  4512. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
  4513. }
  4514. /// Checks whether the given value, which currently has the given
  4515. /// source semantics, has the same value when coerced through the
  4516. /// target semantics.
  4517. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  4518. const llvm::fltSemantics &Src,
  4519. const llvm::fltSemantics &Tgt) {
  4520. llvm::APFloat truncated = value;
  4521. bool ignored;
  4522. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  4523. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  4524. return truncated.bitwiseIsEqual(value);
  4525. }
  4526. /// Checks whether the given value, which currently has the given
  4527. /// source semantics, has the same value when coerced through the
  4528. /// target semantics.
  4529. ///
  4530. /// The value might be a vector of floats (or a complex number).
  4531. static bool IsSameFloatAfterCast(const APValue &value,
  4532. const llvm::fltSemantics &Src,
  4533. const llvm::fltSemantics &Tgt) {
  4534. if (value.isFloat())
  4535. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  4536. if (value.isVector()) {
  4537. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  4538. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  4539. return false;
  4540. return true;
  4541. }
  4542. assert(value.isComplexFloat());
  4543. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  4544. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  4545. }
  4546. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  4547. static bool IsZero(Sema &S, Expr *E) {
  4548. // Suppress cases where we are comparing against an enum constant.
  4549. if (const DeclRefExpr *DR =
  4550. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  4551. if (isa<EnumConstantDecl>(DR->getDecl()))
  4552. return false;
  4553. // Suppress cases where the '0' value is expanded from a macro.
  4554. if (E->getLocStart().isMacroID())
  4555. return false;
  4556. llvm::APSInt Value;
  4557. return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
  4558. }
  4559. static bool HasEnumType(Expr *E) {
  4560. // Strip off implicit integral promotions.
  4561. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  4562. if (ICE->getCastKind() != CK_IntegralCast &&
  4563. ICE->getCastKind() != CK_NoOp)
  4564. break;
  4565. E = ICE->getSubExpr();
  4566. }
  4567. return E->getType()->isEnumeralType();
  4568. }
  4569. static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
  4570. // Disable warning in template instantiations.
  4571. if (!S.ActiveTemplateInstantiations.empty())
  4572. return;
  4573. BinaryOperatorKind op = E->getOpcode();
  4574. if (E->isValueDependent())
  4575. return;
  4576. if (op == BO_LT && IsZero(S, E->getRHS())) {
  4577. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  4578. << "< 0" << "false" << HasEnumType(E->getLHS())
  4579. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  4580. } else if (op == BO_GE && IsZero(S, E->getRHS())) {
  4581. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  4582. << ">= 0" << "true" << HasEnumType(E->getLHS())
  4583. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  4584. } else if (op == BO_GT && IsZero(S, E->getLHS())) {
  4585. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  4586. << "0 >" << "false" << HasEnumType(E->getRHS())
  4587. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  4588. } else if (op == BO_LE && IsZero(S, E->getLHS())) {
  4589. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  4590. << "0 <=" << "true" << HasEnumType(E->getRHS())
  4591. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  4592. }
  4593. }
  4594. static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
  4595. Expr *Constant, Expr *Other,
  4596. llvm::APSInt Value,
  4597. bool RhsConstant) {
  4598. // Disable warning in template instantiations.
  4599. if (!S.ActiveTemplateInstantiations.empty())
  4600. return;
  4601. // TODO: Investigate using GetExprRange() to get tighter bounds
  4602. // on the bit ranges.
  4603. QualType OtherT = Other->getType();
  4604. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  4605. unsigned OtherWidth = OtherRange.Width;
  4606. bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
  4607. // 0 values are handled later by CheckTrivialUnsignedComparison().
  4608. if ((Value == 0) && (!OtherIsBooleanType))
  4609. return;
  4610. BinaryOperatorKind op = E->getOpcode();
  4611. bool IsTrue = true;
  4612. // Used for diagnostic printout.
  4613. enum {
  4614. LiteralConstant = 0,
  4615. CXXBoolLiteralTrue,
  4616. CXXBoolLiteralFalse
  4617. } LiteralOrBoolConstant = LiteralConstant;
  4618. if (!OtherIsBooleanType) {
  4619. QualType ConstantT = Constant->getType();
  4620. QualType CommonT = E->getLHS()->getType();
  4621. if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
  4622. return;
  4623. assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
  4624. "comparison with non-integer type");
  4625. bool ConstantSigned = ConstantT->isSignedIntegerType();
  4626. bool CommonSigned = CommonT->isSignedIntegerType();
  4627. bool EqualityOnly = false;
  4628. if (CommonSigned) {
  4629. // The common type is signed, therefore no signed to unsigned conversion.
  4630. if (!OtherRange.NonNegative) {
  4631. // Check that the constant is representable in type OtherT.
  4632. if (ConstantSigned) {
  4633. if (OtherWidth >= Value.getMinSignedBits())
  4634. return;
  4635. } else { // !ConstantSigned
  4636. if (OtherWidth >= Value.getActiveBits() + 1)
  4637. return;
  4638. }
  4639. } else { // !OtherSigned
  4640. // Check that the constant is representable in type OtherT.
  4641. // Negative values are out of range.
  4642. if (ConstantSigned) {
  4643. if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
  4644. return;
  4645. } else { // !ConstantSigned
  4646. if (OtherWidth >= Value.getActiveBits())
  4647. return;
  4648. }
  4649. }
  4650. } else { // !CommonSigned
  4651. if (OtherRange.NonNegative) {
  4652. if (OtherWidth >= Value.getActiveBits())
  4653. return;
  4654. } else if (!OtherRange.NonNegative && !ConstantSigned) {
  4655. // Check to see if the constant is representable in OtherT.
  4656. if (OtherWidth > Value.getActiveBits())
  4657. return;
  4658. // Check to see if the constant is equivalent to a negative value
  4659. // cast to CommonT.
  4660. if (S.Context.getIntWidth(ConstantT) ==
  4661. S.Context.getIntWidth(CommonT) &&
  4662. Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
  4663. return;
  4664. // The constant value rests between values that OtherT can represent
  4665. // after conversion. Relational comparison still works, but equality
  4666. // comparisons will be tautological.
  4667. EqualityOnly = true;
  4668. } else { // OtherSigned && ConstantSigned
  4669. assert(0 && "Two signed types converted to unsigned types.");
  4670. }
  4671. }
  4672. bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
  4673. if (op == BO_EQ || op == BO_NE) {
  4674. IsTrue = op == BO_NE;
  4675. } else if (EqualityOnly) {
  4676. return;
  4677. } else if (RhsConstant) {
  4678. if (op == BO_GT || op == BO_GE)
  4679. IsTrue = !PositiveConstant;
  4680. else // op == BO_LT || op == BO_LE
  4681. IsTrue = PositiveConstant;
  4682. } else {
  4683. if (op == BO_LT || op == BO_LE)
  4684. IsTrue = !PositiveConstant;
  4685. else // op == BO_GT || op == BO_GE
  4686. IsTrue = PositiveConstant;
  4687. }
  4688. } else {
  4689. // Other isKnownToHaveBooleanValue
  4690. enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
  4691. enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
  4692. enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
  4693. static const struct LinkedConditions {
  4694. CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
  4695. CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
  4696. CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
  4697. CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
  4698. CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
  4699. CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
  4700. } TruthTable = {
  4701. // Constant on LHS. | Constant on RHS. |
  4702. // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
  4703. { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
  4704. { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
  4705. { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
  4706. { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
  4707. { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
  4708. { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
  4709. };
  4710. bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
  4711. enum ConstantValue ConstVal = Zero;
  4712. if (Value.isUnsigned() || Value.isNonNegative()) {
  4713. if (Value == 0) {
  4714. LiteralOrBoolConstant =
  4715. ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
  4716. ConstVal = Zero;
  4717. } else if (Value == 1) {
  4718. LiteralOrBoolConstant =
  4719. ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
  4720. ConstVal = One;
  4721. } else {
  4722. LiteralOrBoolConstant = LiteralConstant;
  4723. ConstVal = GT_One;
  4724. }
  4725. } else {
  4726. ConstVal = LT_Zero;
  4727. }
  4728. CompareBoolWithConstantResult CmpRes;
  4729. switch (op) {
  4730. case BO_LT:
  4731. CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
  4732. break;
  4733. case BO_GT:
  4734. CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
  4735. break;
  4736. case BO_LE:
  4737. CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
  4738. break;
  4739. case BO_GE:
  4740. CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
  4741. break;
  4742. case BO_EQ:
  4743. CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
  4744. break;
  4745. case BO_NE:
  4746. CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
  4747. break;
  4748. default:
  4749. CmpRes = Unkwn;
  4750. break;
  4751. }
  4752. if (CmpRes == AFals) {
  4753. IsTrue = false;
  4754. } else if (CmpRes == ATrue) {
  4755. IsTrue = true;
  4756. } else {
  4757. return;
  4758. }
  4759. }
  4760. // If this is a comparison to an enum constant, include that
  4761. // constant in the diagnostic.
  4762. const EnumConstantDecl *ED = nullptr;
  4763. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  4764. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  4765. SmallString<64> PrettySourceValue;
  4766. llvm::raw_svector_ostream OS(PrettySourceValue);
  4767. if (ED)
  4768. OS << '\'' << *ED << "' (" << Value << ")";
  4769. else
  4770. OS << Value;
  4771. S.DiagRuntimeBehavior(
  4772. E->getOperatorLoc(), E,
  4773. S.PDiag(diag::warn_out_of_range_compare)
  4774. << OS.str() << LiteralOrBoolConstant
  4775. << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
  4776. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  4777. }
  4778. /// Analyze the operands of the given comparison. Implements the
  4779. /// fallback case from AnalyzeComparison.
  4780. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  4781. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  4782. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  4783. }
  4784. /// \brief Implements -Wsign-compare.
  4785. ///
  4786. /// \param E the binary operator to check for warnings
  4787. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  4788. // The type the comparison is being performed in.
  4789. QualType T = E->getLHS()->getType();
  4790. assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
  4791. && "comparison with mismatched types");
  4792. if (E->isValueDependent())
  4793. return AnalyzeImpConvsInComparison(S, E);
  4794. Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
  4795. Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
  4796. bool IsComparisonConstant = false;
  4797. // Check whether an integer constant comparison results in a value
  4798. // of 'true' or 'false'.
  4799. if (T->isIntegralType(S.Context)) {
  4800. llvm::APSInt RHSValue;
  4801. bool IsRHSIntegralLiteral =
  4802. RHS->isIntegerConstantExpr(RHSValue, S.Context);
  4803. llvm::APSInt LHSValue;
  4804. bool IsLHSIntegralLiteral =
  4805. LHS->isIntegerConstantExpr(LHSValue, S.Context);
  4806. if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
  4807. DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
  4808. else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  4809. DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
  4810. else
  4811. IsComparisonConstant =
  4812. (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
  4813. } else if (!T->hasUnsignedIntegerRepresentation())
  4814. IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
  4815. // We don't do anything special if this isn't an unsigned integral
  4816. // comparison: we're only interested in integral comparisons, and
  4817. // signed comparisons only happen in cases we don't care to warn about.
  4818. //
  4819. // We also don't care about value-dependent expressions or expressions
  4820. // whose result is a constant.
  4821. if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
  4822. return AnalyzeImpConvsInComparison(S, E);
  4823. // Check to see if one of the (unmodified) operands is of different
  4824. // signedness.
  4825. Expr *signedOperand, *unsignedOperand;
  4826. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  4827. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  4828. "unsigned comparison between two signed integer expressions?");
  4829. signedOperand = LHS;
  4830. unsignedOperand = RHS;
  4831. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  4832. signedOperand = RHS;
  4833. unsignedOperand = LHS;
  4834. } else {
  4835. CheckTrivialUnsignedComparison(S, E);
  4836. return AnalyzeImpConvsInComparison(S, E);
  4837. }
  4838. // Otherwise, calculate the effective range of the signed operand.
  4839. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  4840. // Go ahead and analyze implicit conversions in the operands. Note
  4841. // that we skip the implicit conversions on both sides.
  4842. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  4843. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  4844. // If the signed range is non-negative, -Wsign-compare won't fire,
  4845. // but we should still check for comparisons which are always true
  4846. // or false.
  4847. if (signedRange.NonNegative)
  4848. return CheckTrivialUnsignedComparison(S, E);
  4849. // For (in)equality comparisons, if the unsigned operand is a
  4850. // constant which cannot collide with a overflowed signed operand,
  4851. // then reinterpreting the signed operand as unsigned will not
  4852. // change the result of the comparison.
  4853. if (E->isEqualityOp()) {
  4854. unsigned comparisonWidth = S.Context.getIntWidth(T);
  4855. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  4856. // We should never be unable to prove that the unsigned operand is
  4857. // non-negative.
  4858. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  4859. if (unsignedRange.Width < comparisonWidth)
  4860. return;
  4861. }
  4862. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  4863. S.PDiag(diag::warn_mixed_sign_comparison)
  4864. << LHS->getType() << RHS->getType()
  4865. << LHS->getSourceRange() << RHS->getSourceRange());
  4866. }
  4867. /// Analyzes an attempt to assign the given value to a bitfield.
  4868. ///
  4869. /// Returns true if there was something fishy about the attempt.
  4870. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  4871. SourceLocation InitLoc) {
  4872. assert(Bitfield->isBitField());
  4873. if (Bitfield->isInvalidDecl())
  4874. return false;
  4875. // White-list bool bitfields.
  4876. if (Bitfield->getType()->isBooleanType())
  4877. return false;
  4878. // Ignore value- or type-dependent expressions.
  4879. if (Bitfield->getBitWidth()->isValueDependent() ||
  4880. Bitfield->getBitWidth()->isTypeDependent() ||
  4881. Init->isValueDependent() ||
  4882. Init->isTypeDependent())
  4883. return false;
  4884. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  4885. llvm::APSInt Value;
  4886. if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
  4887. return false;
  4888. unsigned OriginalWidth = Value.getBitWidth();
  4889. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  4890. if (OriginalWidth <= FieldWidth)
  4891. return false;
  4892. // Compute the value which the bitfield will contain.
  4893. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  4894. TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
  4895. // Check whether the stored value is equal to the original value.
  4896. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  4897. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  4898. return false;
  4899. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  4900. // therefore don't strictly fit into a signed bitfield of width 1.
  4901. if (FieldWidth == 1 && Value == 1)
  4902. return false;
  4903. std::string PrettyValue = Value.toString(10);
  4904. std::string PrettyTrunc = TruncatedValue.toString(10);
  4905. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  4906. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  4907. << Init->getSourceRange();
  4908. return true;
  4909. }
  4910. /// Analyze the given simple or compound assignment for warning-worthy
  4911. /// operations.
  4912. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  4913. // Just recurse on the LHS.
  4914. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  4915. // We want to recurse on the RHS as normal unless we're assigning to
  4916. // a bitfield.
  4917. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  4918. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  4919. E->getOperatorLoc())) {
  4920. // Recurse, ignoring any implicit conversions on the RHS.
  4921. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  4922. E->getOperatorLoc());
  4923. }
  4924. }
  4925. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  4926. }
  4927. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  4928. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  4929. SourceLocation CContext, unsigned diag,
  4930. bool pruneControlFlow = false) {
  4931. if (pruneControlFlow) {
  4932. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  4933. S.PDiag(diag)
  4934. << SourceType << T << E->getSourceRange()
  4935. << SourceRange(CContext));
  4936. return;
  4937. }
  4938. S.Diag(E->getExprLoc(), diag)
  4939. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  4940. }
  4941. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  4942. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  4943. SourceLocation CContext, unsigned diag,
  4944. bool pruneControlFlow = false) {
  4945. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  4946. }
  4947. /// Diagnose an implicit cast from a literal expression. Does not warn when the
  4948. /// cast wouldn't lose information.
  4949. void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
  4950. SourceLocation CContext) {
  4951. // Try to convert the literal exactly to an integer. If we can, don't warn.
  4952. bool isExact = false;
  4953. const llvm::APFloat &Value = FL->getValue();
  4954. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  4955. T->hasUnsignedIntegerRepresentation());
  4956. if (Value.convertToInteger(IntegerValue,
  4957. llvm::APFloat::rmTowardZero, &isExact)
  4958. == llvm::APFloat::opOK && isExact)
  4959. return;
  4960. // FIXME: Force the precision of the source value down so we don't print
  4961. // digits which are usually useless (we don't really care here if we
  4962. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  4963. // would automatically print the shortest representation, but it's a bit
  4964. // tricky to implement.
  4965. SmallString<16> PrettySourceValue;
  4966. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  4967. precision = (precision * 59 + 195) / 196;
  4968. Value.toString(PrettySourceValue, precision);
  4969. SmallString<16> PrettyTargetValue;
  4970. if (T->isSpecificBuiltinType(BuiltinType::Bool))
  4971. PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
  4972. else
  4973. IntegerValue.toString(PrettyTargetValue);
  4974. S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
  4975. << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
  4976. << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
  4977. }
  4978. std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
  4979. if (!Range.Width) return "0";
  4980. llvm::APSInt ValueInRange = Value;
  4981. ValueInRange.setIsSigned(!Range.NonNegative);
  4982. ValueInRange = ValueInRange.trunc(Range.Width);
  4983. return ValueInRange.toString(10);
  4984. }
  4985. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  4986. if (!isa<ImplicitCastExpr>(Ex))
  4987. return false;
  4988. Expr *InnerE = Ex->IgnoreParenImpCasts();
  4989. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  4990. const Type *Source =
  4991. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  4992. if (Target->isDependentType())
  4993. return false;
  4994. const BuiltinType *FloatCandidateBT =
  4995. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  4996. const Type *BoolCandidateType = ToBool ? Target : Source;
  4997. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  4998. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  4999. }
  5000. void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  5001. SourceLocation CC) {
  5002. unsigned NumArgs = TheCall->getNumArgs();
  5003. for (unsigned i = 0; i < NumArgs; ++i) {
  5004. Expr *CurrA = TheCall->getArg(i);
  5005. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  5006. continue;
  5007. bool IsSwapped = ((i > 0) &&
  5008. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  5009. IsSwapped |= ((i < (NumArgs - 1)) &&
  5010. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  5011. if (IsSwapped) {
  5012. // Warn on this floating-point to bool conversion.
  5013. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  5014. CurrA->getType(), CC,
  5015. diag::warn_impcast_floating_point_to_bool);
  5016. }
  5017. }
  5018. }
  5019. void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  5020. SourceLocation CC, bool *ICContext = nullptr) {
  5021. if (E->isTypeDependent() || E->isValueDependent()) return;
  5022. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  5023. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  5024. if (Source == Target) return;
  5025. if (Target->isDependentType()) return;
  5026. // If the conversion context location is invalid don't complain. We also
  5027. // don't want to emit a warning if the issue occurs from the expansion of
  5028. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  5029. // delay this check as long as possible. Once we detect we are in that
  5030. // scenario, we just return.
  5031. if (CC.isInvalid())
  5032. return;
  5033. // Diagnose implicit casts to bool.
  5034. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  5035. if (isa<StringLiteral>(E))
  5036. // Warn on string literal to bool. Checks for string literals in logical
  5037. // and expressions, for instance, assert(0 && "error here"), are
  5038. // prevented by a check in AnalyzeImplicitConversions().
  5039. return DiagnoseImpCast(S, E, T, CC,
  5040. diag::warn_impcast_string_literal_to_bool);
  5041. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  5042. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  5043. // This covers the literal expressions that evaluate to Objective-C
  5044. // objects.
  5045. return DiagnoseImpCast(S, E, T, CC,
  5046. diag::warn_impcast_objective_c_literal_to_bool);
  5047. }
  5048. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  5049. // Warn on pointer to bool conversion that is always true.
  5050. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  5051. SourceRange(CC));
  5052. }
  5053. }
  5054. // Strip vector types.
  5055. if (isa<VectorType>(Source)) {
  5056. if (!isa<VectorType>(Target)) {
  5057. if (S.SourceMgr.isInSystemMacro(CC))
  5058. return;
  5059. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  5060. }
  5061. // If the vector cast is cast between two vectors of the same size, it is
  5062. // a bitcast, not a conversion.
  5063. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  5064. return;
  5065. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  5066. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  5067. }
  5068. if (auto VecTy = dyn_cast<VectorType>(Target))
  5069. Target = VecTy->getElementType().getTypePtr();
  5070. // Strip complex types.
  5071. if (isa<ComplexType>(Source)) {
  5072. if (!isa<ComplexType>(Target)) {
  5073. if (S.SourceMgr.isInSystemMacro(CC))
  5074. return;
  5075. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
  5076. }
  5077. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  5078. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  5079. }
  5080. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  5081. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  5082. // If the source is floating point...
  5083. if (SourceBT && SourceBT->isFloatingPoint()) {
  5084. // ...and the target is floating point...
  5085. if (TargetBT && TargetBT->isFloatingPoint()) {
  5086. // ...then warn if we're dropping FP rank.
  5087. // Builtin FP kinds are ordered by increasing FP rank.
  5088. if (SourceBT->getKind() > TargetBT->getKind()) {
  5089. // Don't warn about float constants that are precisely
  5090. // representable in the target type.
  5091. Expr::EvalResult result;
  5092. if (E->EvaluateAsRValue(result, S.Context)) {
  5093. // Value might be a float, a float vector, or a float complex.
  5094. if (IsSameFloatAfterCast(result.Val,
  5095. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  5096. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  5097. return;
  5098. }
  5099. if (S.SourceMgr.isInSystemMacro(CC))
  5100. return;
  5101. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  5102. }
  5103. return;
  5104. }
  5105. // If the target is integral, always warn.
  5106. if (TargetBT && TargetBT->isInteger()) {
  5107. if (S.SourceMgr.isInSystemMacro(CC))
  5108. return;
  5109. Expr *InnerE = E->IgnoreParenImpCasts();
  5110. // We also want to warn on, e.g., "int i = -1.234"
  5111. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  5112. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  5113. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  5114. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
  5115. DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
  5116. } else {
  5117. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
  5118. }
  5119. }
  5120. // If the target is bool, warn if expr is a function or method call.
  5121. if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
  5122. isa<CallExpr>(E)) {
  5123. // Check last argument of function call to see if it is an
  5124. // implicit cast from a type matching the type the result
  5125. // is being cast to.
  5126. CallExpr *CEx = cast<CallExpr>(E);
  5127. unsigned NumArgs = CEx->getNumArgs();
  5128. if (NumArgs > 0) {
  5129. Expr *LastA = CEx->getArg(NumArgs - 1);
  5130. Expr *InnerE = LastA->IgnoreParenImpCasts();
  5131. const Type *InnerType =
  5132. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  5133. if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
  5134. // Warn on this floating-point to bool conversion
  5135. DiagnoseImpCast(S, E, T, CC,
  5136. diag::warn_impcast_floating_point_to_bool);
  5137. }
  5138. }
  5139. }
  5140. return;
  5141. }
  5142. if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
  5143. == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
  5144. && !Target->isBlockPointerType() && !Target->isMemberPointerType()
  5145. && Target->isScalarType() && !Target->isNullPtrType()) {
  5146. SourceLocation Loc = E->getSourceRange().getBegin();
  5147. if (Loc.isMacroID())
  5148. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
  5149. if (!Loc.isMacroID() || CC.isMacroID())
  5150. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  5151. << T << clang::SourceRange(CC)
  5152. << FixItHint::CreateReplacement(Loc,
  5153. S.getFixItZeroLiteralForType(T, Loc));
  5154. }
  5155. if (!Source->isIntegerType() || !Target->isIntegerType())
  5156. return;
  5157. // TODO: remove this early return once the false positives for constant->bool
  5158. // in templates, macros, etc, are reduced or removed.
  5159. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  5160. return;
  5161. IntRange SourceRange = GetExprRange(S.Context, E);
  5162. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  5163. if (SourceRange.Width > TargetRange.Width) {
  5164. // If the source is a constant, use a default-on diagnostic.
  5165. // TODO: this should happen for bitfield stores, too.
  5166. llvm::APSInt Value(32);
  5167. if (E->isIntegerConstantExpr(Value, S.Context)) {
  5168. if (S.SourceMgr.isInSystemMacro(CC))
  5169. return;
  5170. std::string PrettySourceValue = Value.toString(10);
  5171. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  5172. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  5173. S.PDiag(diag::warn_impcast_integer_precision_constant)
  5174. << PrettySourceValue << PrettyTargetValue
  5175. << E->getType() << T << E->getSourceRange()
  5176. << clang::SourceRange(CC));
  5177. return;
  5178. }
  5179. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  5180. if (S.SourceMgr.isInSystemMacro(CC))
  5181. return;
  5182. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  5183. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  5184. /* pruneControlFlow */ true);
  5185. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  5186. }
  5187. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  5188. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  5189. SourceRange.Width == TargetRange.Width)) {
  5190. if (S.SourceMgr.isInSystemMacro(CC))
  5191. return;
  5192. unsigned DiagID = diag::warn_impcast_integer_sign;
  5193. // Traditionally, gcc has warned about this under -Wsign-compare.
  5194. // We also want to warn about it in -Wconversion.
  5195. // So if -Wconversion is off, use a completely identical diagnostic
  5196. // in the sign-compare group.
  5197. // The conditional-checking code will
  5198. if (ICContext) {
  5199. DiagID = diag::warn_impcast_integer_sign_conditional;
  5200. *ICContext = true;
  5201. }
  5202. return DiagnoseImpCast(S, E, T, CC, DiagID);
  5203. }
  5204. // Diagnose conversions between different enumeration types.
  5205. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  5206. // type, to give us better diagnostics.
  5207. QualType SourceType = E->getType();
  5208. if (!S.getLangOpts().CPlusPlus) {
  5209. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  5210. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  5211. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  5212. SourceType = S.Context.getTypeDeclType(Enum);
  5213. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  5214. }
  5215. }
  5216. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  5217. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  5218. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  5219. TargetEnum->getDecl()->hasNameForLinkage() &&
  5220. SourceEnum != TargetEnum) {
  5221. if (S.SourceMgr.isInSystemMacro(CC))
  5222. return;
  5223. return DiagnoseImpCast(S, E, SourceType, T, CC,
  5224. diag::warn_impcast_different_enum_types);
  5225. }
  5226. return;
  5227. }
  5228. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  5229. SourceLocation CC, QualType T);
  5230. void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  5231. SourceLocation CC, bool &ICContext) {
  5232. E = E->IgnoreParenImpCasts();
  5233. if (isa<ConditionalOperator>(E))
  5234. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  5235. AnalyzeImplicitConversions(S, E, CC);
  5236. if (E->getType() != T)
  5237. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  5238. return;
  5239. }
  5240. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  5241. SourceLocation CC, QualType T) {
  5242. AnalyzeImplicitConversions(S, E->getCond(), CC);
  5243. bool Suspicious = false;
  5244. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  5245. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  5246. // If -Wconversion would have warned about either of the candidates
  5247. // for a signedness conversion to the context type...
  5248. if (!Suspicious) return;
  5249. // ...but it's currently ignored...
  5250. if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
  5251. CC))
  5252. return;
  5253. // ...then check whether it would have warned about either of the
  5254. // candidates for a signedness conversion to the condition type.
  5255. if (E->getType() == T) return;
  5256. Suspicious = false;
  5257. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  5258. E->getType(), CC, &Suspicious);
  5259. if (!Suspicious)
  5260. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  5261. E->getType(), CC, &Suspicious);
  5262. }
  5263. /// AnalyzeImplicitConversions - Find and report any interesting
  5264. /// implicit conversions in the given expression. There are a couple
  5265. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  5266. void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
  5267. QualType T = OrigE->getType();
  5268. Expr *E = OrigE->IgnoreParenImpCasts();
  5269. if (E->isTypeDependent() || E->isValueDependent())
  5270. return;
  5271. // For conditional operators, we analyze the arguments as if they
  5272. // were being fed directly into the output.
  5273. if (isa<ConditionalOperator>(E)) {
  5274. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  5275. CheckConditionalOperator(S, CO, CC, T);
  5276. return;
  5277. }
  5278. // Check implicit argument conversions for function calls.
  5279. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  5280. CheckImplicitArgumentConversions(S, Call, CC);
  5281. // Go ahead and check any implicit conversions we might have skipped.
  5282. // The non-canonical typecheck is just an optimization;
  5283. // CheckImplicitConversion will filter out dead implicit conversions.
  5284. if (E->getType() != T)
  5285. CheckImplicitConversion(S, E, T, CC);
  5286. // Now continue drilling into this expression.
  5287. if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
  5288. if (POE->getResultExpr())
  5289. E = POE->getResultExpr();
  5290. }
  5291. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
  5292. return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  5293. // Skip past explicit casts.
  5294. if (isa<ExplicitCastExpr>(E)) {
  5295. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  5296. return AnalyzeImplicitConversions(S, E, CC);
  5297. }
  5298. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  5299. // Do a somewhat different check with comparison operators.
  5300. if (BO->isComparisonOp())
  5301. return AnalyzeComparison(S, BO);
  5302. // And with simple assignments.
  5303. if (BO->getOpcode() == BO_Assign)
  5304. return AnalyzeAssignment(S, BO);
  5305. }
  5306. // These break the otherwise-useful invariant below. Fortunately,
  5307. // we don't really need to recurse into them, because any internal
  5308. // expressions should have been analyzed already when they were
  5309. // built into statements.
  5310. if (isa<StmtExpr>(E)) return;
  5311. // Don't descend into unevaluated contexts.
  5312. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  5313. // Now just recurse over the expression's children.
  5314. CC = E->getExprLoc();
  5315. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  5316. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  5317. for (Stmt::child_range I = E->children(); I; ++I) {
  5318. Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
  5319. if (!ChildExpr)
  5320. continue;
  5321. if (IsLogicalAndOperator &&
  5322. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  5323. // Ignore checking string literals that are in logical and operators.
  5324. // This is a common pattern for asserts.
  5325. continue;
  5326. AnalyzeImplicitConversions(S, ChildExpr, CC);
  5327. }
  5328. }
  5329. } // end anonymous namespace
  5330. enum {
  5331. AddressOf,
  5332. FunctionPointer,
  5333. ArrayPointer
  5334. };
  5335. /// \brief Diagnose pointers that are always non-null.
  5336. /// \param E the expression containing the pointer
  5337. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  5338. /// compared to a null pointer
  5339. /// \param IsEqual True when the comparison is equal to a null pointer
  5340. /// \param Range Extra SourceRange to highlight in the diagnostic
  5341. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  5342. Expr::NullPointerConstantKind NullKind,
  5343. bool IsEqual, SourceRange Range) {
  5344. // Don't warn inside macros.
  5345. if (E->getExprLoc().isMacroID())
  5346. return;
  5347. E = E->IgnoreImpCasts();
  5348. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  5349. bool IsAddressOf = false;
  5350. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  5351. if (UO->getOpcode() != UO_AddrOf)
  5352. return;
  5353. IsAddressOf = true;
  5354. E = UO->getSubExpr();
  5355. }
  5356. // Expect to find a single Decl. Skip anything more complicated.
  5357. ValueDecl *D = nullptr;
  5358. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  5359. D = R->getDecl();
  5360. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  5361. D = M->getMemberDecl();
  5362. }
  5363. // Weak Decls can be null.
  5364. if (!D || D->isWeak())
  5365. return;
  5366. QualType T = D->getType();
  5367. const bool IsArray = T->isArrayType();
  5368. const bool IsFunction = T->isFunctionType();
  5369. if (IsAddressOf) {
  5370. // Address of function is used to silence the function warning.
  5371. if (IsFunction)
  5372. return;
  5373. // Address of reference can be null.
  5374. if (T->isReferenceType())
  5375. return;
  5376. }
  5377. // Found nothing.
  5378. if (!IsAddressOf && !IsFunction && !IsArray)
  5379. return;
  5380. // Pretty print the expression for the diagnostic.
  5381. std::string Str;
  5382. llvm::raw_string_ostream S(Str);
  5383. E->printPretty(S, nullptr, getPrintingPolicy());
  5384. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  5385. : diag::warn_impcast_pointer_to_bool;
  5386. unsigned DiagType;
  5387. if (IsAddressOf)
  5388. DiagType = AddressOf;
  5389. else if (IsFunction)
  5390. DiagType = FunctionPointer;
  5391. else if (IsArray)
  5392. DiagType = ArrayPointer;
  5393. else
  5394. llvm_unreachable("Could not determine diagnostic.");
  5395. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  5396. << Range << IsEqual;
  5397. if (!IsFunction)
  5398. return;
  5399. // Suggest '&' to silence the function warning.
  5400. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  5401. << FixItHint::CreateInsertion(E->getLocStart(), "&");
  5402. // Check to see if '()' fixit should be emitted.
  5403. QualType ReturnType;
  5404. UnresolvedSet<4> NonTemplateOverloads;
  5405. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  5406. if (ReturnType.isNull())
  5407. return;
  5408. if (IsCompare) {
  5409. // There are two cases here. If there is null constant, the only suggest
  5410. // for a pointer return type. If the null is 0, then suggest if the return
  5411. // type is a pointer or an integer type.
  5412. if (!ReturnType->isPointerType()) {
  5413. if (NullKind == Expr::NPCK_ZeroExpression ||
  5414. NullKind == Expr::NPCK_ZeroLiteral) {
  5415. if (!ReturnType->isIntegerType())
  5416. return;
  5417. } else {
  5418. return;
  5419. }
  5420. }
  5421. } else { // !IsCompare
  5422. // For function to bool, only suggest if the function pointer has bool
  5423. // return type.
  5424. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  5425. return;
  5426. }
  5427. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  5428. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
  5429. }
  5430. /// Diagnoses "dangerous" implicit conversions within the given
  5431. /// expression (which is a full expression). Implements -Wconversion
  5432. /// and -Wsign-compare.
  5433. ///
  5434. /// \param CC the "context" location of the implicit conversion, i.e.
  5435. /// the most location of the syntactic entity requiring the implicit
  5436. /// conversion
  5437. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  5438. // Don't diagnose in unevaluated contexts.
  5439. if (isUnevaluatedContext())
  5440. return;
  5441. // Don't diagnose for value- or type-dependent expressions.
  5442. if (E->isTypeDependent() || E->isValueDependent())
  5443. return;
  5444. // Check for array bounds violations in cases where the check isn't triggered
  5445. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  5446. // ArraySubscriptExpr is on the RHS of a variable initialization.
  5447. CheckArrayAccess(E);
  5448. // This is not the right CC for (e.g.) a variable initialization.
  5449. AnalyzeImplicitConversions(*this, E, CC);
  5450. }
  5451. /// Diagnose when expression is an integer constant expression and its evaluation
  5452. /// results in integer overflow
  5453. void Sema::CheckForIntOverflow (Expr *E) {
  5454. if (isa<BinaryOperator>(E->IgnoreParens()))
  5455. E->EvaluateForOverflow(Context);
  5456. }
  5457. namespace {
  5458. /// \brief Visitor for expressions which looks for unsequenced operations on the
  5459. /// same object.
  5460. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  5461. typedef EvaluatedExprVisitor<SequenceChecker> Base;
  5462. /// \brief A tree of sequenced regions within an expression. Two regions are
  5463. /// unsequenced if one is an ancestor or a descendent of the other. When we
  5464. /// finish processing an expression with sequencing, such as a comma
  5465. /// expression, we fold its tree nodes into its parent, since they are
  5466. /// unsequenced with respect to nodes we will visit later.
  5467. class SequenceTree {
  5468. struct Value {
  5469. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  5470. unsigned Parent : 31;
  5471. bool Merged : 1;
  5472. };
  5473. SmallVector<Value, 8> Values;
  5474. public:
  5475. /// \brief A region within an expression which may be sequenced with respect
  5476. /// to some other region.
  5477. class Seq {
  5478. explicit Seq(unsigned N) : Index(N) {}
  5479. unsigned Index;
  5480. friend class SequenceTree;
  5481. public:
  5482. Seq() : Index(0) {}
  5483. };
  5484. SequenceTree() { Values.push_back(Value(0)); }
  5485. Seq root() const { return Seq(0); }
  5486. /// \brief Create a new sequence of operations, which is an unsequenced
  5487. /// subset of \p Parent. This sequence of operations is sequenced with
  5488. /// respect to other children of \p Parent.
  5489. Seq allocate(Seq Parent) {
  5490. Values.push_back(Value(Parent.Index));
  5491. return Seq(Values.size() - 1);
  5492. }
  5493. /// \brief Merge a sequence of operations into its parent.
  5494. void merge(Seq S) {
  5495. Values[S.Index].Merged = true;
  5496. }
  5497. /// \brief Determine whether two operations are unsequenced. This operation
  5498. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  5499. /// should have been merged into its parent as appropriate.
  5500. bool isUnsequenced(Seq Cur, Seq Old) {
  5501. unsigned C = representative(Cur.Index);
  5502. unsigned Target = representative(Old.Index);
  5503. while (C >= Target) {
  5504. if (C == Target)
  5505. return true;
  5506. C = Values[C].Parent;
  5507. }
  5508. return false;
  5509. }
  5510. private:
  5511. /// \brief Pick a representative for a sequence.
  5512. unsigned representative(unsigned K) {
  5513. if (Values[K].Merged)
  5514. // Perform path compression as we go.
  5515. return Values[K].Parent = representative(Values[K].Parent);
  5516. return K;
  5517. }
  5518. };
  5519. /// An object for which we can track unsequenced uses.
  5520. typedef NamedDecl *Object;
  5521. /// Different flavors of object usage which we track. We only track the
  5522. /// least-sequenced usage of each kind.
  5523. enum UsageKind {
  5524. /// A read of an object. Multiple unsequenced reads are OK.
  5525. UK_Use,
  5526. /// A modification of an object which is sequenced before the value
  5527. /// computation of the expression, such as ++n in C++.
  5528. UK_ModAsValue,
  5529. /// A modification of an object which is not sequenced before the value
  5530. /// computation of the expression, such as n++.
  5531. UK_ModAsSideEffect,
  5532. UK_Count = UK_ModAsSideEffect + 1
  5533. };
  5534. struct Usage {
  5535. Usage() : Use(nullptr), Seq() {}
  5536. Expr *Use;
  5537. SequenceTree::Seq Seq;
  5538. };
  5539. struct UsageInfo {
  5540. UsageInfo() : Diagnosed(false) {}
  5541. Usage Uses[UK_Count];
  5542. /// Have we issued a diagnostic for this variable already?
  5543. bool Diagnosed;
  5544. };
  5545. typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
  5546. Sema &SemaRef;
  5547. /// Sequenced regions within the expression.
  5548. SequenceTree Tree;
  5549. /// Declaration modifications and references which we have seen.
  5550. UsageInfoMap UsageMap;
  5551. /// The region we are currently within.
  5552. SequenceTree::Seq Region;
  5553. /// Filled in with declarations which were modified as a side-effect
  5554. /// (that is, post-increment operations).
  5555. SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
  5556. /// Expressions to check later. We defer checking these to reduce
  5557. /// stack usage.
  5558. SmallVectorImpl<Expr *> &WorkList;
  5559. /// RAII object wrapping the visitation of a sequenced subexpression of an
  5560. /// expression. At the end of this process, the side-effects of the evaluation
  5561. /// become sequenced with respect to the value computation of the result, so
  5562. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  5563. /// UK_ModAsValue.
  5564. struct SequencedSubexpression {
  5565. SequencedSubexpression(SequenceChecker &Self)
  5566. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  5567. Self.ModAsSideEffect = &ModAsSideEffect;
  5568. }
  5569. ~SequencedSubexpression() {
  5570. for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
  5571. UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
  5572. U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
  5573. Self.addUsage(U, ModAsSideEffect[I].first,
  5574. ModAsSideEffect[I].second.Use, UK_ModAsValue);
  5575. }
  5576. Self.ModAsSideEffect = OldModAsSideEffect;
  5577. }
  5578. SequenceChecker &Self;
  5579. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  5580. SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
  5581. };
  5582. /// RAII object wrapping the visitation of a subexpression which we might
  5583. /// choose to evaluate as a constant. If any subexpression is evaluated and
  5584. /// found to be non-constant, this allows us to suppress the evaluation of
  5585. /// the outer expression.
  5586. class EvaluationTracker {
  5587. public:
  5588. EvaluationTracker(SequenceChecker &Self)
  5589. : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
  5590. Self.EvalTracker = this;
  5591. }
  5592. ~EvaluationTracker() {
  5593. Self.EvalTracker = Prev;
  5594. if (Prev)
  5595. Prev->EvalOK &= EvalOK;
  5596. }
  5597. bool evaluate(const Expr *E, bool &Result) {
  5598. if (!EvalOK || E->isValueDependent())
  5599. return false;
  5600. EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
  5601. return EvalOK;
  5602. }
  5603. private:
  5604. SequenceChecker &Self;
  5605. EvaluationTracker *Prev;
  5606. bool EvalOK;
  5607. } *EvalTracker;
  5608. /// \brief Find the object which is produced by the specified expression,
  5609. /// if any.
  5610. Object getObject(Expr *E, bool Mod) const {
  5611. E = E->IgnoreParenCasts();
  5612. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  5613. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  5614. return getObject(UO->getSubExpr(), Mod);
  5615. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  5616. if (BO->getOpcode() == BO_Comma)
  5617. return getObject(BO->getRHS(), Mod);
  5618. if (Mod && BO->isAssignmentOp())
  5619. return getObject(BO->getLHS(), Mod);
  5620. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  5621. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  5622. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  5623. return ME->getMemberDecl();
  5624. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  5625. // FIXME: If this is a reference, map through to its value.
  5626. return DRE->getDecl();
  5627. return nullptr;
  5628. }
  5629. /// \brief Note that an object was modified or used by an expression.
  5630. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  5631. Usage &U = UI.Uses[UK];
  5632. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  5633. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  5634. ModAsSideEffect->push_back(std::make_pair(O, U));
  5635. U.Use = Ref;
  5636. U.Seq = Region;
  5637. }
  5638. }
  5639. /// \brief Check whether a modification or use conflicts with a prior usage.
  5640. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  5641. bool IsModMod) {
  5642. if (UI.Diagnosed)
  5643. return;
  5644. const Usage &U = UI.Uses[OtherKind];
  5645. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  5646. return;
  5647. Expr *Mod = U.Use;
  5648. Expr *ModOrUse = Ref;
  5649. if (OtherKind == UK_Use)
  5650. std::swap(Mod, ModOrUse);
  5651. SemaRef.Diag(Mod->getExprLoc(),
  5652. IsModMod ? diag::warn_unsequenced_mod_mod
  5653. : diag::warn_unsequenced_mod_use)
  5654. << O << SourceRange(ModOrUse->getExprLoc());
  5655. UI.Diagnosed = true;
  5656. }
  5657. void notePreUse(Object O, Expr *Use) {
  5658. UsageInfo &U = UsageMap[O];
  5659. // Uses conflict with other modifications.
  5660. checkUsage(O, U, Use, UK_ModAsValue, false);
  5661. }
  5662. void notePostUse(Object O, Expr *Use) {
  5663. UsageInfo &U = UsageMap[O];
  5664. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  5665. addUsage(U, O, Use, UK_Use);
  5666. }
  5667. void notePreMod(Object O, Expr *Mod) {
  5668. UsageInfo &U = UsageMap[O];
  5669. // Modifications conflict with other modifications and with uses.
  5670. checkUsage(O, U, Mod, UK_ModAsValue, true);
  5671. checkUsage(O, U, Mod, UK_Use, false);
  5672. }
  5673. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  5674. UsageInfo &U = UsageMap[O];
  5675. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  5676. addUsage(U, O, Use, UK);
  5677. }
  5678. public:
  5679. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  5680. : Base(S.Context), SemaRef(S), Region(Tree.root()),
  5681. ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
  5682. Visit(E);
  5683. }
  5684. void VisitStmt(Stmt *S) {
  5685. // Skip all statements which aren't expressions for now.
  5686. }
  5687. void VisitExpr(Expr *E) {
  5688. // By default, just recurse to evaluated subexpressions.
  5689. Base::VisitStmt(E);
  5690. }
  5691. void VisitCastExpr(CastExpr *E) {
  5692. Object O = Object();
  5693. if (E->getCastKind() == CK_LValueToRValue)
  5694. O = getObject(E->getSubExpr(), false);
  5695. if (O)
  5696. notePreUse(O, E);
  5697. VisitExpr(E);
  5698. if (O)
  5699. notePostUse(O, E);
  5700. }
  5701. void VisitBinComma(BinaryOperator *BO) {
  5702. // C++11 [expr.comma]p1:
  5703. // Every value computation and side effect associated with the left
  5704. // expression is sequenced before every value computation and side
  5705. // effect associated with the right expression.
  5706. SequenceTree::Seq LHS = Tree.allocate(Region);
  5707. SequenceTree::Seq RHS = Tree.allocate(Region);
  5708. SequenceTree::Seq OldRegion = Region;
  5709. {
  5710. SequencedSubexpression SeqLHS(*this);
  5711. Region = LHS;
  5712. Visit(BO->getLHS());
  5713. }
  5714. Region = RHS;
  5715. Visit(BO->getRHS());
  5716. Region = OldRegion;
  5717. // Forget that LHS and RHS are sequenced. They are both unsequenced
  5718. // with respect to other stuff.
  5719. Tree.merge(LHS);
  5720. Tree.merge(RHS);
  5721. }
  5722. void VisitBinAssign(BinaryOperator *BO) {
  5723. // The modification is sequenced after the value computation of the LHS
  5724. // and RHS, so check it before inspecting the operands and update the
  5725. // map afterwards.
  5726. Object O = getObject(BO->getLHS(), true);
  5727. if (!O)
  5728. return VisitExpr(BO);
  5729. notePreMod(O, BO);
  5730. // C++11 [expr.ass]p7:
  5731. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  5732. // only once.
  5733. //
  5734. // Therefore, for a compound assignment operator, O is considered used
  5735. // everywhere except within the evaluation of E1 itself.
  5736. if (isa<CompoundAssignOperator>(BO))
  5737. notePreUse(O, BO);
  5738. Visit(BO->getLHS());
  5739. if (isa<CompoundAssignOperator>(BO))
  5740. notePostUse(O, BO);
  5741. Visit(BO->getRHS());
  5742. // C++11 [expr.ass]p1:
  5743. // the assignment is sequenced [...] before the value computation of the
  5744. // assignment expression.
  5745. // C11 6.5.16/3 has no such rule.
  5746. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  5747. : UK_ModAsSideEffect);
  5748. }
  5749. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  5750. VisitBinAssign(CAO);
  5751. }
  5752. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  5753. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  5754. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  5755. Object O = getObject(UO->getSubExpr(), true);
  5756. if (!O)
  5757. return VisitExpr(UO);
  5758. notePreMod(O, UO);
  5759. Visit(UO->getSubExpr());
  5760. // C++11 [expr.pre.incr]p1:
  5761. // the expression ++x is equivalent to x+=1
  5762. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  5763. : UK_ModAsSideEffect);
  5764. }
  5765. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  5766. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  5767. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  5768. Object O = getObject(UO->getSubExpr(), true);
  5769. if (!O)
  5770. return VisitExpr(UO);
  5771. notePreMod(O, UO);
  5772. Visit(UO->getSubExpr());
  5773. notePostMod(O, UO, UK_ModAsSideEffect);
  5774. }
  5775. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  5776. void VisitBinLOr(BinaryOperator *BO) {
  5777. // The side-effects of the LHS of an '&&' are sequenced before the
  5778. // value computation of the RHS, and hence before the value computation
  5779. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  5780. // as if they were unconditionally sequenced.
  5781. EvaluationTracker Eval(*this);
  5782. {
  5783. SequencedSubexpression Sequenced(*this);
  5784. Visit(BO->getLHS());
  5785. }
  5786. bool Result;
  5787. if (Eval.evaluate(BO->getLHS(), Result)) {
  5788. if (!Result)
  5789. Visit(BO->getRHS());
  5790. } else {
  5791. // Check for unsequenced operations in the RHS, treating it as an
  5792. // entirely separate evaluation.
  5793. //
  5794. // FIXME: If there are operations in the RHS which are unsequenced
  5795. // with respect to operations outside the RHS, and those operations
  5796. // are unconditionally evaluated, diagnose them.
  5797. WorkList.push_back(BO->getRHS());
  5798. }
  5799. }
  5800. void VisitBinLAnd(BinaryOperator *BO) {
  5801. EvaluationTracker Eval(*this);
  5802. {
  5803. SequencedSubexpression Sequenced(*this);
  5804. Visit(BO->getLHS());
  5805. }
  5806. bool Result;
  5807. if (Eval.evaluate(BO->getLHS(), Result)) {
  5808. if (Result)
  5809. Visit(BO->getRHS());
  5810. } else {
  5811. WorkList.push_back(BO->getRHS());
  5812. }
  5813. }
  5814. // Only visit the condition, unless we can be sure which subexpression will
  5815. // be chosen.
  5816. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  5817. EvaluationTracker Eval(*this);
  5818. {
  5819. SequencedSubexpression Sequenced(*this);
  5820. Visit(CO->getCond());
  5821. }
  5822. bool Result;
  5823. if (Eval.evaluate(CO->getCond(), Result))
  5824. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  5825. else {
  5826. WorkList.push_back(CO->getTrueExpr());
  5827. WorkList.push_back(CO->getFalseExpr());
  5828. }
  5829. }
  5830. void VisitCallExpr(CallExpr *CE) {
  5831. // C++11 [intro.execution]p15:
  5832. // When calling a function [...], every value computation and side effect
  5833. // associated with any argument expression, or with the postfix expression
  5834. // designating the called function, is sequenced before execution of every
  5835. // expression or statement in the body of the function [and thus before
  5836. // the value computation of its result].
  5837. SequencedSubexpression Sequenced(*this);
  5838. Base::VisitCallExpr(CE);
  5839. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  5840. }
  5841. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  5842. // This is a call, so all subexpressions are sequenced before the result.
  5843. SequencedSubexpression Sequenced(*this);
  5844. if (!CCE->isListInitialization())
  5845. return VisitExpr(CCE);
  5846. // In C++11, list initializations are sequenced.
  5847. SmallVector<SequenceTree::Seq, 32> Elts;
  5848. SequenceTree::Seq Parent = Region;
  5849. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  5850. E = CCE->arg_end();
  5851. I != E; ++I) {
  5852. Region = Tree.allocate(Parent);
  5853. Elts.push_back(Region);
  5854. Visit(*I);
  5855. }
  5856. // Forget that the initializers are sequenced.
  5857. Region = Parent;
  5858. for (unsigned I = 0; I < Elts.size(); ++I)
  5859. Tree.merge(Elts[I]);
  5860. }
  5861. void VisitInitListExpr(InitListExpr *ILE) {
  5862. if (!SemaRef.getLangOpts().CPlusPlus11)
  5863. return VisitExpr(ILE);
  5864. // In C++11, list initializations are sequenced.
  5865. SmallVector<SequenceTree::Seq, 32> Elts;
  5866. SequenceTree::Seq Parent = Region;
  5867. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  5868. Expr *E = ILE->getInit(I);
  5869. if (!E) continue;
  5870. Region = Tree.allocate(Parent);
  5871. Elts.push_back(Region);
  5872. Visit(E);
  5873. }
  5874. // Forget that the initializers are sequenced.
  5875. Region = Parent;
  5876. for (unsigned I = 0; I < Elts.size(); ++I)
  5877. Tree.merge(Elts[I]);
  5878. }
  5879. };
  5880. }
  5881. void Sema::CheckUnsequencedOperations(Expr *E) {
  5882. SmallVector<Expr *, 8> WorkList;
  5883. WorkList.push_back(E);
  5884. while (!WorkList.empty()) {
  5885. Expr *Item = WorkList.pop_back_val();
  5886. SequenceChecker(*this, Item, WorkList);
  5887. }
  5888. }
  5889. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  5890. bool IsConstexpr) {
  5891. CheckImplicitConversions(E, CheckLoc);
  5892. CheckUnsequencedOperations(E);
  5893. if (!IsConstexpr && !E->isValueDependent())
  5894. CheckForIntOverflow(E);
  5895. }
  5896. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  5897. FieldDecl *BitField,
  5898. Expr *Init) {
  5899. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  5900. }
  5901. /// CheckParmsForFunctionDef - Check that the parameters of the given
  5902. /// function are appropriate for the definition of a function. This
  5903. /// takes care of any checks that cannot be performed on the
  5904. /// declaration itself, e.g., that the types of each of the function
  5905. /// parameters are complete.
  5906. bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
  5907. ParmVarDecl *const *PEnd,
  5908. bool CheckParameterNames) {
  5909. bool HasInvalidParm = false;
  5910. for (; P != PEnd; ++P) {
  5911. ParmVarDecl *Param = *P;
  5912. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  5913. // function declarator that is part of a function definition of
  5914. // that function shall not have incomplete type.
  5915. //
  5916. // This is also C++ [dcl.fct]p6.
  5917. if (!Param->isInvalidDecl() &&
  5918. RequireCompleteType(Param->getLocation(), Param->getType(),
  5919. diag::err_typecheck_decl_incomplete_type)) {
  5920. Param->setInvalidDecl();
  5921. HasInvalidParm = true;
  5922. }
  5923. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  5924. // declaration of each parameter shall include an identifier.
  5925. if (CheckParameterNames &&
  5926. Param->getIdentifier() == nullptr &&
  5927. !Param->isImplicit() &&
  5928. !getLangOpts().CPlusPlus)
  5929. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  5930. // C99 6.7.5.3p12:
  5931. // If the function declarator is not part of a definition of that
  5932. // function, parameters may have incomplete type and may use the [*]
  5933. // notation in their sequences of declarator specifiers to specify
  5934. // variable length array types.
  5935. QualType PType = Param->getOriginalType();
  5936. while (const ArrayType *AT = Context.getAsArrayType(PType)) {
  5937. if (AT->getSizeModifier() == ArrayType::Star) {
  5938. // FIXME: This diagnostic should point the '[*]' if source-location
  5939. // information is added for it.
  5940. Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
  5941. break;
  5942. }
  5943. PType= AT->getElementType();
  5944. }
  5945. // MSVC destroys objects passed by value in the callee. Therefore a
  5946. // function definition which takes such a parameter must be able to call the
  5947. // object's destructor. However, we don't perform any direct access check
  5948. // on the dtor.
  5949. if (getLangOpts().CPlusPlus && Context.getTargetInfo()
  5950. .getCXXABI()
  5951. .areArgsDestroyedLeftToRightInCallee()) {
  5952. if (!Param->isInvalidDecl()) {
  5953. if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
  5954. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  5955. if (!ClassDecl->isInvalidDecl() &&
  5956. !ClassDecl->hasIrrelevantDestructor() &&
  5957. !ClassDecl->isDependentContext()) {
  5958. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  5959. MarkFunctionReferenced(Param->getLocation(), Destructor);
  5960. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  5961. }
  5962. }
  5963. }
  5964. }
  5965. }
  5966. return HasInvalidParm;
  5967. }
  5968. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  5969. /// pointer cast increases the alignment requirements.
  5970. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  5971. // This is actually a lot of work to potentially be doing on every
  5972. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  5973. if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
  5974. TRange.getBegin())
  5975. == DiagnosticsEngine::Ignored)
  5976. return;
  5977. // Ignore dependent types.
  5978. if (T->isDependentType() || Op->getType()->isDependentType())
  5979. return;
  5980. // Require that the destination be a pointer type.
  5981. const PointerType *DestPtr = T->getAs<PointerType>();
  5982. if (!DestPtr) return;
  5983. // If the destination has alignment 1, we're done.
  5984. QualType DestPointee = DestPtr->getPointeeType();
  5985. if (DestPointee->isIncompleteType()) return;
  5986. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  5987. if (DestAlign.isOne()) return;
  5988. // Require that the source be a pointer type.
  5989. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  5990. if (!SrcPtr) return;
  5991. QualType SrcPointee = SrcPtr->getPointeeType();
  5992. // Whitelist casts from cv void*. We already implicitly
  5993. // whitelisted casts to cv void*, since they have alignment 1.
  5994. // Also whitelist casts involving incomplete types, which implicitly
  5995. // includes 'void'.
  5996. if (SrcPointee->isIncompleteType()) return;
  5997. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  5998. if (SrcAlign >= DestAlign) return;
  5999. Diag(TRange.getBegin(), diag::warn_cast_align)
  6000. << Op->getType() << T
  6001. << static_cast<unsigned>(SrcAlign.getQuantity())
  6002. << static_cast<unsigned>(DestAlign.getQuantity())
  6003. << TRange << Op->getSourceRange();
  6004. }
  6005. static const Type* getElementType(const Expr *BaseExpr) {
  6006. const Type* EltType = BaseExpr->getType().getTypePtr();
  6007. if (EltType->isAnyPointerType())
  6008. return EltType->getPointeeType().getTypePtr();
  6009. else if (EltType->isArrayType())
  6010. return EltType->getBaseElementTypeUnsafe();
  6011. return EltType;
  6012. }
  6013. /// \brief Check whether this array fits the idiom of a size-one tail padded
  6014. /// array member of a struct.
  6015. ///
  6016. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  6017. /// commonly used to emulate flexible arrays in C89 code.
  6018. static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
  6019. const NamedDecl *ND) {
  6020. if (Size != 1 || !ND) return false;
  6021. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  6022. if (!FD) return false;
  6023. // Don't consider sizes resulting from macro expansions or template argument
  6024. // substitution to form C89 tail-padded arrays.
  6025. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  6026. while (TInfo) {
  6027. TypeLoc TL = TInfo->getTypeLoc();
  6028. // Look through typedefs.
  6029. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  6030. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  6031. TInfo = TDL->getTypeSourceInfo();
  6032. continue;
  6033. }
  6034. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  6035. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  6036. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  6037. return false;
  6038. }
  6039. break;
  6040. }
  6041. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  6042. if (!RD) return false;
  6043. if (RD->isUnion()) return false;
  6044. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  6045. if (!CRD->isStandardLayout()) return false;
  6046. }
  6047. // See if this is the last field decl in the record.
  6048. const Decl *D = FD;
  6049. while ((D = D->getNextDeclInContext()))
  6050. if (isa<FieldDecl>(D))
  6051. return false;
  6052. return true;
  6053. }
  6054. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  6055. const ArraySubscriptExpr *ASE,
  6056. bool AllowOnePastEnd, bool IndexNegated) {
  6057. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  6058. if (IndexExpr->isValueDependent())
  6059. return;
  6060. const Type *EffectiveType = getElementType(BaseExpr);
  6061. BaseExpr = BaseExpr->IgnoreParenCasts();
  6062. const ConstantArrayType *ArrayTy =
  6063. Context.getAsConstantArrayType(BaseExpr->getType());
  6064. if (!ArrayTy)
  6065. return;
  6066. llvm::APSInt index;
  6067. if (!IndexExpr->EvaluateAsInt(index, Context))
  6068. return;
  6069. if (IndexNegated)
  6070. index = -index;
  6071. const NamedDecl *ND = nullptr;
  6072. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  6073. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  6074. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  6075. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  6076. if (index.isUnsigned() || !index.isNegative()) {
  6077. llvm::APInt size = ArrayTy->getSize();
  6078. if (!size.isStrictlyPositive())
  6079. return;
  6080. const Type* BaseType = getElementType(BaseExpr);
  6081. if (BaseType != EffectiveType) {
  6082. // Make sure we're comparing apples to apples when comparing index to size
  6083. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  6084. uint64_t array_typesize = Context.getTypeSize(BaseType);
  6085. // Handle ptrarith_typesize being zero, such as when casting to void*
  6086. if (!ptrarith_typesize) ptrarith_typesize = 1;
  6087. if (ptrarith_typesize != array_typesize) {
  6088. // There's a cast to a different size type involved
  6089. uint64_t ratio = array_typesize / ptrarith_typesize;
  6090. // TODO: Be smarter about handling cases where array_typesize is not a
  6091. // multiple of ptrarith_typesize
  6092. if (ptrarith_typesize * ratio == array_typesize)
  6093. size *= llvm::APInt(size.getBitWidth(), ratio);
  6094. }
  6095. }
  6096. if (size.getBitWidth() > index.getBitWidth())
  6097. index = index.zext(size.getBitWidth());
  6098. else if (size.getBitWidth() < index.getBitWidth())
  6099. size = size.zext(index.getBitWidth());
  6100. // For array subscripting the index must be less than size, but for pointer
  6101. // arithmetic also allow the index (offset) to be equal to size since
  6102. // computing the next address after the end of the array is legal and
  6103. // commonly done e.g. in C++ iterators and range-based for loops.
  6104. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  6105. return;
  6106. // Also don't warn for arrays of size 1 which are members of some
  6107. // structure. These are often used to approximate flexible arrays in C89
  6108. // code.
  6109. if (IsTailPaddedMemberArray(*this, size, ND))
  6110. return;
  6111. // Suppress the warning if the subscript expression (as identified by the
  6112. // ']' location) and the index expression are both from macro expansions
  6113. // within a system header.
  6114. if (ASE) {
  6115. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  6116. ASE->getRBracketLoc());
  6117. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  6118. SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
  6119. IndexExpr->getLocStart());
  6120. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  6121. return;
  6122. }
  6123. }
  6124. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  6125. if (ASE)
  6126. DiagID = diag::warn_array_index_exceeds_bounds;
  6127. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  6128. PDiag(DiagID) << index.toString(10, true)
  6129. << size.toString(10, true)
  6130. << (unsigned)size.getLimitedValue(~0U)
  6131. << IndexExpr->getSourceRange());
  6132. } else {
  6133. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  6134. if (!ASE) {
  6135. DiagID = diag::warn_ptr_arith_precedes_bounds;
  6136. if (index.isNegative()) index = -index;
  6137. }
  6138. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  6139. PDiag(DiagID) << index.toString(10, true)
  6140. << IndexExpr->getSourceRange());
  6141. }
  6142. if (!ND) {
  6143. // Try harder to find a NamedDecl to point at in the note.
  6144. while (const ArraySubscriptExpr *ASE =
  6145. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  6146. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  6147. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  6148. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  6149. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  6150. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  6151. }
  6152. if (ND)
  6153. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  6154. PDiag(diag::note_array_index_out_of_bounds)
  6155. << ND->getDeclName());
  6156. }
  6157. void Sema::CheckArrayAccess(const Expr *expr) {
  6158. int AllowOnePastEnd = 0;
  6159. while (expr) {
  6160. expr = expr->IgnoreParenImpCasts();
  6161. switch (expr->getStmtClass()) {
  6162. case Stmt::ArraySubscriptExprClass: {
  6163. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  6164. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  6165. AllowOnePastEnd > 0);
  6166. return;
  6167. }
  6168. case Stmt::UnaryOperatorClass: {
  6169. // Only unwrap the * and & unary operators
  6170. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  6171. expr = UO->getSubExpr();
  6172. switch (UO->getOpcode()) {
  6173. case UO_AddrOf:
  6174. AllowOnePastEnd++;
  6175. break;
  6176. case UO_Deref:
  6177. AllowOnePastEnd--;
  6178. break;
  6179. default:
  6180. return;
  6181. }
  6182. break;
  6183. }
  6184. case Stmt::ConditionalOperatorClass: {
  6185. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  6186. if (const Expr *lhs = cond->getLHS())
  6187. CheckArrayAccess(lhs);
  6188. if (const Expr *rhs = cond->getRHS())
  6189. CheckArrayAccess(rhs);
  6190. return;
  6191. }
  6192. default:
  6193. return;
  6194. }
  6195. }
  6196. }
  6197. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  6198. namespace {
  6199. struct RetainCycleOwner {
  6200. RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
  6201. VarDecl *Variable;
  6202. SourceRange Range;
  6203. SourceLocation Loc;
  6204. bool Indirect;
  6205. void setLocsFrom(Expr *e) {
  6206. Loc = e->getExprLoc();
  6207. Range = e->getSourceRange();
  6208. }
  6209. };
  6210. }
  6211. /// Consider whether capturing the given variable can possibly lead to
  6212. /// a retain cycle.
  6213. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  6214. // In ARC, it's captured strongly iff the variable has __strong
  6215. // lifetime. In MRR, it's captured strongly if the variable is
  6216. // __block and has an appropriate type.
  6217. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  6218. return false;
  6219. owner.Variable = var;
  6220. if (ref)
  6221. owner.setLocsFrom(ref);
  6222. return true;
  6223. }
  6224. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  6225. while (true) {
  6226. e = e->IgnoreParens();
  6227. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  6228. switch (cast->getCastKind()) {
  6229. case CK_BitCast:
  6230. case CK_LValueBitCast:
  6231. case CK_LValueToRValue:
  6232. case CK_ARCReclaimReturnedObject:
  6233. e = cast->getSubExpr();
  6234. continue;
  6235. default:
  6236. return false;
  6237. }
  6238. }
  6239. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  6240. ObjCIvarDecl *ivar = ref->getDecl();
  6241. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  6242. return false;
  6243. // Try to find a retain cycle in the base.
  6244. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  6245. return false;
  6246. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  6247. owner.Indirect = true;
  6248. return true;
  6249. }
  6250. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  6251. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  6252. if (!var) return false;
  6253. return considerVariable(var, ref, owner);
  6254. }
  6255. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  6256. if (member->isArrow()) return false;
  6257. // Don't count this as an indirect ownership.
  6258. e = member->getBase();
  6259. continue;
  6260. }
  6261. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  6262. // Only pay attention to pseudo-objects on property references.
  6263. ObjCPropertyRefExpr *pre
  6264. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  6265. ->IgnoreParens());
  6266. if (!pre) return false;
  6267. if (pre->isImplicitProperty()) return false;
  6268. ObjCPropertyDecl *property = pre->getExplicitProperty();
  6269. if (!property->isRetaining() &&
  6270. !(property->getPropertyIvarDecl() &&
  6271. property->getPropertyIvarDecl()->getType()
  6272. .getObjCLifetime() == Qualifiers::OCL_Strong))
  6273. return false;
  6274. owner.Indirect = true;
  6275. if (pre->isSuperReceiver()) {
  6276. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  6277. if (!owner.Variable)
  6278. return false;
  6279. owner.Loc = pre->getLocation();
  6280. owner.Range = pre->getSourceRange();
  6281. return true;
  6282. }
  6283. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  6284. ->getSourceExpr());
  6285. continue;
  6286. }
  6287. // Array ivars?
  6288. return false;
  6289. }
  6290. }
  6291. namespace {
  6292. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  6293. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  6294. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  6295. Variable(variable), Capturer(nullptr) {}
  6296. VarDecl *Variable;
  6297. Expr *Capturer;
  6298. void VisitDeclRefExpr(DeclRefExpr *ref) {
  6299. if (ref->getDecl() == Variable && !Capturer)
  6300. Capturer = ref;
  6301. }
  6302. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  6303. if (Capturer) return;
  6304. Visit(ref->getBase());
  6305. if (Capturer && ref->isFreeIvar())
  6306. Capturer = ref;
  6307. }
  6308. void VisitBlockExpr(BlockExpr *block) {
  6309. // Look inside nested blocks
  6310. if (block->getBlockDecl()->capturesVariable(Variable))
  6311. Visit(block->getBlockDecl()->getBody());
  6312. }
  6313. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  6314. if (Capturer) return;
  6315. if (OVE->getSourceExpr())
  6316. Visit(OVE->getSourceExpr());
  6317. }
  6318. };
  6319. }
  6320. /// Check whether the given argument is a block which captures a
  6321. /// variable.
  6322. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  6323. assert(owner.Variable && owner.Loc.isValid());
  6324. e = e->IgnoreParenCasts();
  6325. // Look through [^{...} copy] and Block_copy(^{...}).
  6326. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  6327. Selector Cmd = ME->getSelector();
  6328. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  6329. e = ME->getInstanceReceiver();
  6330. if (!e)
  6331. return nullptr;
  6332. e = e->IgnoreParenCasts();
  6333. }
  6334. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  6335. if (CE->getNumArgs() == 1) {
  6336. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  6337. if (Fn) {
  6338. const IdentifierInfo *FnI = Fn->getIdentifier();
  6339. if (FnI && FnI->isStr("_Block_copy")) {
  6340. e = CE->getArg(0)->IgnoreParenCasts();
  6341. }
  6342. }
  6343. }
  6344. }
  6345. BlockExpr *block = dyn_cast<BlockExpr>(e);
  6346. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  6347. return nullptr;
  6348. FindCaptureVisitor visitor(S.Context, owner.Variable);
  6349. visitor.Visit(block->getBlockDecl()->getBody());
  6350. return visitor.Capturer;
  6351. }
  6352. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  6353. RetainCycleOwner &owner) {
  6354. assert(capturer);
  6355. assert(owner.Variable && owner.Loc.isValid());
  6356. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  6357. << owner.Variable << capturer->getSourceRange();
  6358. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  6359. << owner.Indirect << owner.Range;
  6360. }
  6361. /// Check for a keyword selector that starts with the word 'add' or
  6362. /// 'set'.
  6363. static bool isSetterLikeSelector(Selector sel) {
  6364. if (sel.isUnarySelector()) return false;
  6365. StringRef str = sel.getNameForSlot(0);
  6366. while (!str.empty() && str.front() == '_') str = str.substr(1);
  6367. if (str.startswith("set"))
  6368. str = str.substr(3);
  6369. else if (str.startswith("add")) {
  6370. // Specially whitelist 'addOperationWithBlock:'.
  6371. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  6372. return false;
  6373. str = str.substr(3);
  6374. }
  6375. else
  6376. return false;
  6377. if (str.empty()) return true;
  6378. return !isLowercase(str.front());
  6379. }
  6380. /// Check a message send to see if it's likely to cause a retain cycle.
  6381. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  6382. // Only check instance methods whose selector looks like a setter.
  6383. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  6384. return;
  6385. // Try to find a variable that the receiver is strongly owned by.
  6386. RetainCycleOwner owner;
  6387. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  6388. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  6389. return;
  6390. } else {
  6391. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  6392. owner.Variable = getCurMethodDecl()->getSelfDecl();
  6393. owner.Loc = msg->getSuperLoc();
  6394. owner.Range = msg->getSuperLoc();
  6395. }
  6396. // Check whether the receiver is captured by any of the arguments.
  6397. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
  6398. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
  6399. return diagnoseRetainCycle(*this, capturer, owner);
  6400. }
  6401. /// Check a property assign to see if it's likely to cause a retain cycle.
  6402. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  6403. RetainCycleOwner owner;
  6404. if (!findRetainCycleOwner(*this, receiver, owner))
  6405. return;
  6406. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  6407. diagnoseRetainCycle(*this, capturer, owner);
  6408. }
  6409. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  6410. RetainCycleOwner Owner;
  6411. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  6412. return;
  6413. // Because we don't have an expression for the variable, we have to set the
  6414. // location explicitly here.
  6415. Owner.Loc = Var->getLocation();
  6416. Owner.Range = Var->getSourceRange();
  6417. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  6418. diagnoseRetainCycle(*this, Capturer, Owner);
  6419. }
  6420. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  6421. Expr *RHS, bool isProperty) {
  6422. // Check if RHS is an Objective-C object literal, which also can get
  6423. // immediately zapped in a weak reference. Note that we explicitly
  6424. // allow ObjCStringLiterals, since those are designed to never really die.
  6425. RHS = RHS->IgnoreParenImpCasts();
  6426. // This enum needs to match with the 'select' in
  6427. // warn_objc_arc_literal_assign (off-by-1).
  6428. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  6429. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  6430. return false;
  6431. S.Diag(Loc, diag::warn_arc_literal_assign)
  6432. << (unsigned) Kind
  6433. << (isProperty ? 0 : 1)
  6434. << RHS->getSourceRange();
  6435. return true;
  6436. }
  6437. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  6438. Qualifiers::ObjCLifetime LT,
  6439. Expr *RHS, bool isProperty) {
  6440. // Strip off any implicit cast added to get to the one ARC-specific.
  6441. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  6442. if (cast->getCastKind() == CK_ARCConsumeObject) {
  6443. S.Diag(Loc, diag::warn_arc_retained_assign)
  6444. << (LT == Qualifiers::OCL_ExplicitNone)
  6445. << (isProperty ? 0 : 1)
  6446. << RHS->getSourceRange();
  6447. return true;
  6448. }
  6449. RHS = cast->getSubExpr();
  6450. }
  6451. if (LT == Qualifiers::OCL_Weak &&
  6452. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  6453. return true;
  6454. return false;
  6455. }
  6456. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  6457. QualType LHS, Expr *RHS) {
  6458. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  6459. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  6460. return false;
  6461. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  6462. return true;
  6463. return false;
  6464. }
  6465. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  6466. Expr *LHS, Expr *RHS) {
  6467. QualType LHSType;
  6468. // PropertyRef on LHS type need be directly obtained from
  6469. // its declaration as it has a PseudoType.
  6470. ObjCPropertyRefExpr *PRE
  6471. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  6472. if (PRE && !PRE->isImplicitProperty()) {
  6473. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  6474. if (PD)
  6475. LHSType = PD->getType();
  6476. }
  6477. if (LHSType.isNull())
  6478. LHSType = LHS->getType();
  6479. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  6480. if (LT == Qualifiers::OCL_Weak) {
  6481. DiagnosticsEngine::Level Level =
  6482. Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
  6483. if (Level != DiagnosticsEngine::Ignored)
  6484. getCurFunction()->markSafeWeakUse(LHS);
  6485. }
  6486. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  6487. return;
  6488. // FIXME. Check for other life times.
  6489. if (LT != Qualifiers::OCL_None)
  6490. return;
  6491. if (PRE) {
  6492. if (PRE->isImplicitProperty())
  6493. return;
  6494. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  6495. if (!PD)
  6496. return;
  6497. unsigned Attributes = PD->getPropertyAttributes();
  6498. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  6499. // when 'assign' attribute was not explicitly specified
  6500. // by user, ignore it and rely on property type itself
  6501. // for lifetime info.
  6502. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  6503. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  6504. LHSType->isObjCRetainableType())
  6505. return;
  6506. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  6507. if (cast->getCastKind() == CK_ARCConsumeObject) {
  6508. Diag(Loc, diag::warn_arc_retained_property_assign)
  6509. << RHS->getSourceRange();
  6510. return;
  6511. }
  6512. RHS = cast->getSubExpr();
  6513. }
  6514. }
  6515. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  6516. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  6517. return;
  6518. }
  6519. }
  6520. }
  6521. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  6522. namespace {
  6523. bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  6524. SourceLocation StmtLoc,
  6525. const NullStmt *Body) {
  6526. // Do not warn if the body is a macro that expands to nothing, e.g:
  6527. //
  6528. // #define CALL(x)
  6529. // if (condition)
  6530. // CALL(0);
  6531. //
  6532. if (Body->hasLeadingEmptyMacro())
  6533. return false;
  6534. // Get line numbers of statement and body.
  6535. bool StmtLineInvalid;
  6536. unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
  6537. &StmtLineInvalid);
  6538. if (StmtLineInvalid)
  6539. return false;
  6540. bool BodyLineInvalid;
  6541. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  6542. &BodyLineInvalid);
  6543. if (BodyLineInvalid)
  6544. return false;
  6545. // Warn if null statement and body are on the same line.
  6546. if (StmtLine != BodyLine)
  6547. return false;
  6548. return true;
  6549. }
  6550. } // Unnamed namespace
  6551. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  6552. const Stmt *Body,
  6553. unsigned DiagID) {
  6554. // Since this is a syntactic check, don't emit diagnostic for template
  6555. // instantiations, this just adds noise.
  6556. if (CurrentInstantiationScope)
  6557. return;
  6558. // The body should be a null statement.
  6559. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  6560. if (!NBody)
  6561. return;
  6562. // Do the usual checks.
  6563. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  6564. return;
  6565. Diag(NBody->getSemiLoc(), DiagID);
  6566. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  6567. }
  6568. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  6569. const Stmt *PossibleBody) {
  6570. assert(!CurrentInstantiationScope); // Ensured by caller
  6571. SourceLocation StmtLoc;
  6572. const Stmt *Body;
  6573. unsigned DiagID;
  6574. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  6575. StmtLoc = FS->getRParenLoc();
  6576. Body = FS->getBody();
  6577. DiagID = diag::warn_empty_for_body;
  6578. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  6579. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  6580. Body = WS->getBody();
  6581. DiagID = diag::warn_empty_while_body;
  6582. } else
  6583. return; // Neither `for' nor `while'.
  6584. // The body should be a null statement.
  6585. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  6586. if (!NBody)
  6587. return;
  6588. // Skip expensive checks if diagnostic is disabled.
  6589. if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
  6590. DiagnosticsEngine::Ignored)
  6591. return;
  6592. // Do the usual checks.
  6593. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  6594. return;
  6595. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  6596. // noise level low, emit diagnostics only if for/while is followed by a
  6597. // CompoundStmt, e.g.:
  6598. // for (int i = 0; i < n; i++);
  6599. // {
  6600. // a(i);
  6601. // }
  6602. // or if for/while is followed by a statement with more indentation
  6603. // than for/while itself:
  6604. // for (int i = 0; i < n; i++);
  6605. // a(i);
  6606. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  6607. if (!ProbableTypo) {
  6608. bool BodyColInvalid;
  6609. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  6610. PossibleBody->getLocStart(),
  6611. &BodyColInvalid);
  6612. if (BodyColInvalid)
  6613. return;
  6614. bool StmtColInvalid;
  6615. unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
  6616. S->getLocStart(),
  6617. &StmtColInvalid);
  6618. if (StmtColInvalid)
  6619. return;
  6620. if (BodyCol > StmtCol)
  6621. ProbableTypo = true;
  6622. }
  6623. if (ProbableTypo) {
  6624. Diag(NBody->getSemiLoc(), DiagID);
  6625. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  6626. }
  6627. }
  6628. //===--- Layout compatibility ----------------------------------------------//
  6629. namespace {
  6630. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  6631. /// \brief Check if two enumeration types are layout-compatible.
  6632. bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  6633. // C++11 [dcl.enum] p8:
  6634. // Two enumeration types are layout-compatible if they have the same
  6635. // underlying type.
  6636. return ED1->isComplete() && ED2->isComplete() &&
  6637. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  6638. }
  6639. /// \brief Check if two fields are layout-compatible.
  6640. bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
  6641. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  6642. return false;
  6643. if (Field1->isBitField() != Field2->isBitField())
  6644. return false;
  6645. if (Field1->isBitField()) {
  6646. // Make sure that the bit-fields are the same length.
  6647. unsigned Bits1 = Field1->getBitWidthValue(C);
  6648. unsigned Bits2 = Field2->getBitWidthValue(C);
  6649. if (Bits1 != Bits2)
  6650. return false;
  6651. }
  6652. return true;
  6653. }
  6654. /// \brief Check if two standard-layout structs are layout-compatible.
  6655. /// (C++11 [class.mem] p17)
  6656. bool isLayoutCompatibleStruct(ASTContext &C,
  6657. RecordDecl *RD1,
  6658. RecordDecl *RD2) {
  6659. // If both records are C++ classes, check that base classes match.
  6660. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  6661. // If one of records is a CXXRecordDecl we are in C++ mode,
  6662. // thus the other one is a CXXRecordDecl, too.
  6663. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  6664. // Check number of base classes.
  6665. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  6666. return false;
  6667. // Check the base classes.
  6668. for (CXXRecordDecl::base_class_const_iterator
  6669. Base1 = D1CXX->bases_begin(),
  6670. BaseEnd1 = D1CXX->bases_end(),
  6671. Base2 = D2CXX->bases_begin();
  6672. Base1 != BaseEnd1;
  6673. ++Base1, ++Base2) {
  6674. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  6675. return false;
  6676. }
  6677. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  6678. // If only RD2 is a C++ class, it should have zero base classes.
  6679. if (D2CXX->getNumBases() > 0)
  6680. return false;
  6681. }
  6682. // Check the fields.
  6683. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  6684. Field2End = RD2->field_end(),
  6685. Field1 = RD1->field_begin(),
  6686. Field1End = RD1->field_end();
  6687. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  6688. if (!isLayoutCompatible(C, *Field1, *Field2))
  6689. return false;
  6690. }
  6691. if (Field1 != Field1End || Field2 != Field2End)
  6692. return false;
  6693. return true;
  6694. }
  6695. /// \brief Check if two standard-layout unions are layout-compatible.
  6696. /// (C++11 [class.mem] p18)
  6697. bool isLayoutCompatibleUnion(ASTContext &C,
  6698. RecordDecl *RD1,
  6699. RecordDecl *RD2) {
  6700. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  6701. for (auto *Field2 : RD2->fields())
  6702. UnmatchedFields.insert(Field2);
  6703. for (auto *Field1 : RD1->fields()) {
  6704. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  6705. I = UnmatchedFields.begin(),
  6706. E = UnmatchedFields.end();
  6707. for ( ; I != E; ++I) {
  6708. if (isLayoutCompatible(C, Field1, *I)) {
  6709. bool Result = UnmatchedFields.erase(*I);
  6710. (void) Result;
  6711. assert(Result);
  6712. break;
  6713. }
  6714. }
  6715. if (I == E)
  6716. return false;
  6717. }
  6718. return UnmatchedFields.empty();
  6719. }
  6720. bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
  6721. if (RD1->isUnion() != RD2->isUnion())
  6722. return false;
  6723. if (RD1->isUnion())
  6724. return isLayoutCompatibleUnion(C, RD1, RD2);
  6725. else
  6726. return isLayoutCompatibleStruct(C, RD1, RD2);
  6727. }
  6728. /// \brief Check if two types are layout-compatible in C++11 sense.
  6729. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  6730. if (T1.isNull() || T2.isNull())
  6731. return false;
  6732. // C++11 [basic.types] p11:
  6733. // If two types T1 and T2 are the same type, then T1 and T2 are
  6734. // layout-compatible types.
  6735. if (C.hasSameType(T1, T2))
  6736. return true;
  6737. T1 = T1.getCanonicalType().getUnqualifiedType();
  6738. T2 = T2.getCanonicalType().getUnqualifiedType();
  6739. const Type::TypeClass TC1 = T1->getTypeClass();
  6740. const Type::TypeClass TC2 = T2->getTypeClass();
  6741. if (TC1 != TC2)
  6742. return false;
  6743. if (TC1 == Type::Enum) {
  6744. return isLayoutCompatible(C,
  6745. cast<EnumType>(T1)->getDecl(),
  6746. cast<EnumType>(T2)->getDecl());
  6747. } else if (TC1 == Type::Record) {
  6748. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  6749. return false;
  6750. return isLayoutCompatible(C,
  6751. cast<RecordType>(T1)->getDecl(),
  6752. cast<RecordType>(T2)->getDecl());
  6753. }
  6754. return false;
  6755. }
  6756. }
  6757. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  6758. namespace {
  6759. /// \brief Given a type tag expression find the type tag itself.
  6760. ///
  6761. /// \param TypeExpr Type tag expression, as it appears in user's code.
  6762. ///
  6763. /// \param VD Declaration of an identifier that appears in a type tag.
  6764. ///
  6765. /// \param MagicValue Type tag magic value.
  6766. bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  6767. const ValueDecl **VD, uint64_t *MagicValue) {
  6768. while(true) {
  6769. if (!TypeExpr)
  6770. return false;
  6771. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  6772. switch (TypeExpr->getStmtClass()) {
  6773. case Stmt::UnaryOperatorClass: {
  6774. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  6775. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  6776. TypeExpr = UO->getSubExpr();
  6777. continue;
  6778. }
  6779. return false;
  6780. }
  6781. case Stmt::DeclRefExprClass: {
  6782. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  6783. *VD = DRE->getDecl();
  6784. return true;
  6785. }
  6786. case Stmt::IntegerLiteralClass: {
  6787. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  6788. llvm::APInt MagicValueAPInt = IL->getValue();
  6789. if (MagicValueAPInt.getActiveBits() <= 64) {
  6790. *MagicValue = MagicValueAPInt.getZExtValue();
  6791. return true;
  6792. } else
  6793. return false;
  6794. }
  6795. case Stmt::BinaryConditionalOperatorClass:
  6796. case Stmt::ConditionalOperatorClass: {
  6797. const AbstractConditionalOperator *ACO =
  6798. cast<AbstractConditionalOperator>(TypeExpr);
  6799. bool Result;
  6800. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  6801. if (Result)
  6802. TypeExpr = ACO->getTrueExpr();
  6803. else
  6804. TypeExpr = ACO->getFalseExpr();
  6805. continue;
  6806. }
  6807. return false;
  6808. }
  6809. case Stmt::BinaryOperatorClass: {
  6810. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  6811. if (BO->getOpcode() == BO_Comma) {
  6812. TypeExpr = BO->getRHS();
  6813. continue;
  6814. }
  6815. return false;
  6816. }
  6817. default:
  6818. return false;
  6819. }
  6820. }
  6821. }
  6822. /// \brief Retrieve the C type corresponding to type tag TypeExpr.
  6823. ///
  6824. /// \param TypeExpr Expression that specifies a type tag.
  6825. ///
  6826. /// \param MagicValues Registered magic values.
  6827. ///
  6828. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  6829. /// kind.
  6830. ///
  6831. /// \param TypeInfo Information about the corresponding C type.
  6832. ///
  6833. /// \returns true if the corresponding C type was found.
  6834. bool GetMatchingCType(
  6835. const IdentifierInfo *ArgumentKind,
  6836. const Expr *TypeExpr, const ASTContext &Ctx,
  6837. const llvm::DenseMap<Sema::TypeTagMagicValue,
  6838. Sema::TypeTagData> *MagicValues,
  6839. bool &FoundWrongKind,
  6840. Sema::TypeTagData &TypeInfo) {
  6841. FoundWrongKind = false;
  6842. // Variable declaration that has type_tag_for_datatype attribute.
  6843. const ValueDecl *VD = nullptr;
  6844. uint64_t MagicValue;
  6845. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  6846. return false;
  6847. if (VD) {
  6848. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  6849. if (I->getArgumentKind() != ArgumentKind) {
  6850. FoundWrongKind = true;
  6851. return false;
  6852. }
  6853. TypeInfo.Type = I->getMatchingCType();
  6854. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  6855. TypeInfo.MustBeNull = I->getMustBeNull();
  6856. return true;
  6857. }
  6858. return false;
  6859. }
  6860. if (!MagicValues)
  6861. return false;
  6862. llvm::DenseMap<Sema::TypeTagMagicValue,
  6863. Sema::TypeTagData>::const_iterator I =
  6864. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  6865. if (I == MagicValues->end())
  6866. return false;
  6867. TypeInfo = I->second;
  6868. return true;
  6869. }
  6870. } // unnamed namespace
  6871. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  6872. uint64_t MagicValue, QualType Type,
  6873. bool LayoutCompatible,
  6874. bool MustBeNull) {
  6875. if (!TypeTagForDatatypeMagicValues)
  6876. TypeTagForDatatypeMagicValues.reset(
  6877. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  6878. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  6879. (*TypeTagForDatatypeMagicValues)[Magic] =
  6880. TypeTagData(Type, LayoutCompatible, MustBeNull);
  6881. }
  6882. namespace {
  6883. bool IsSameCharType(QualType T1, QualType T2) {
  6884. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  6885. if (!BT1)
  6886. return false;
  6887. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  6888. if (!BT2)
  6889. return false;
  6890. BuiltinType::Kind T1Kind = BT1->getKind();
  6891. BuiltinType::Kind T2Kind = BT2->getKind();
  6892. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  6893. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  6894. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  6895. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  6896. }
  6897. } // unnamed namespace
  6898. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  6899. const Expr * const *ExprArgs) {
  6900. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  6901. bool IsPointerAttr = Attr->getIsPointer();
  6902. const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
  6903. bool FoundWrongKind;
  6904. TypeTagData TypeInfo;
  6905. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  6906. TypeTagForDatatypeMagicValues.get(),
  6907. FoundWrongKind, TypeInfo)) {
  6908. if (FoundWrongKind)
  6909. Diag(TypeTagExpr->getExprLoc(),
  6910. diag::warn_type_tag_for_datatype_wrong_kind)
  6911. << TypeTagExpr->getSourceRange();
  6912. return;
  6913. }
  6914. const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
  6915. if (IsPointerAttr) {
  6916. // Skip implicit cast of pointer to `void *' (as a function argument).
  6917. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  6918. if (ICE->getType()->isVoidPointerType() &&
  6919. ICE->getCastKind() == CK_BitCast)
  6920. ArgumentExpr = ICE->getSubExpr();
  6921. }
  6922. QualType ArgumentType = ArgumentExpr->getType();
  6923. // Passing a `void*' pointer shouldn't trigger a warning.
  6924. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  6925. return;
  6926. if (TypeInfo.MustBeNull) {
  6927. // Type tag with matching void type requires a null pointer.
  6928. if (!ArgumentExpr->isNullPointerConstant(Context,
  6929. Expr::NPC_ValueDependentIsNotNull)) {
  6930. Diag(ArgumentExpr->getExprLoc(),
  6931. diag::warn_type_safety_null_pointer_required)
  6932. << ArgumentKind->getName()
  6933. << ArgumentExpr->getSourceRange()
  6934. << TypeTagExpr->getSourceRange();
  6935. }
  6936. return;
  6937. }
  6938. QualType RequiredType = TypeInfo.Type;
  6939. if (IsPointerAttr)
  6940. RequiredType = Context.getPointerType(RequiredType);
  6941. bool mismatch = false;
  6942. if (!TypeInfo.LayoutCompatible) {
  6943. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  6944. // C++11 [basic.fundamental] p1:
  6945. // Plain char, signed char, and unsigned char are three distinct types.
  6946. //
  6947. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  6948. // char' depending on the current char signedness mode.
  6949. if (mismatch)
  6950. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  6951. RequiredType->getPointeeType())) ||
  6952. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  6953. mismatch = false;
  6954. } else
  6955. if (IsPointerAttr)
  6956. mismatch = !isLayoutCompatible(Context,
  6957. ArgumentType->getPointeeType(),
  6958. RequiredType->getPointeeType());
  6959. else
  6960. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  6961. if (mismatch)
  6962. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  6963. << ArgumentType << ArgumentKind
  6964. << TypeInfo.LayoutCompatible << RequiredType
  6965. << ArgumentExpr->getSourceRange()
  6966. << TypeTagExpr->getSourceRange();
  6967. }