SemaChecking.cpp 229 KB

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