SemaChecking.cpp 251 KB

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