SemaChecking.cpp 353 KB

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