SemaChecking.cpp 288 KB

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