SemaChecking.cpp 465 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694
  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/AST/APValue.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/Attr.h"
  17. #include "clang/AST/AttrIterator.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclBase.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/DeclarationName.h"
  24. #include "clang/AST/EvaluatedExprVisitor.h"
  25. #include "clang/AST/Expr.h"
  26. #include "clang/AST/ExprCXX.h"
  27. #include "clang/AST/ExprObjC.h"
  28. #include "clang/AST/ExprOpenMP.h"
  29. #include "clang/AST/NSAPI.h"
  30. #include "clang/AST/NonTrivialTypeVisitor.h"
  31. #include "clang/AST/OperationKinds.h"
  32. #include "clang/AST/Stmt.h"
  33. #include "clang/AST/TemplateBase.h"
  34. #include "clang/AST/Type.h"
  35. #include "clang/AST/TypeLoc.h"
  36. #include "clang/AST/UnresolvedSet.h"
  37. #include "clang/Analysis/Analyses/FormatString.h"
  38. #include "clang/Basic/AddressSpaces.h"
  39. #include "clang/Basic/CharInfo.h"
  40. #include "clang/Basic/Diagnostic.h"
  41. #include "clang/Basic/IdentifierTable.h"
  42. #include "clang/Basic/LLVM.h"
  43. #include "clang/Basic/LangOptions.h"
  44. #include "clang/Basic/OpenCLOptions.h"
  45. #include "clang/Basic/OperatorKinds.h"
  46. #include "clang/Basic/PartialDiagnostic.h"
  47. #include "clang/Basic/SourceLocation.h"
  48. #include "clang/Basic/SourceManager.h"
  49. #include "clang/Basic/Specifiers.h"
  50. #include "clang/Basic/SyncScope.h"
  51. #include "clang/Basic/TargetBuiltins.h"
  52. #include "clang/Basic/TargetCXXABI.h"
  53. #include "clang/Basic/TargetInfo.h"
  54. #include "clang/Basic/TypeTraits.h"
  55. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  56. #include "clang/Sema/Initialization.h"
  57. #include "clang/Sema/Lookup.h"
  58. #include "clang/Sema/Ownership.h"
  59. #include "clang/Sema/Scope.h"
  60. #include "clang/Sema/ScopeInfo.h"
  61. #include "clang/Sema/Sema.h"
  62. #include "clang/Sema/SemaInternal.h"
  63. #include "llvm/ADT/APFloat.h"
  64. #include "llvm/ADT/APInt.h"
  65. #include "llvm/ADT/APSInt.h"
  66. #include "llvm/ADT/ArrayRef.h"
  67. #include "llvm/ADT/DenseMap.h"
  68. #include "llvm/ADT/FoldingSet.h"
  69. #include "llvm/ADT/None.h"
  70. #include "llvm/ADT/Optional.h"
  71. #include "llvm/ADT/STLExtras.h"
  72. #include "llvm/ADT/SmallBitVector.h"
  73. #include "llvm/ADT/SmallPtrSet.h"
  74. #include "llvm/ADT/SmallString.h"
  75. #include "llvm/ADT/SmallVector.h"
  76. #include "llvm/ADT/StringRef.h"
  77. #include "llvm/ADT/StringSwitch.h"
  78. #include "llvm/ADT/Triple.h"
  79. #include "llvm/Support/AtomicOrdering.h"
  80. #include "llvm/Support/Casting.h"
  81. #include "llvm/Support/Compiler.h"
  82. #include "llvm/Support/ConvertUTF.h"
  83. #include "llvm/Support/ErrorHandling.h"
  84. #include "llvm/Support/Format.h"
  85. #include "llvm/Support/Locale.h"
  86. #include "llvm/Support/MathExtras.h"
  87. #include "llvm/Support/raw_ostream.h"
  88. #include <algorithm>
  89. #include <cassert>
  90. #include <cstddef>
  91. #include <cstdint>
  92. #include <functional>
  93. #include <limits>
  94. #include <string>
  95. #include <tuple>
  96. #include <utility>
  97. using namespace clang;
  98. using namespace sema;
  99. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  100. unsigned ByteNo) const {
  101. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  102. Context.getTargetInfo());
  103. }
  104. /// Checks that a call expression's argument count is the desired number.
  105. /// This is useful when doing custom type-checking. Returns true on error.
  106. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  107. unsigned argCount = call->getNumArgs();
  108. if (argCount == desiredArgCount) return false;
  109. if (argCount < desiredArgCount)
  110. return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
  111. << 0 /*function call*/ << desiredArgCount << argCount
  112. << call->getSourceRange();
  113. // Highlight all the excess arguments.
  114. SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
  115. call->getArg(argCount - 1)->getLocEnd());
  116. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  117. << 0 /*function call*/ << desiredArgCount << argCount
  118. << call->getArg(1)->getSourceRange();
  119. }
  120. /// Check that the first argument to __builtin_annotation is an integer
  121. /// and the second argument is a non-wide string literal.
  122. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  123. if (checkArgCount(S, TheCall, 2))
  124. return true;
  125. // First argument should be an integer.
  126. Expr *ValArg = TheCall->getArg(0);
  127. QualType Ty = ValArg->getType();
  128. if (!Ty->isIntegerType()) {
  129. S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
  130. << ValArg->getSourceRange();
  131. return true;
  132. }
  133. // Second argument should be a constant string.
  134. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  135. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  136. if (!Literal || !Literal->isAscii()) {
  137. S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
  138. << StrArg->getSourceRange();
  139. return true;
  140. }
  141. TheCall->setType(Ty);
  142. return false;
  143. }
  144. static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
  145. // We need at least one argument.
  146. if (TheCall->getNumArgs() < 1) {
  147. S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  148. << 0 << 1 << TheCall->getNumArgs()
  149. << TheCall->getCallee()->getSourceRange();
  150. return true;
  151. }
  152. // All arguments should be wide string literals.
  153. for (Expr *Arg : TheCall->arguments()) {
  154. auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  155. if (!Literal || !Literal->isWide()) {
  156. S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
  157. << Arg->getSourceRange();
  158. return true;
  159. }
  160. }
  161. return false;
  162. }
  163. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  164. /// result type to the corresponding pointer type.
  165. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  166. if (checkArgCount(S, TheCall, 1))
  167. return true;
  168. ExprResult Arg(TheCall->getArg(0));
  169. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
  170. if (ResultType.isNull())
  171. return true;
  172. TheCall->setArg(0, Arg.get());
  173. TheCall->setType(ResultType);
  174. return false;
  175. }
  176. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
  177. if (checkArgCount(S, TheCall, 3))
  178. return true;
  179. // First two arguments should be integers.
  180. for (unsigned I = 0; I < 2; ++I) {
  181. Expr *Arg = TheCall->getArg(I);
  182. QualType Ty = Arg->getType();
  183. if (!Ty->isIntegerType()) {
  184. S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
  185. << Ty << Arg->getSourceRange();
  186. return true;
  187. }
  188. }
  189. // Third argument should be a pointer to a non-const integer.
  190. // IRGen correctly handles volatile, restrict, and address spaces, and
  191. // the other qualifiers aren't possible.
  192. {
  193. Expr *Arg = TheCall->getArg(2);
  194. QualType Ty = Arg->getType();
  195. const auto *PtrTy = Ty->getAs<PointerType>();
  196. if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
  197. !PtrTy->getPointeeType().isConstQualified())) {
  198. S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
  199. << Ty << Arg->getSourceRange();
  200. return true;
  201. }
  202. }
  203. return false;
  204. }
  205. static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
  206. CallExpr *TheCall, unsigned SizeIdx,
  207. unsigned DstSizeIdx) {
  208. if (TheCall->getNumArgs() <= SizeIdx ||
  209. TheCall->getNumArgs() <= DstSizeIdx)
  210. return;
  211. const Expr *SizeArg = TheCall->getArg(SizeIdx);
  212. const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
  213. llvm::APSInt Size, DstSize;
  214. // find out if both sizes are known at compile time
  215. if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
  216. !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
  217. return;
  218. if (Size.ule(DstSize))
  219. return;
  220. // confirmed overflow so generate the diagnostic.
  221. IdentifierInfo *FnName = FDecl->getIdentifier();
  222. SourceLocation SL = TheCall->getLocStart();
  223. SourceRange SR = TheCall->getSourceRange();
  224. S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
  225. }
  226. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  227. if (checkArgCount(S, BuiltinCall, 2))
  228. return true;
  229. SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
  230. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  231. Expr *Call = BuiltinCall->getArg(0);
  232. Expr *Chain = BuiltinCall->getArg(1);
  233. if (Call->getStmtClass() != Stmt::CallExprClass) {
  234. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  235. << Call->getSourceRange();
  236. return true;
  237. }
  238. auto CE = cast<CallExpr>(Call);
  239. if (CE->getCallee()->getType()->isBlockPointerType()) {
  240. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  241. << Call->getSourceRange();
  242. return true;
  243. }
  244. const Decl *TargetDecl = CE->getCalleeDecl();
  245. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  246. if (FD->getBuiltinID()) {
  247. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  248. << Call->getSourceRange();
  249. return true;
  250. }
  251. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  252. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  253. << Call->getSourceRange();
  254. return true;
  255. }
  256. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  257. if (ChainResult.isInvalid())
  258. return true;
  259. if (!ChainResult.get()->getType()->isPointerType()) {
  260. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  261. << Chain->getSourceRange();
  262. return true;
  263. }
  264. QualType ReturnTy = CE->getCallReturnType(S.Context);
  265. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  266. QualType BuiltinTy = S.Context.getFunctionType(
  267. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  268. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  269. Builtin =
  270. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  271. BuiltinCall->setType(CE->getType());
  272. BuiltinCall->setValueKind(CE->getValueKind());
  273. BuiltinCall->setObjectKind(CE->getObjectKind());
  274. BuiltinCall->setCallee(Builtin);
  275. BuiltinCall->setArg(1, ChainResult.get());
  276. return false;
  277. }
  278. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  279. Scope::ScopeFlags NeededScopeFlags,
  280. unsigned DiagID) {
  281. // Scopes aren't available during instantiation. Fortunately, builtin
  282. // functions cannot be template args so they cannot be formed through template
  283. // instantiation. Therefore checking once during the parse is sufficient.
  284. if (SemaRef.inTemplateInstantiation())
  285. return false;
  286. Scope *S = SemaRef.getCurScope();
  287. while (S && !S->isSEHExceptScope())
  288. S = S->getParent();
  289. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  290. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  291. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  292. << DRE->getDecl()->getIdentifier();
  293. return true;
  294. }
  295. return false;
  296. }
  297. static inline bool isBlockPointer(Expr *Arg) {
  298. return Arg->getType()->isBlockPointerType();
  299. }
  300. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  301. /// void*, which is a requirement of device side enqueue.
  302. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  303. const BlockPointerType *BPT =
  304. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  305. ArrayRef<QualType> Params =
  306. BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
  307. unsigned ArgCounter = 0;
  308. bool IllegalParams = false;
  309. // Iterate through the block parameters until either one is found that is not
  310. // a local void*, or the block is valid.
  311. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  312. I != E; ++I, ++ArgCounter) {
  313. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  314. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  315. LangAS::opencl_local) {
  316. // Get the location of the error. If a block literal has been passed
  317. // (BlockExpr) then we can point straight to the offending argument,
  318. // else we just point to the variable reference.
  319. SourceLocation ErrorLoc;
  320. if (isa<BlockExpr>(BlockArg)) {
  321. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  322. ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
  323. } else if (isa<DeclRefExpr>(BlockArg)) {
  324. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
  325. }
  326. S.Diag(ErrorLoc,
  327. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  328. IllegalParams = true;
  329. }
  330. }
  331. return IllegalParams;
  332. }
  333. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  334. if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
  335. S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
  336. << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
  337. return true;
  338. }
  339. return false;
  340. }
  341. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  342. if (checkArgCount(S, TheCall, 2))
  343. return true;
  344. if (checkOpenCLSubgroupExt(S, TheCall))
  345. return true;
  346. // First argument is an ndrange_t type.
  347. Expr *NDRangeArg = TheCall->getArg(0);
  348. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  349. S.Diag(NDRangeArg->getLocStart(),
  350. diag::err_opencl_builtin_expected_type)
  351. << TheCall->getDirectCallee() << "'ndrange_t'";
  352. return true;
  353. }
  354. Expr *BlockArg = TheCall->getArg(1);
  355. if (!isBlockPointer(BlockArg)) {
  356. S.Diag(BlockArg->getLocStart(),
  357. diag::err_opencl_builtin_expected_type)
  358. << TheCall->getDirectCallee() << "block";
  359. return true;
  360. }
  361. return checkOpenCLBlockArgs(S, BlockArg);
  362. }
  363. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  364. /// get_kernel_work_group_size
  365. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  366. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  367. if (checkArgCount(S, TheCall, 1))
  368. return true;
  369. Expr *BlockArg = TheCall->getArg(0);
  370. if (!isBlockPointer(BlockArg)) {
  371. S.Diag(BlockArg->getLocStart(),
  372. diag::err_opencl_builtin_expected_type)
  373. << TheCall->getDirectCallee() << "block";
  374. return true;
  375. }
  376. return checkOpenCLBlockArgs(S, BlockArg);
  377. }
  378. /// Diagnose integer type and any valid implicit conversion to it.
  379. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  380. const QualType &IntType);
  381. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  382. unsigned Start, unsigned End) {
  383. bool IllegalParams = false;
  384. for (unsigned I = Start; I <= End; ++I)
  385. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  386. S.Context.getSizeType());
  387. return IllegalParams;
  388. }
  389. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  390. /// 'local void*' parameter of passed block.
  391. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  392. Expr *BlockArg,
  393. unsigned NumNonVarArgs) {
  394. const BlockPointerType *BPT =
  395. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  396. unsigned NumBlockParams =
  397. BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
  398. unsigned TotalNumArgs = TheCall->getNumArgs();
  399. // For each argument passed to the block, a corresponding uint needs to
  400. // be passed to describe the size of the local memory.
  401. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  402. S.Diag(TheCall->getLocStart(),
  403. diag::err_opencl_enqueue_kernel_local_size_args);
  404. return true;
  405. }
  406. // Check that the sizes of the local memory are specified by integers.
  407. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  408. TotalNumArgs - 1);
  409. }
  410. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  411. /// overload formats specified in Table 6.13.17.1.
  412. /// int enqueue_kernel(queue_t queue,
  413. /// kernel_enqueue_flags_t flags,
  414. /// const ndrange_t ndrange,
  415. /// void (^block)(void))
  416. /// int enqueue_kernel(queue_t queue,
  417. /// kernel_enqueue_flags_t flags,
  418. /// const ndrange_t ndrange,
  419. /// uint num_events_in_wait_list,
  420. /// clk_event_t *event_wait_list,
  421. /// clk_event_t *event_ret,
  422. /// void (^block)(void))
  423. /// int enqueue_kernel(queue_t queue,
  424. /// kernel_enqueue_flags_t flags,
  425. /// const ndrange_t ndrange,
  426. /// void (^block)(local void*, ...),
  427. /// uint size0, ...)
  428. /// int enqueue_kernel(queue_t queue,
  429. /// kernel_enqueue_flags_t flags,
  430. /// const ndrange_t ndrange,
  431. /// uint num_events_in_wait_list,
  432. /// clk_event_t *event_wait_list,
  433. /// clk_event_t *event_ret,
  434. /// void (^block)(local void*, ...),
  435. /// uint size0, ...)
  436. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  437. unsigned NumArgs = TheCall->getNumArgs();
  438. if (NumArgs < 4) {
  439. S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
  440. return true;
  441. }
  442. Expr *Arg0 = TheCall->getArg(0);
  443. Expr *Arg1 = TheCall->getArg(1);
  444. Expr *Arg2 = TheCall->getArg(2);
  445. Expr *Arg3 = TheCall->getArg(3);
  446. // First argument always needs to be a queue_t type.
  447. if (!Arg0->getType()->isQueueT()) {
  448. S.Diag(TheCall->getArg(0)->getLocStart(),
  449. diag::err_opencl_builtin_expected_type)
  450. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  451. return true;
  452. }
  453. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  454. if (!Arg1->getType()->isIntegerType()) {
  455. S.Diag(TheCall->getArg(1)->getLocStart(),
  456. diag::err_opencl_builtin_expected_type)
  457. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  458. return true;
  459. }
  460. // Third argument is always an ndrange_t type.
  461. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  462. S.Diag(TheCall->getArg(2)->getLocStart(),
  463. diag::err_opencl_builtin_expected_type)
  464. << TheCall->getDirectCallee() << "'ndrange_t'";
  465. return true;
  466. }
  467. // With four arguments, there is only one form that the function could be
  468. // called in: no events and no variable arguments.
  469. if (NumArgs == 4) {
  470. // check that the last argument is the right block type.
  471. if (!isBlockPointer(Arg3)) {
  472. S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
  473. << TheCall->getDirectCallee() << "block";
  474. return true;
  475. }
  476. // we have a block type, check the prototype
  477. const BlockPointerType *BPT =
  478. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  479. if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
  480. S.Diag(Arg3->getLocStart(),
  481. diag::err_opencl_enqueue_kernel_blocks_no_args);
  482. return true;
  483. }
  484. return false;
  485. }
  486. // we can have block + varargs.
  487. if (isBlockPointer(Arg3))
  488. return (checkOpenCLBlockArgs(S, Arg3) ||
  489. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  490. // last two cases with either exactly 7 args or 7 args and varargs.
  491. if (NumArgs >= 7) {
  492. // check common block argument.
  493. Expr *Arg6 = TheCall->getArg(6);
  494. if (!isBlockPointer(Arg6)) {
  495. S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
  496. << TheCall->getDirectCallee() << "block";
  497. return true;
  498. }
  499. if (checkOpenCLBlockArgs(S, Arg6))
  500. return true;
  501. // Forth argument has to be any integer type.
  502. if (!Arg3->getType()->isIntegerType()) {
  503. S.Diag(TheCall->getArg(3)->getLocStart(),
  504. diag::err_opencl_builtin_expected_type)
  505. << TheCall->getDirectCallee() << "integer";
  506. return true;
  507. }
  508. // check remaining common arguments.
  509. Expr *Arg4 = TheCall->getArg(4);
  510. Expr *Arg5 = TheCall->getArg(5);
  511. // Fifth argument is always passed as a pointer to clk_event_t.
  512. if (!Arg4->isNullPointerConstant(S.Context,
  513. Expr::NPC_ValueDependentIsNotNull) &&
  514. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  515. S.Diag(TheCall->getArg(4)->getLocStart(),
  516. diag::err_opencl_builtin_expected_type)
  517. << TheCall->getDirectCallee()
  518. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  519. return true;
  520. }
  521. // Sixth argument is always passed as a pointer to clk_event_t.
  522. if (!Arg5->isNullPointerConstant(S.Context,
  523. Expr::NPC_ValueDependentIsNotNull) &&
  524. !(Arg5->getType()->isPointerType() &&
  525. Arg5->getType()->getPointeeType()->isClkEventT())) {
  526. S.Diag(TheCall->getArg(5)->getLocStart(),
  527. diag::err_opencl_builtin_expected_type)
  528. << TheCall->getDirectCallee()
  529. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  530. return true;
  531. }
  532. if (NumArgs == 7)
  533. return false;
  534. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  535. }
  536. // None of the specific case has been detected, give generic error
  537. S.Diag(TheCall->getLocStart(),
  538. diag::err_opencl_enqueue_kernel_incorrect_args);
  539. return true;
  540. }
  541. /// Returns OpenCL access qual.
  542. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  543. return D->getAttr<OpenCLAccessAttr>();
  544. }
  545. /// Returns true if pipe element type is different from the pointer.
  546. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  547. const Expr *Arg0 = Call->getArg(0);
  548. // First argument type should always be pipe.
  549. if (!Arg0->getType()->isPipeType()) {
  550. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
  551. << Call->getDirectCallee() << Arg0->getSourceRange();
  552. return true;
  553. }
  554. OpenCLAccessAttr *AccessQual =
  555. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  556. // Validates the access qualifier is compatible with the call.
  557. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  558. // read_only and write_only, and assumed to be read_only if no qualifier is
  559. // specified.
  560. switch (Call->getDirectCallee()->getBuiltinID()) {
  561. case Builtin::BIread_pipe:
  562. case Builtin::BIreserve_read_pipe:
  563. case Builtin::BIcommit_read_pipe:
  564. case Builtin::BIwork_group_reserve_read_pipe:
  565. case Builtin::BIsub_group_reserve_read_pipe:
  566. case Builtin::BIwork_group_commit_read_pipe:
  567. case Builtin::BIsub_group_commit_read_pipe:
  568. if (!(!AccessQual || AccessQual->isReadOnly())) {
  569. S.Diag(Arg0->getLocStart(),
  570. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  571. << "read_only" << Arg0->getSourceRange();
  572. return true;
  573. }
  574. break;
  575. case Builtin::BIwrite_pipe:
  576. case Builtin::BIreserve_write_pipe:
  577. case Builtin::BIcommit_write_pipe:
  578. case Builtin::BIwork_group_reserve_write_pipe:
  579. case Builtin::BIsub_group_reserve_write_pipe:
  580. case Builtin::BIwork_group_commit_write_pipe:
  581. case Builtin::BIsub_group_commit_write_pipe:
  582. if (!(AccessQual && AccessQual->isWriteOnly())) {
  583. S.Diag(Arg0->getLocStart(),
  584. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  585. << "write_only" << Arg0->getSourceRange();
  586. return true;
  587. }
  588. break;
  589. default:
  590. break;
  591. }
  592. return false;
  593. }
  594. /// Returns true if pipe element type is different from the pointer.
  595. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  596. const Expr *Arg0 = Call->getArg(0);
  597. const Expr *ArgIdx = Call->getArg(Idx);
  598. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  599. const QualType EltTy = PipeTy->getElementType();
  600. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  601. // The Idx argument should be a pointer and the type of the pointer and
  602. // the type of pipe element should also be the same.
  603. if (!ArgTy ||
  604. !S.Context.hasSameType(
  605. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  606. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  607. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  608. << ArgIdx->getType() << ArgIdx->getSourceRange();
  609. return true;
  610. }
  611. return false;
  612. }
  613. // \brief Performs semantic analysis for the read/write_pipe call.
  614. // \param S Reference to the semantic analyzer.
  615. // \param Call A pointer to the builtin call.
  616. // \return True if a semantic error has been found, false otherwise.
  617. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  618. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  619. // functions have two forms.
  620. switch (Call->getNumArgs()) {
  621. case 2:
  622. if (checkOpenCLPipeArg(S, Call))
  623. return true;
  624. // The call with 2 arguments should be
  625. // read/write_pipe(pipe T, T*).
  626. // Check packet type T.
  627. if (checkOpenCLPipePacketType(S, Call, 1))
  628. return true;
  629. break;
  630. case 4: {
  631. if (checkOpenCLPipeArg(S, Call))
  632. return true;
  633. // The call with 4 arguments should be
  634. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  635. // Check reserve_id_t.
  636. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  637. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  638. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  639. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  640. return true;
  641. }
  642. // Check the index.
  643. const Expr *Arg2 = Call->getArg(2);
  644. if (!Arg2->getType()->isIntegerType() &&
  645. !Arg2->getType()->isUnsignedIntegerType()) {
  646. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  647. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  648. << Arg2->getType() << Arg2->getSourceRange();
  649. return true;
  650. }
  651. // Check packet type T.
  652. if (checkOpenCLPipePacketType(S, Call, 3))
  653. return true;
  654. } break;
  655. default:
  656. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
  657. << Call->getDirectCallee() << Call->getSourceRange();
  658. return true;
  659. }
  660. return false;
  661. }
  662. // \brief Performs a semantic analysis on the {work_group_/sub_group_
  663. // /_}reserve_{read/write}_pipe
  664. // \param S Reference to the semantic analyzer.
  665. // \param Call The call to the builtin function to be analyzed.
  666. // \return True if a semantic error was found, false otherwise.
  667. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  668. if (checkArgCount(S, Call, 2))
  669. return true;
  670. if (checkOpenCLPipeArg(S, Call))
  671. return true;
  672. // Check the reserve size.
  673. if (!Call->getArg(1)->getType()->isIntegerType() &&
  674. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  675. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  676. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  677. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  678. return true;
  679. }
  680. // Since return type of reserve_read/write_pipe built-in function is
  681. // reserve_id_t, which is not defined in the builtin def file , we used int
  682. // as return type and need to override the return type of these functions.
  683. Call->setType(S.Context.OCLReserveIDTy);
  684. return false;
  685. }
  686. // \brief Performs a semantic analysis on {work_group_/sub_group_
  687. // /_}commit_{read/write}_pipe
  688. // \param S Reference to the semantic analyzer.
  689. // \param Call The call to the builtin function to be analyzed.
  690. // \return True if a semantic error was found, false otherwise.
  691. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  692. if (checkArgCount(S, Call, 2))
  693. return true;
  694. if (checkOpenCLPipeArg(S, Call))
  695. return true;
  696. // Check reserve_id_t.
  697. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  698. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  699. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  700. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  701. return true;
  702. }
  703. return false;
  704. }
  705. // \brief Performs a semantic analysis on the call to built-in Pipe
  706. // Query Functions.
  707. // \param S Reference to the semantic analyzer.
  708. // \param Call The call to the builtin function to be analyzed.
  709. // \return True if a semantic error was found, false otherwise.
  710. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  711. if (checkArgCount(S, Call, 1))
  712. return true;
  713. if (!Call->getArg(0)->getType()->isPipeType()) {
  714. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
  715. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  716. return true;
  717. }
  718. return false;
  719. }
  720. // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  721. // \brief Performs semantic analysis for the to_global/local/private call.
  722. // \param S Reference to the semantic analyzer.
  723. // \param BuiltinID ID of the builtin function.
  724. // \param Call A pointer to the builtin call.
  725. // \return True if a semantic error has been found, false otherwise.
  726. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  727. CallExpr *Call) {
  728. if (Call->getNumArgs() != 1) {
  729. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
  730. << Call->getDirectCallee() << Call->getSourceRange();
  731. return true;
  732. }
  733. auto RT = Call->getArg(0)->getType();
  734. if (!RT->isPointerType() || RT->getPointeeType()
  735. .getAddressSpace() == LangAS::opencl_constant) {
  736. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
  737. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  738. return true;
  739. }
  740. RT = RT->getPointeeType();
  741. auto Qual = RT.getQualifiers();
  742. switch (BuiltinID) {
  743. case Builtin::BIto_global:
  744. Qual.setAddressSpace(LangAS::opencl_global);
  745. break;
  746. case Builtin::BIto_local:
  747. Qual.setAddressSpace(LangAS::opencl_local);
  748. break;
  749. case Builtin::BIto_private:
  750. Qual.setAddressSpace(LangAS::opencl_private);
  751. break;
  752. default:
  753. llvm_unreachable("Invalid builtin function");
  754. }
  755. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  756. RT.getUnqualifiedType(), Qual)));
  757. return false;
  758. }
  759. ExprResult
  760. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  761. CallExpr *TheCall) {
  762. ExprResult TheCallResult(TheCall);
  763. // Find out if any arguments are required to be integer constant expressions.
  764. unsigned ICEArguments = 0;
  765. ASTContext::GetBuiltinTypeError Error;
  766. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  767. if (Error != ASTContext::GE_None)
  768. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  769. // If any arguments are required to be ICE's, check and diagnose.
  770. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  771. // Skip arguments not required to be ICE's.
  772. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  773. llvm::APSInt Result;
  774. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  775. return true;
  776. ICEArguments &= ~(1 << ArgNo);
  777. }
  778. switch (BuiltinID) {
  779. case Builtin::BI__builtin___CFStringMakeConstantString:
  780. assert(TheCall->getNumArgs() == 1 &&
  781. "Wrong # arguments to builtin CFStringMakeConstantString");
  782. if (CheckObjCString(TheCall->getArg(0)))
  783. return ExprError();
  784. break;
  785. case Builtin::BI__builtin_ms_va_start:
  786. case Builtin::BI__builtin_stdarg_start:
  787. case Builtin::BI__builtin_va_start:
  788. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  789. return ExprError();
  790. break;
  791. case Builtin::BI__va_start: {
  792. switch (Context.getTargetInfo().getTriple().getArch()) {
  793. case llvm::Triple::arm:
  794. case llvm::Triple::thumb:
  795. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  796. return ExprError();
  797. break;
  798. default:
  799. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  800. return ExprError();
  801. break;
  802. }
  803. break;
  804. }
  805. case Builtin::BI__builtin_isgreater:
  806. case Builtin::BI__builtin_isgreaterequal:
  807. case Builtin::BI__builtin_isless:
  808. case Builtin::BI__builtin_islessequal:
  809. case Builtin::BI__builtin_islessgreater:
  810. case Builtin::BI__builtin_isunordered:
  811. if (SemaBuiltinUnorderedCompare(TheCall))
  812. return ExprError();
  813. break;
  814. case Builtin::BI__builtin_fpclassify:
  815. if (SemaBuiltinFPClassification(TheCall, 6))
  816. return ExprError();
  817. break;
  818. case Builtin::BI__builtin_isfinite:
  819. case Builtin::BI__builtin_isinf:
  820. case Builtin::BI__builtin_isinf_sign:
  821. case Builtin::BI__builtin_isnan:
  822. case Builtin::BI__builtin_isnormal:
  823. if (SemaBuiltinFPClassification(TheCall, 1))
  824. return ExprError();
  825. break;
  826. case Builtin::BI__builtin_shufflevector:
  827. return SemaBuiltinShuffleVector(TheCall);
  828. // TheCall will be freed by the smart pointer here, but that's fine, since
  829. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  830. case Builtin::BI__builtin_prefetch:
  831. if (SemaBuiltinPrefetch(TheCall))
  832. return ExprError();
  833. break;
  834. case Builtin::BI__builtin_alloca_with_align:
  835. if (SemaBuiltinAllocaWithAlign(TheCall))
  836. return ExprError();
  837. break;
  838. case Builtin::BI__assume:
  839. case Builtin::BI__builtin_assume:
  840. if (SemaBuiltinAssume(TheCall))
  841. return ExprError();
  842. break;
  843. case Builtin::BI__builtin_assume_aligned:
  844. if (SemaBuiltinAssumeAligned(TheCall))
  845. return ExprError();
  846. break;
  847. case Builtin::BI__builtin_object_size:
  848. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  849. return ExprError();
  850. break;
  851. case Builtin::BI__builtin_longjmp:
  852. if (SemaBuiltinLongjmp(TheCall))
  853. return ExprError();
  854. break;
  855. case Builtin::BI__builtin_setjmp:
  856. if (SemaBuiltinSetjmp(TheCall))
  857. return ExprError();
  858. break;
  859. case Builtin::BI_setjmp:
  860. case Builtin::BI_setjmpex:
  861. if (checkArgCount(*this, TheCall, 1))
  862. return true;
  863. break;
  864. case Builtin::BI__builtin_classify_type:
  865. if (checkArgCount(*this, TheCall, 1)) return true;
  866. TheCall->setType(Context.IntTy);
  867. break;
  868. case Builtin::BI__builtin_constant_p:
  869. if (checkArgCount(*this, TheCall, 1)) return true;
  870. TheCall->setType(Context.IntTy);
  871. break;
  872. case Builtin::BI__sync_fetch_and_add:
  873. case Builtin::BI__sync_fetch_and_add_1:
  874. case Builtin::BI__sync_fetch_and_add_2:
  875. case Builtin::BI__sync_fetch_and_add_4:
  876. case Builtin::BI__sync_fetch_and_add_8:
  877. case Builtin::BI__sync_fetch_and_add_16:
  878. case Builtin::BI__sync_fetch_and_sub:
  879. case Builtin::BI__sync_fetch_and_sub_1:
  880. case Builtin::BI__sync_fetch_and_sub_2:
  881. case Builtin::BI__sync_fetch_and_sub_4:
  882. case Builtin::BI__sync_fetch_and_sub_8:
  883. case Builtin::BI__sync_fetch_and_sub_16:
  884. case Builtin::BI__sync_fetch_and_or:
  885. case Builtin::BI__sync_fetch_and_or_1:
  886. case Builtin::BI__sync_fetch_and_or_2:
  887. case Builtin::BI__sync_fetch_and_or_4:
  888. case Builtin::BI__sync_fetch_and_or_8:
  889. case Builtin::BI__sync_fetch_and_or_16:
  890. case Builtin::BI__sync_fetch_and_and:
  891. case Builtin::BI__sync_fetch_and_and_1:
  892. case Builtin::BI__sync_fetch_and_and_2:
  893. case Builtin::BI__sync_fetch_and_and_4:
  894. case Builtin::BI__sync_fetch_and_and_8:
  895. case Builtin::BI__sync_fetch_and_and_16:
  896. case Builtin::BI__sync_fetch_and_xor:
  897. case Builtin::BI__sync_fetch_and_xor_1:
  898. case Builtin::BI__sync_fetch_and_xor_2:
  899. case Builtin::BI__sync_fetch_and_xor_4:
  900. case Builtin::BI__sync_fetch_and_xor_8:
  901. case Builtin::BI__sync_fetch_and_xor_16:
  902. case Builtin::BI__sync_fetch_and_nand:
  903. case Builtin::BI__sync_fetch_and_nand_1:
  904. case Builtin::BI__sync_fetch_and_nand_2:
  905. case Builtin::BI__sync_fetch_and_nand_4:
  906. case Builtin::BI__sync_fetch_and_nand_8:
  907. case Builtin::BI__sync_fetch_and_nand_16:
  908. case Builtin::BI__sync_add_and_fetch:
  909. case Builtin::BI__sync_add_and_fetch_1:
  910. case Builtin::BI__sync_add_and_fetch_2:
  911. case Builtin::BI__sync_add_and_fetch_4:
  912. case Builtin::BI__sync_add_and_fetch_8:
  913. case Builtin::BI__sync_add_and_fetch_16:
  914. case Builtin::BI__sync_sub_and_fetch:
  915. case Builtin::BI__sync_sub_and_fetch_1:
  916. case Builtin::BI__sync_sub_and_fetch_2:
  917. case Builtin::BI__sync_sub_and_fetch_4:
  918. case Builtin::BI__sync_sub_and_fetch_8:
  919. case Builtin::BI__sync_sub_and_fetch_16:
  920. case Builtin::BI__sync_and_and_fetch:
  921. case Builtin::BI__sync_and_and_fetch_1:
  922. case Builtin::BI__sync_and_and_fetch_2:
  923. case Builtin::BI__sync_and_and_fetch_4:
  924. case Builtin::BI__sync_and_and_fetch_8:
  925. case Builtin::BI__sync_and_and_fetch_16:
  926. case Builtin::BI__sync_or_and_fetch:
  927. case Builtin::BI__sync_or_and_fetch_1:
  928. case Builtin::BI__sync_or_and_fetch_2:
  929. case Builtin::BI__sync_or_and_fetch_4:
  930. case Builtin::BI__sync_or_and_fetch_8:
  931. case Builtin::BI__sync_or_and_fetch_16:
  932. case Builtin::BI__sync_xor_and_fetch:
  933. case Builtin::BI__sync_xor_and_fetch_1:
  934. case Builtin::BI__sync_xor_and_fetch_2:
  935. case Builtin::BI__sync_xor_and_fetch_4:
  936. case Builtin::BI__sync_xor_and_fetch_8:
  937. case Builtin::BI__sync_xor_and_fetch_16:
  938. case Builtin::BI__sync_nand_and_fetch:
  939. case Builtin::BI__sync_nand_and_fetch_1:
  940. case Builtin::BI__sync_nand_and_fetch_2:
  941. case Builtin::BI__sync_nand_and_fetch_4:
  942. case Builtin::BI__sync_nand_and_fetch_8:
  943. case Builtin::BI__sync_nand_and_fetch_16:
  944. case Builtin::BI__sync_val_compare_and_swap:
  945. case Builtin::BI__sync_val_compare_and_swap_1:
  946. case Builtin::BI__sync_val_compare_and_swap_2:
  947. case Builtin::BI__sync_val_compare_and_swap_4:
  948. case Builtin::BI__sync_val_compare_and_swap_8:
  949. case Builtin::BI__sync_val_compare_and_swap_16:
  950. case Builtin::BI__sync_bool_compare_and_swap:
  951. case Builtin::BI__sync_bool_compare_and_swap_1:
  952. case Builtin::BI__sync_bool_compare_and_swap_2:
  953. case Builtin::BI__sync_bool_compare_and_swap_4:
  954. case Builtin::BI__sync_bool_compare_and_swap_8:
  955. case Builtin::BI__sync_bool_compare_and_swap_16:
  956. case Builtin::BI__sync_lock_test_and_set:
  957. case Builtin::BI__sync_lock_test_and_set_1:
  958. case Builtin::BI__sync_lock_test_and_set_2:
  959. case Builtin::BI__sync_lock_test_and_set_4:
  960. case Builtin::BI__sync_lock_test_and_set_8:
  961. case Builtin::BI__sync_lock_test_and_set_16:
  962. case Builtin::BI__sync_lock_release:
  963. case Builtin::BI__sync_lock_release_1:
  964. case Builtin::BI__sync_lock_release_2:
  965. case Builtin::BI__sync_lock_release_4:
  966. case Builtin::BI__sync_lock_release_8:
  967. case Builtin::BI__sync_lock_release_16:
  968. case Builtin::BI__sync_swap:
  969. case Builtin::BI__sync_swap_1:
  970. case Builtin::BI__sync_swap_2:
  971. case Builtin::BI__sync_swap_4:
  972. case Builtin::BI__sync_swap_8:
  973. case Builtin::BI__sync_swap_16:
  974. return SemaBuiltinAtomicOverloaded(TheCallResult);
  975. case Builtin::BI__builtin_nontemporal_load:
  976. case Builtin::BI__builtin_nontemporal_store:
  977. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  978. #define BUILTIN(ID, TYPE, ATTRS)
  979. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  980. case Builtin::BI##ID: \
  981. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  982. #include "clang/Basic/Builtins.def"
  983. case Builtin::BI__annotation:
  984. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  985. return ExprError();
  986. break;
  987. case Builtin::BI__builtin_annotation:
  988. if (SemaBuiltinAnnotation(*this, TheCall))
  989. return ExprError();
  990. break;
  991. case Builtin::BI__builtin_addressof:
  992. if (SemaBuiltinAddressof(*this, TheCall))
  993. return ExprError();
  994. break;
  995. case Builtin::BI__builtin_add_overflow:
  996. case Builtin::BI__builtin_sub_overflow:
  997. case Builtin::BI__builtin_mul_overflow:
  998. if (SemaBuiltinOverflow(*this, TheCall))
  999. return ExprError();
  1000. break;
  1001. case Builtin::BI__builtin_operator_new:
  1002. case Builtin::BI__builtin_operator_delete: {
  1003. bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
  1004. ExprResult Res =
  1005. SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
  1006. if (Res.isInvalid())
  1007. CorrectDelayedTyposInExpr(TheCallResult.get());
  1008. return Res;
  1009. }
  1010. case Builtin::BI__builtin_dump_struct: {
  1011. // We first want to ensure we are called with 2 arguments
  1012. if (checkArgCount(*this, TheCall, 2))
  1013. return ExprError();
  1014. // Ensure that the first argument is of type 'struct XX *'
  1015. const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
  1016. const QualType PtrArgType = PtrArg->getType();
  1017. if (!PtrArgType->isPointerType() ||
  1018. !PtrArgType->getPointeeType()->isRecordType()) {
  1019. Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
  1020. << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
  1021. << "structure pointer";
  1022. return ExprError();
  1023. }
  1024. // Ensure that the second argument is of type 'FunctionType'
  1025. const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
  1026. const QualType FnPtrArgType = FnPtrArg->getType();
  1027. if (!FnPtrArgType->isPointerType()) {
  1028. Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
  1029. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1030. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1031. return ExprError();
  1032. }
  1033. const auto *FuncType =
  1034. FnPtrArgType->getPointeeType()->getAs<FunctionType>();
  1035. if (!FuncType) {
  1036. Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
  1037. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1038. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1039. return ExprError();
  1040. }
  1041. if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
  1042. if (!FT->getNumParams()) {
  1043. Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
  1044. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1045. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1046. return ExprError();
  1047. }
  1048. QualType PT = FT->getParamType(0);
  1049. if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
  1050. !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
  1051. !PT->getPointeeType().isConstQualified()) {
  1052. Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
  1053. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1054. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1055. return ExprError();
  1056. }
  1057. }
  1058. TheCall->setType(Context.IntTy);
  1059. break;
  1060. }
  1061. // check secure string manipulation functions where overflows
  1062. // are detectable at compile time
  1063. case Builtin::BI__builtin___memcpy_chk:
  1064. case Builtin::BI__builtin___memmove_chk:
  1065. case Builtin::BI__builtin___memset_chk:
  1066. case Builtin::BI__builtin___strlcat_chk:
  1067. case Builtin::BI__builtin___strlcpy_chk:
  1068. case Builtin::BI__builtin___strncat_chk:
  1069. case Builtin::BI__builtin___strncpy_chk:
  1070. case Builtin::BI__builtin___stpncpy_chk:
  1071. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
  1072. break;
  1073. case Builtin::BI__builtin___memccpy_chk:
  1074. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
  1075. break;
  1076. case Builtin::BI__builtin___snprintf_chk:
  1077. case Builtin::BI__builtin___vsnprintf_chk:
  1078. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
  1079. break;
  1080. case Builtin::BI__builtin_call_with_static_chain:
  1081. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  1082. return ExprError();
  1083. break;
  1084. case Builtin::BI__exception_code:
  1085. case Builtin::BI_exception_code:
  1086. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  1087. diag::err_seh___except_block))
  1088. return ExprError();
  1089. break;
  1090. case Builtin::BI__exception_info:
  1091. case Builtin::BI_exception_info:
  1092. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  1093. diag::err_seh___except_filter))
  1094. return ExprError();
  1095. break;
  1096. case Builtin::BI__GetExceptionInfo:
  1097. if (checkArgCount(*this, TheCall, 1))
  1098. return ExprError();
  1099. if (CheckCXXThrowOperand(
  1100. TheCall->getLocStart(),
  1101. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1102. TheCall))
  1103. return ExprError();
  1104. TheCall->setType(Context.VoidPtrTy);
  1105. break;
  1106. // OpenCL v2.0, s6.13.16 - Pipe functions
  1107. case Builtin::BIread_pipe:
  1108. case Builtin::BIwrite_pipe:
  1109. // Since those two functions are declared with var args, we need a semantic
  1110. // check for the argument.
  1111. if (SemaBuiltinRWPipe(*this, TheCall))
  1112. return ExprError();
  1113. TheCall->setType(Context.IntTy);
  1114. break;
  1115. case Builtin::BIreserve_read_pipe:
  1116. case Builtin::BIreserve_write_pipe:
  1117. case Builtin::BIwork_group_reserve_read_pipe:
  1118. case Builtin::BIwork_group_reserve_write_pipe:
  1119. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1120. return ExprError();
  1121. break;
  1122. case Builtin::BIsub_group_reserve_read_pipe:
  1123. case Builtin::BIsub_group_reserve_write_pipe:
  1124. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1125. SemaBuiltinReserveRWPipe(*this, TheCall))
  1126. return ExprError();
  1127. break;
  1128. case Builtin::BIcommit_read_pipe:
  1129. case Builtin::BIcommit_write_pipe:
  1130. case Builtin::BIwork_group_commit_read_pipe:
  1131. case Builtin::BIwork_group_commit_write_pipe:
  1132. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1133. return ExprError();
  1134. break;
  1135. case Builtin::BIsub_group_commit_read_pipe:
  1136. case Builtin::BIsub_group_commit_write_pipe:
  1137. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1138. SemaBuiltinCommitRWPipe(*this, TheCall))
  1139. return ExprError();
  1140. break;
  1141. case Builtin::BIget_pipe_num_packets:
  1142. case Builtin::BIget_pipe_max_packets:
  1143. if (SemaBuiltinPipePackets(*this, TheCall))
  1144. return ExprError();
  1145. TheCall->setType(Context.UnsignedIntTy);
  1146. break;
  1147. case Builtin::BIto_global:
  1148. case Builtin::BIto_local:
  1149. case Builtin::BIto_private:
  1150. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1151. return ExprError();
  1152. break;
  1153. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1154. case Builtin::BIenqueue_kernel:
  1155. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1156. return ExprError();
  1157. break;
  1158. case Builtin::BIget_kernel_work_group_size:
  1159. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1160. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1161. return ExprError();
  1162. break;
  1163. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1164. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1165. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1166. return ExprError();
  1167. break;
  1168. case Builtin::BI__builtin_os_log_format:
  1169. case Builtin::BI__builtin_os_log_format_buffer_size:
  1170. if (SemaBuiltinOSLogFormat(TheCall))
  1171. return ExprError();
  1172. break;
  1173. }
  1174. // Since the target specific builtins for each arch overlap, only check those
  1175. // of the arch we are compiling for.
  1176. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  1177. switch (Context.getTargetInfo().getTriple().getArch()) {
  1178. case llvm::Triple::arm:
  1179. case llvm::Triple::armeb:
  1180. case llvm::Triple::thumb:
  1181. case llvm::Triple::thumbeb:
  1182. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  1183. return ExprError();
  1184. break;
  1185. case llvm::Triple::aarch64:
  1186. case llvm::Triple::aarch64_be:
  1187. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  1188. return ExprError();
  1189. break;
  1190. case llvm::Triple::mips:
  1191. case llvm::Triple::mipsel:
  1192. case llvm::Triple::mips64:
  1193. case llvm::Triple::mips64el:
  1194. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  1195. return ExprError();
  1196. break;
  1197. case llvm::Triple::systemz:
  1198. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  1199. return ExprError();
  1200. break;
  1201. case llvm::Triple::x86:
  1202. case llvm::Triple::x86_64:
  1203. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  1204. return ExprError();
  1205. break;
  1206. case llvm::Triple::ppc:
  1207. case llvm::Triple::ppc64:
  1208. case llvm::Triple::ppc64le:
  1209. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  1210. return ExprError();
  1211. break;
  1212. default:
  1213. break;
  1214. }
  1215. }
  1216. return TheCallResult;
  1217. }
  1218. // Get the valid immediate range for the specified NEON type code.
  1219. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  1220. NeonTypeFlags Type(t);
  1221. int IsQuad = ForceQuad ? true : Type.isQuad();
  1222. switch (Type.getEltType()) {
  1223. case NeonTypeFlags::Int8:
  1224. case NeonTypeFlags::Poly8:
  1225. return shift ? 7 : (8 << IsQuad) - 1;
  1226. case NeonTypeFlags::Int16:
  1227. case NeonTypeFlags::Poly16:
  1228. return shift ? 15 : (4 << IsQuad) - 1;
  1229. case NeonTypeFlags::Int32:
  1230. return shift ? 31 : (2 << IsQuad) - 1;
  1231. case NeonTypeFlags::Int64:
  1232. case NeonTypeFlags::Poly64:
  1233. return shift ? 63 : (1 << IsQuad) - 1;
  1234. case NeonTypeFlags::Poly128:
  1235. return shift ? 127 : (1 << IsQuad) - 1;
  1236. case NeonTypeFlags::Float16:
  1237. assert(!shift && "cannot shift float types!");
  1238. return (4 << IsQuad) - 1;
  1239. case NeonTypeFlags::Float32:
  1240. assert(!shift && "cannot shift float types!");
  1241. return (2 << IsQuad) - 1;
  1242. case NeonTypeFlags::Float64:
  1243. assert(!shift && "cannot shift float types!");
  1244. return (1 << IsQuad) - 1;
  1245. }
  1246. llvm_unreachable("Invalid NeonTypeFlag!");
  1247. }
  1248. /// getNeonEltType - Return the QualType corresponding to the elements of
  1249. /// the vector type specified by the NeonTypeFlags. This is used to check
  1250. /// the pointer arguments for Neon load/store intrinsics.
  1251. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  1252. bool IsPolyUnsigned, bool IsInt64Long) {
  1253. switch (Flags.getEltType()) {
  1254. case NeonTypeFlags::Int8:
  1255. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  1256. case NeonTypeFlags::Int16:
  1257. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  1258. case NeonTypeFlags::Int32:
  1259. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  1260. case NeonTypeFlags::Int64:
  1261. if (IsInt64Long)
  1262. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  1263. else
  1264. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  1265. : Context.LongLongTy;
  1266. case NeonTypeFlags::Poly8:
  1267. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  1268. case NeonTypeFlags::Poly16:
  1269. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  1270. case NeonTypeFlags::Poly64:
  1271. if (IsInt64Long)
  1272. return Context.UnsignedLongTy;
  1273. else
  1274. return Context.UnsignedLongLongTy;
  1275. case NeonTypeFlags::Poly128:
  1276. break;
  1277. case NeonTypeFlags::Float16:
  1278. return Context.HalfTy;
  1279. case NeonTypeFlags::Float32:
  1280. return Context.FloatTy;
  1281. case NeonTypeFlags::Float64:
  1282. return Context.DoubleTy;
  1283. }
  1284. llvm_unreachable("Invalid NeonTypeFlag!");
  1285. }
  1286. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1287. llvm::APSInt Result;
  1288. uint64_t mask = 0;
  1289. unsigned TV = 0;
  1290. int PtrArgNum = -1;
  1291. bool HasConstPtr = false;
  1292. switch (BuiltinID) {
  1293. #define GET_NEON_OVERLOAD_CHECK
  1294. #include "clang/Basic/arm_neon.inc"
  1295. #include "clang/Basic/arm_fp16.inc"
  1296. #undef GET_NEON_OVERLOAD_CHECK
  1297. }
  1298. // For NEON intrinsics which are overloaded on vector element type, validate
  1299. // the immediate which specifies which variant to emit.
  1300. unsigned ImmArg = TheCall->getNumArgs()-1;
  1301. if (mask) {
  1302. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  1303. return true;
  1304. TV = Result.getLimitedValue(64);
  1305. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  1306. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  1307. << TheCall->getArg(ImmArg)->getSourceRange();
  1308. }
  1309. if (PtrArgNum >= 0) {
  1310. // Check that pointer arguments have the specified type.
  1311. Expr *Arg = TheCall->getArg(PtrArgNum);
  1312. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  1313. Arg = ICE->getSubExpr();
  1314. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  1315. QualType RHSTy = RHS.get()->getType();
  1316. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  1317. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  1318. Arch == llvm::Triple::aarch64_be;
  1319. bool IsInt64Long =
  1320. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  1321. QualType EltTy =
  1322. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  1323. if (HasConstPtr)
  1324. EltTy = EltTy.withConst();
  1325. QualType LHSTy = Context.getPointerType(EltTy);
  1326. AssignConvertType ConvTy;
  1327. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  1328. if (RHS.isInvalid())
  1329. return true;
  1330. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  1331. RHS.get(), AA_Assigning))
  1332. return true;
  1333. }
  1334. // For NEON intrinsics which take an immediate value as part of the
  1335. // instruction, range check them here.
  1336. unsigned i = 0, l = 0, u = 0;
  1337. switch (BuiltinID) {
  1338. default:
  1339. return false;
  1340. #define GET_NEON_IMMEDIATE_CHECK
  1341. #include "clang/Basic/arm_neon.inc"
  1342. #include "clang/Basic/arm_fp16.inc"
  1343. #undef GET_NEON_IMMEDIATE_CHECK
  1344. }
  1345. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1346. }
  1347. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  1348. unsigned MaxWidth) {
  1349. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1350. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1351. BuiltinID == ARM::BI__builtin_arm_strex ||
  1352. BuiltinID == ARM::BI__builtin_arm_stlex ||
  1353. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1354. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1355. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1356. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  1357. "unexpected ARM builtin");
  1358. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1359. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1360. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1361. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  1362. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1363. // Ensure that we have the proper number of arguments.
  1364. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  1365. return true;
  1366. // Inspect the pointer argument of the atomic builtin. This should always be
  1367. // a pointer type, whose element is an integral scalar or pointer type.
  1368. // Because it is a pointer type, we don't have to worry about any implicit
  1369. // casts here.
  1370. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  1371. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  1372. if (PointerArgRes.isInvalid())
  1373. return true;
  1374. PointerArg = PointerArgRes.get();
  1375. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  1376. if (!pointerType) {
  1377. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  1378. << PointerArg->getType() << PointerArg->getSourceRange();
  1379. return true;
  1380. }
  1381. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  1382. // task is to insert the appropriate casts into the AST. First work out just
  1383. // what the appropriate type is.
  1384. QualType ValType = pointerType->getPointeeType();
  1385. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  1386. if (IsLdrex)
  1387. AddrType.addConst();
  1388. // Issue a warning if the cast is dodgy.
  1389. CastKind CastNeeded = CK_NoOp;
  1390. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  1391. CastNeeded = CK_BitCast;
  1392. Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
  1393. << PointerArg->getType()
  1394. << Context.getPointerType(AddrType)
  1395. << AA_Passing << PointerArg->getSourceRange();
  1396. }
  1397. // Finally, do the cast and replace the argument with the corrected version.
  1398. AddrType = Context.getPointerType(AddrType);
  1399. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  1400. if (PointerArgRes.isInvalid())
  1401. return true;
  1402. PointerArg = PointerArgRes.get();
  1403. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  1404. // In general, we allow ints, floats and pointers to be loaded and stored.
  1405. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1406. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  1407. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  1408. << PointerArg->getType() << PointerArg->getSourceRange();
  1409. return true;
  1410. }
  1411. // But ARM doesn't have instructions to deal with 128-bit versions.
  1412. if (Context.getTypeSize(ValType) > MaxWidth) {
  1413. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  1414. Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
  1415. << PointerArg->getType() << PointerArg->getSourceRange();
  1416. return true;
  1417. }
  1418. switch (ValType.getObjCLifetime()) {
  1419. case Qualifiers::OCL_None:
  1420. case Qualifiers::OCL_ExplicitNone:
  1421. // okay
  1422. break;
  1423. case Qualifiers::OCL_Weak:
  1424. case Qualifiers::OCL_Strong:
  1425. case Qualifiers::OCL_Autoreleasing:
  1426. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  1427. << ValType << PointerArg->getSourceRange();
  1428. return true;
  1429. }
  1430. if (IsLdrex) {
  1431. TheCall->setType(ValType);
  1432. return false;
  1433. }
  1434. // Initialize the argument to be stored.
  1435. ExprResult ValArg = TheCall->getArg(0);
  1436. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  1437. Context, ValType, /*consume*/ false);
  1438. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  1439. if (ValArg.isInvalid())
  1440. return true;
  1441. TheCall->setArg(0, ValArg.get());
  1442. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  1443. // but the custom checker bypasses all default analysis.
  1444. TheCall->setType(Context.IntTy);
  1445. return false;
  1446. }
  1447. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1448. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1449. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1450. BuiltinID == ARM::BI__builtin_arm_strex ||
  1451. BuiltinID == ARM::BI__builtin_arm_stlex) {
  1452. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  1453. }
  1454. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  1455. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1456. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  1457. }
  1458. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  1459. BuiltinID == ARM::BI__builtin_arm_wsr64)
  1460. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  1461. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  1462. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  1463. BuiltinID == ARM::BI__builtin_arm_wsr ||
  1464. BuiltinID == ARM::BI__builtin_arm_wsrp)
  1465. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1466. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1467. return true;
  1468. // For intrinsics which take an immediate value as part of the instruction,
  1469. // range check them here.
  1470. // FIXME: VFP Intrinsics should error if VFP not present.
  1471. switch (BuiltinID) {
  1472. default: return false;
  1473. case ARM::BI__builtin_arm_ssat:
  1474. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  1475. case ARM::BI__builtin_arm_usat:
  1476. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  1477. case ARM::BI__builtin_arm_ssat16:
  1478. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  1479. case ARM::BI__builtin_arm_usat16:
  1480. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  1481. case ARM::BI__builtin_arm_vcvtr_f:
  1482. case ARM::BI__builtin_arm_vcvtr_d:
  1483. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  1484. case ARM::BI__builtin_arm_dmb:
  1485. case ARM::BI__builtin_arm_dsb:
  1486. case ARM::BI__builtin_arm_isb:
  1487. case ARM::BI__builtin_arm_dbg:
  1488. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  1489. }
  1490. }
  1491. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  1492. CallExpr *TheCall) {
  1493. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1494. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1495. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1496. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  1497. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  1498. }
  1499. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  1500. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1501. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  1502. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  1503. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  1504. }
  1505. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  1506. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  1507. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1508. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  1509. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  1510. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  1511. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  1512. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1513. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1514. return true;
  1515. // For intrinsics which take an immediate value as part of the instruction,
  1516. // range check them here.
  1517. unsigned i = 0, l = 0, u = 0;
  1518. switch (BuiltinID) {
  1519. default: return false;
  1520. case AArch64::BI__builtin_arm_dmb:
  1521. case AArch64::BI__builtin_arm_dsb:
  1522. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  1523. }
  1524. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1525. }
  1526. // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
  1527. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  1528. // ordering for DSP is unspecified. MSA is ordered by the data format used
  1529. // by the underlying instruction i.e., df/m, df/n and then by size.
  1530. //
  1531. // FIXME: The size tests here should instead be tablegen'd along with the
  1532. // definitions from include/clang/Basic/BuiltinsMips.def.
  1533. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  1534. // be too.
  1535. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1536. unsigned i = 0, l = 0, u = 0, m = 0;
  1537. switch (BuiltinID) {
  1538. default: return false;
  1539. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  1540. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  1541. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  1542. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  1543. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  1544. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  1545. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  1546. // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
  1547. // df/m field.
  1548. // These intrinsics take an unsigned 3 bit immediate.
  1549. case Mips::BI__builtin_msa_bclri_b:
  1550. case Mips::BI__builtin_msa_bnegi_b:
  1551. case Mips::BI__builtin_msa_bseti_b:
  1552. case Mips::BI__builtin_msa_sat_s_b:
  1553. case Mips::BI__builtin_msa_sat_u_b:
  1554. case Mips::BI__builtin_msa_slli_b:
  1555. case Mips::BI__builtin_msa_srai_b:
  1556. case Mips::BI__builtin_msa_srari_b:
  1557. case Mips::BI__builtin_msa_srli_b:
  1558. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  1559. case Mips::BI__builtin_msa_binsli_b:
  1560. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  1561. // These intrinsics take an unsigned 4 bit immediate.
  1562. case Mips::BI__builtin_msa_bclri_h:
  1563. case Mips::BI__builtin_msa_bnegi_h:
  1564. case Mips::BI__builtin_msa_bseti_h:
  1565. case Mips::BI__builtin_msa_sat_s_h:
  1566. case Mips::BI__builtin_msa_sat_u_h:
  1567. case Mips::BI__builtin_msa_slli_h:
  1568. case Mips::BI__builtin_msa_srai_h:
  1569. case Mips::BI__builtin_msa_srari_h:
  1570. case Mips::BI__builtin_msa_srli_h:
  1571. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  1572. case Mips::BI__builtin_msa_binsli_h:
  1573. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  1574. // These intrinsics take an unsigned 5 bit immediate.
  1575. // The first block of intrinsics actually have an unsigned 5 bit field,
  1576. // not a df/n field.
  1577. case Mips::BI__builtin_msa_clei_u_b:
  1578. case Mips::BI__builtin_msa_clei_u_h:
  1579. case Mips::BI__builtin_msa_clei_u_w:
  1580. case Mips::BI__builtin_msa_clei_u_d:
  1581. case Mips::BI__builtin_msa_clti_u_b:
  1582. case Mips::BI__builtin_msa_clti_u_h:
  1583. case Mips::BI__builtin_msa_clti_u_w:
  1584. case Mips::BI__builtin_msa_clti_u_d:
  1585. case Mips::BI__builtin_msa_maxi_u_b:
  1586. case Mips::BI__builtin_msa_maxi_u_h:
  1587. case Mips::BI__builtin_msa_maxi_u_w:
  1588. case Mips::BI__builtin_msa_maxi_u_d:
  1589. case Mips::BI__builtin_msa_mini_u_b:
  1590. case Mips::BI__builtin_msa_mini_u_h:
  1591. case Mips::BI__builtin_msa_mini_u_w:
  1592. case Mips::BI__builtin_msa_mini_u_d:
  1593. case Mips::BI__builtin_msa_addvi_b:
  1594. case Mips::BI__builtin_msa_addvi_h:
  1595. case Mips::BI__builtin_msa_addvi_w:
  1596. case Mips::BI__builtin_msa_addvi_d:
  1597. case Mips::BI__builtin_msa_bclri_w:
  1598. case Mips::BI__builtin_msa_bnegi_w:
  1599. case Mips::BI__builtin_msa_bseti_w:
  1600. case Mips::BI__builtin_msa_sat_s_w:
  1601. case Mips::BI__builtin_msa_sat_u_w:
  1602. case Mips::BI__builtin_msa_slli_w:
  1603. case Mips::BI__builtin_msa_srai_w:
  1604. case Mips::BI__builtin_msa_srari_w:
  1605. case Mips::BI__builtin_msa_srli_w:
  1606. case Mips::BI__builtin_msa_srlri_w:
  1607. case Mips::BI__builtin_msa_subvi_b:
  1608. case Mips::BI__builtin_msa_subvi_h:
  1609. case Mips::BI__builtin_msa_subvi_w:
  1610. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  1611. case Mips::BI__builtin_msa_binsli_w:
  1612. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  1613. // These intrinsics take an unsigned 6 bit immediate.
  1614. case Mips::BI__builtin_msa_bclri_d:
  1615. case Mips::BI__builtin_msa_bnegi_d:
  1616. case Mips::BI__builtin_msa_bseti_d:
  1617. case Mips::BI__builtin_msa_sat_s_d:
  1618. case Mips::BI__builtin_msa_sat_u_d:
  1619. case Mips::BI__builtin_msa_slli_d:
  1620. case Mips::BI__builtin_msa_srai_d:
  1621. case Mips::BI__builtin_msa_srari_d:
  1622. case Mips::BI__builtin_msa_srli_d:
  1623. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  1624. case Mips::BI__builtin_msa_binsli_d:
  1625. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  1626. // These intrinsics take a signed 5 bit immediate.
  1627. case Mips::BI__builtin_msa_ceqi_b:
  1628. case Mips::BI__builtin_msa_ceqi_h:
  1629. case Mips::BI__builtin_msa_ceqi_w:
  1630. case Mips::BI__builtin_msa_ceqi_d:
  1631. case Mips::BI__builtin_msa_clti_s_b:
  1632. case Mips::BI__builtin_msa_clti_s_h:
  1633. case Mips::BI__builtin_msa_clti_s_w:
  1634. case Mips::BI__builtin_msa_clti_s_d:
  1635. case Mips::BI__builtin_msa_clei_s_b:
  1636. case Mips::BI__builtin_msa_clei_s_h:
  1637. case Mips::BI__builtin_msa_clei_s_w:
  1638. case Mips::BI__builtin_msa_clei_s_d:
  1639. case Mips::BI__builtin_msa_maxi_s_b:
  1640. case Mips::BI__builtin_msa_maxi_s_h:
  1641. case Mips::BI__builtin_msa_maxi_s_w:
  1642. case Mips::BI__builtin_msa_maxi_s_d:
  1643. case Mips::BI__builtin_msa_mini_s_b:
  1644. case Mips::BI__builtin_msa_mini_s_h:
  1645. case Mips::BI__builtin_msa_mini_s_w:
  1646. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  1647. // These intrinsics take an unsigned 8 bit immediate.
  1648. case Mips::BI__builtin_msa_andi_b:
  1649. case Mips::BI__builtin_msa_nori_b:
  1650. case Mips::BI__builtin_msa_ori_b:
  1651. case Mips::BI__builtin_msa_shf_b:
  1652. case Mips::BI__builtin_msa_shf_h:
  1653. case Mips::BI__builtin_msa_shf_w:
  1654. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  1655. case Mips::BI__builtin_msa_bseli_b:
  1656. case Mips::BI__builtin_msa_bmnzi_b:
  1657. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  1658. // df/n format
  1659. // These intrinsics take an unsigned 4 bit immediate.
  1660. case Mips::BI__builtin_msa_copy_s_b:
  1661. case Mips::BI__builtin_msa_copy_u_b:
  1662. case Mips::BI__builtin_msa_insve_b:
  1663. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  1664. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  1665. // These intrinsics take an unsigned 3 bit immediate.
  1666. case Mips::BI__builtin_msa_copy_s_h:
  1667. case Mips::BI__builtin_msa_copy_u_h:
  1668. case Mips::BI__builtin_msa_insve_h:
  1669. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  1670. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  1671. // These intrinsics take an unsigned 2 bit immediate.
  1672. case Mips::BI__builtin_msa_copy_s_w:
  1673. case Mips::BI__builtin_msa_copy_u_w:
  1674. case Mips::BI__builtin_msa_insve_w:
  1675. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  1676. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  1677. // These intrinsics take an unsigned 1 bit immediate.
  1678. case Mips::BI__builtin_msa_copy_s_d:
  1679. case Mips::BI__builtin_msa_copy_u_d:
  1680. case Mips::BI__builtin_msa_insve_d:
  1681. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  1682. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  1683. // Memory offsets and immediate loads.
  1684. // These intrinsics take a signed 10 bit immediate.
  1685. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  1686. case Mips::BI__builtin_msa_ldi_h:
  1687. case Mips::BI__builtin_msa_ldi_w:
  1688. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  1689. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
  1690. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
  1691. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
  1692. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
  1693. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
  1694. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
  1695. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
  1696. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
  1697. }
  1698. if (!m)
  1699. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  1700. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  1701. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  1702. }
  1703. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1704. unsigned i = 0, l = 0, u = 0;
  1705. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  1706. BuiltinID == PPC::BI__builtin_divdeu ||
  1707. BuiltinID == PPC::BI__builtin_bpermd;
  1708. bool IsTarget64Bit = Context.getTargetInfo()
  1709. .getTypeWidth(Context
  1710. .getTargetInfo()
  1711. .getIntPtrType()) == 64;
  1712. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  1713. BuiltinID == PPC::BI__builtin_divweu ||
  1714. BuiltinID == PPC::BI__builtin_divde ||
  1715. BuiltinID == PPC::BI__builtin_divdeu;
  1716. if (Is64BitBltin && !IsTarget64Bit)
  1717. return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
  1718. << TheCall->getSourceRange();
  1719. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  1720. (BuiltinID == PPC::BI__builtin_bpermd &&
  1721. !Context.getTargetInfo().hasFeature("bpermd")))
  1722. return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
  1723. << TheCall->getSourceRange();
  1724. switch (BuiltinID) {
  1725. default: return false;
  1726. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  1727. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  1728. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1729. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  1730. case PPC::BI__builtin_tbegin:
  1731. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  1732. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  1733. case PPC::BI__builtin_tabortwc:
  1734. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  1735. case PPC::BI__builtin_tabortwci:
  1736. case PPC::BI__builtin_tabortdci:
  1737. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  1738. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  1739. case PPC::BI__builtin_vsx_xxpermdi:
  1740. case PPC::BI__builtin_vsx_xxsldwi:
  1741. return SemaBuiltinVSX(TheCall);
  1742. }
  1743. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  1744. }
  1745. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  1746. CallExpr *TheCall) {
  1747. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  1748. Expr *Arg = TheCall->getArg(0);
  1749. llvm::APSInt AbortCode(32);
  1750. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  1751. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  1752. return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
  1753. << Arg->getSourceRange();
  1754. }
  1755. // For intrinsics which take an immediate value as part of the instruction,
  1756. // range check them here.
  1757. unsigned i = 0, l = 0, u = 0;
  1758. switch (BuiltinID) {
  1759. default: return false;
  1760. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  1761. case SystemZ::BI__builtin_s390_verimb:
  1762. case SystemZ::BI__builtin_s390_verimh:
  1763. case SystemZ::BI__builtin_s390_verimf:
  1764. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  1765. case SystemZ::BI__builtin_s390_vfaeb:
  1766. case SystemZ::BI__builtin_s390_vfaeh:
  1767. case SystemZ::BI__builtin_s390_vfaef:
  1768. case SystemZ::BI__builtin_s390_vfaebs:
  1769. case SystemZ::BI__builtin_s390_vfaehs:
  1770. case SystemZ::BI__builtin_s390_vfaefs:
  1771. case SystemZ::BI__builtin_s390_vfaezb:
  1772. case SystemZ::BI__builtin_s390_vfaezh:
  1773. case SystemZ::BI__builtin_s390_vfaezf:
  1774. case SystemZ::BI__builtin_s390_vfaezbs:
  1775. case SystemZ::BI__builtin_s390_vfaezhs:
  1776. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  1777. case SystemZ::BI__builtin_s390_vfisb:
  1778. case SystemZ::BI__builtin_s390_vfidb:
  1779. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  1780. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  1781. case SystemZ::BI__builtin_s390_vftcisb:
  1782. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  1783. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  1784. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  1785. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  1786. case SystemZ::BI__builtin_s390_vstrcb:
  1787. case SystemZ::BI__builtin_s390_vstrch:
  1788. case SystemZ::BI__builtin_s390_vstrcf:
  1789. case SystemZ::BI__builtin_s390_vstrczb:
  1790. case SystemZ::BI__builtin_s390_vstrczh:
  1791. case SystemZ::BI__builtin_s390_vstrczf:
  1792. case SystemZ::BI__builtin_s390_vstrcbs:
  1793. case SystemZ::BI__builtin_s390_vstrchs:
  1794. case SystemZ::BI__builtin_s390_vstrcfs:
  1795. case SystemZ::BI__builtin_s390_vstrczbs:
  1796. case SystemZ::BI__builtin_s390_vstrczhs:
  1797. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  1798. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  1799. case SystemZ::BI__builtin_s390_vfminsb:
  1800. case SystemZ::BI__builtin_s390_vfmaxsb:
  1801. case SystemZ::BI__builtin_s390_vfmindb:
  1802. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  1803. }
  1804. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  1805. }
  1806. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  1807. /// This checks that the target supports __builtin_cpu_supports and
  1808. /// that the string argument is constant and valid.
  1809. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  1810. Expr *Arg = TheCall->getArg(0);
  1811. // Check if the argument is a string literal.
  1812. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  1813. return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  1814. << Arg->getSourceRange();
  1815. // Check the contents of the string.
  1816. StringRef Feature =
  1817. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  1818. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  1819. return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
  1820. << Arg->getSourceRange();
  1821. return false;
  1822. }
  1823. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  1824. /// This checks that the target supports __builtin_cpu_is and
  1825. /// that the string argument is constant and valid.
  1826. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  1827. Expr *Arg = TheCall->getArg(0);
  1828. // Check if the argument is a string literal.
  1829. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  1830. return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  1831. << Arg->getSourceRange();
  1832. // Check the contents of the string.
  1833. StringRef Feature =
  1834. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  1835. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  1836. return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
  1837. << Arg->getSourceRange();
  1838. return false;
  1839. }
  1840. // Check if the rounding mode is legal.
  1841. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  1842. // Indicates if this instruction has rounding control or just SAE.
  1843. bool HasRC = false;
  1844. unsigned ArgNum = 0;
  1845. switch (BuiltinID) {
  1846. default:
  1847. return false;
  1848. case X86::BI__builtin_ia32_vcvttsd2si32:
  1849. case X86::BI__builtin_ia32_vcvttsd2si64:
  1850. case X86::BI__builtin_ia32_vcvttsd2usi32:
  1851. case X86::BI__builtin_ia32_vcvttsd2usi64:
  1852. case X86::BI__builtin_ia32_vcvttss2si32:
  1853. case X86::BI__builtin_ia32_vcvttss2si64:
  1854. case X86::BI__builtin_ia32_vcvttss2usi32:
  1855. case X86::BI__builtin_ia32_vcvttss2usi64:
  1856. ArgNum = 1;
  1857. break;
  1858. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  1859. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  1860. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  1861. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  1862. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  1863. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  1864. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  1865. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  1866. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  1867. case X86::BI__builtin_ia32_exp2pd_mask:
  1868. case X86::BI__builtin_ia32_exp2ps_mask:
  1869. case X86::BI__builtin_ia32_getexppd512_mask:
  1870. case X86::BI__builtin_ia32_getexpps512_mask:
  1871. case X86::BI__builtin_ia32_rcp28pd_mask:
  1872. case X86::BI__builtin_ia32_rcp28ps_mask:
  1873. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  1874. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  1875. case X86::BI__builtin_ia32_vcomisd:
  1876. case X86::BI__builtin_ia32_vcomiss:
  1877. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  1878. ArgNum = 3;
  1879. break;
  1880. case X86::BI__builtin_ia32_cmppd512_mask:
  1881. case X86::BI__builtin_ia32_cmpps512_mask:
  1882. case X86::BI__builtin_ia32_cmpsd_mask:
  1883. case X86::BI__builtin_ia32_cmpss_mask:
  1884. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  1885. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  1886. case X86::BI__builtin_ia32_getexpss128_round_mask:
  1887. case X86::BI__builtin_ia32_maxpd512_mask:
  1888. case X86::BI__builtin_ia32_maxps512_mask:
  1889. case X86::BI__builtin_ia32_maxsd_round_mask:
  1890. case X86::BI__builtin_ia32_maxss_round_mask:
  1891. case X86::BI__builtin_ia32_minpd512_mask:
  1892. case X86::BI__builtin_ia32_minps512_mask:
  1893. case X86::BI__builtin_ia32_minsd_round_mask:
  1894. case X86::BI__builtin_ia32_minss_round_mask:
  1895. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  1896. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  1897. case X86::BI__builtin_ia32_reducepd512_mask:
  1898. case X86::BI__builtin_ia32_reduceps512_mask:
  1899. case X86::BI__builtin_ia32_rndscalepd_mask:
  1900. case X86::BI__builtin_ia32_rndscaleps_mask:
  1901. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  1902. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  1903. ArgNum = 4;
  1904. break;
  1905. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  1906. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  1907. case X86::BI__builtin_ia32_fixupimmps512_mask:
  1908. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  1909. case X86::BI__builtin_ia32_fixupimmsd_mask:
  1910. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  1911. case X86::BI__builtin_ia32_fixupimmss_mask:
  1912. case X86::BI__builtin_ia32_fixupimmss_maskz:
  1913. case X86::BI__builtin_ia32_rangepd512_mask:
  1914. case X86::BI__builtin_ia32_rangeps512_mask:
  1915. case X86::BI__builtin_ia32_rangesd128_round_mask:
  1916. case X86::BI__builtin_ia32_rangess128_round_mask:
  1917. case X86::BI__builtin_ia32_reducesd_mask:
  1918. case X86::BI__builtin_ia32_reducess_mask:
  1919. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  1920. case X86::BI__builtin_ia32_rndscaless_round_mask:
  1921. ArgNum = 5;
  1922. break;
  1923. case X86::BI__builtin_ia32_vcvtsd2si64:
  1924. case X86::BI__builtin_ia32_vcvtsd2si32:
  1925. case X86::BI__builtin_ia32_vcvtsd2usi32:
  1926. case X86::BI__builtin_ia32_vcvtsd2usi64:
  1927. case X86::BI__builtin_ia32_vcvtss2si32:
  1928. case X86::BI__builtin_ia32_vcvtss2si64:
  1929. case X86::BI__builtin_ia32_vcvtss2usi32:
  1930. case X86::BI__builtin_ia32_vcvtss2usi64:
  1931. ArgNum = 1;
  1932. HasRC = true;
  1933. break;
  1934. case X86::BI__builtin_ia32_cvtsi2sd64:
  1935. case X86::BI__builtin_ia32_cvtsi2ss32:
  1936. case X86::BI__builtin_ia32_cvtsi2ss64:
  1937. case X86::BI__builtin_ia32_cvtusi2sd64:
  1938. case X86::BI__builtin_ia32_cvtusi2ss32:
  1939. case X86::BI__builtin_ia32_cvtusi2ss64:
  1940. ArgNum = 2;
  1941. HasRC = true;
  1942. break;
  1943. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  1944. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  1945. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  1946. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  1947. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  1948. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  1949. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  1950. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  1951. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  1952. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  1953. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  1954. case X86::BI__builtin_ia32_sqrtpd512_mask:
  1955. case X86::BI__builtin_ia32_sqrtps512_mask:
  1956. ArgNum = 3;
  1957. HasRC = true;
  1958. break;
  1959. case X86::BI__builtin_ia32_addpd512_mask:
  1960. case X86::BI__builtin_ia32_addps512_mask:
  1961. case X86::BI__builtin_ia32_divpd512_mask:
  1962. case X86::BI__builtin_ia32_divps512_mask:
  1963. case X86::BI__builtin_ia32_mulpd512_mask:
  1964. case X86::BI__builtin_ia32_mulps512_mask:
  1965. case X86::BI__builtin_ia32_subpd512_mask:
  1966. case X86::BI__builtin_ia32_subps512_mask:
  1967. case X86::BI__builtin_ia32_addss_round_mask:
  1968. case X86::BI__builtin_ia32_addsd_round_mask:
  1969. case X86::BI__builtin_ia32_divss_round_mask:
  1970. case X86::BI__builtin_ia32_divsd_round_mask:
  1971. case X86::BI__builtin_ia32_mulss_round_mask:
  1972. case X86::BI__builtin_ia32_mulsd_round_mask:
  1973. case X86::BI__builtin_ia32_subss_round_mask:
  1974. case X86::BI__builtin_ia32_subsd_round_mask:
  1975. case X86::BI__builtin_ia32_scalefpd512_mask:
  1976. case X86::BI__builtin_ia32_scalefps512_mask:
  1977. case X86::BI__builtin_ia32_scalefsd_round_mask:
  1978. case X86::BI__builtin_ia32_scalefss_round_mask:
  1979. case X86::BI__builtin_ia32_getmantpd512_mask:
  1980. case X86::BI__builtin_ia32_getmantps512_mask:
  1981. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  1982. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  1983. case X86::BI__builtin_ia32_sqrtss_round_mask:
  1984. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  1985. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  1986. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  1987. case X86::BI__builtin_ia32_vfmaddps512_mask:
  1988. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  1989. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  1990. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  1991. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  1992. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  1993. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  1994. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  1995. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  1996. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  1997. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  1998. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  1999. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  2000. case X86::BI__builtin_ia32_vfnmaddpd512_mask:
  2001. case X86::BI__builtin_ia32_vfnmaddps512_mask:
  2002. case X86::BI__builtin_ia32_vfnmsubpd512_mask:
  2003. case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
  2004. case X86::BI__builtin_ia32_vfnmsubps512_mask:
  2005. case X86::BI__builtin_ia32_vfnmsubps512_mask3:
  2006. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  2007. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  2008. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  2009. case X86::BI__builtin_ia32_vfmaddss3_mask:
  2010. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  2011. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  2012. ArgNum = 4;
  2013. HasRC = true;
  2014. break;
  2015. case X86::BI__builtin_ia32_getmantsd_round_mask:
  2016. case X86::BI__builtin_ia32_getmantss_round_mask:
  2017. ArgNum = 5;
  2018. HasRC = true;
  2019. break;
  2020. }
  2021. llvm::APSInt Result;
  2022. // We can't check the value of a dependent argument.
  2023. Expr *Arg = TheCall->getArg(ArgNum);
  2024. if (Arg->isTypeDependent() || Arg->isValueDependent())
  2025. return false;
  2026. // Check constant-ness first.
  2027. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  2028. return true;
  2029. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  2030. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  2031. // combined with ROUND_NO_EXC.
  2032. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  2033. Result == 8/*ROUND_NO_EXC*/ ||
  2034. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  2035. return false;
  2036. return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
  2037. << Arg->getSourceRange();
  2038. }
  2039. // Check if the gather/scatter scale is legal.
  2040. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  2041. CallExpr *TheCall) {
  2042. unsigned ArgNum = 0;
  2043. switch (BuiltinID) {
  2044. default:
  2045. return false;
  2046. case X86::BI__builtin_ia32_gatherpfdpd:
  2047. case X86::BI__builtin_ia32_gatherpfdps:
  2048. case X86::BI__builtin_ia32_gatherpfqpd:
  2049. case X86::BI__builtin_ia32_gatherpfqps:
  2050. case X86::BI__builtin_ia32_scatterpfdpd:
  2051. case X86::BI__builtin_ia32_scatterpfdps:
  2052. case X86::BI__builtin_ia32_scatterpfqpd:
  2053. case X86::BI__builtin_ia32_scatterpfqps:
  2054. ArgNum = 3;
  2055. break;
  2056. case X86::BI__builtin_ia32_gatherd_pd:
  2057. case X86::BI__builtin_ia32_gatherd_pd256:
  2058. case X86::BI__builtin_ia32_gatherq_pd:
  2059. case X86::BI__builtin_ia32_gatherq_pd256:
  2060. case X86::BI__builtin_ia32_gatherd_ps:
  2061. case X86::BI__builtin_ia32_gatherd_ps256:
  2062. case X86::BI__builtin_ia32_gatherq_ps:
  2063. case X86::BI__builtin_ia32_gatherq_ps256:
  2064. case X86::BI__builtin_ia32_gatherd_q:
  2065. case X86::BI__builtin_ia32_gatherd_q256:
  2066. case X86::BI__builtin_ia32_gatherq_q:
  2067. case X86::BI__builtin_ia32_gatherq_q256:
  2068. case X86::BI__builtin_ia32_gatherd_d:
  2069. case X86::BI__builtin_ia32_gatherd_d256:
  2070. case X86::BI__builtin_ia32_gatherq_d:
  2071. case X86::BI__builtin_ia32_gatherq_d256:
  2072. case X86::BI__builtin_ia32_gather3div2df:
  2073. case X86::BI__builtin_ia32_gather3div2di:
  2074. case X86::BI__builtin_ia32_gather3div4df:
  2075. case X86::BI__builtin_ia32_gather3div4di:
  2076. case X86::BI__builtin_ia32_gather3div4sf:
  2077. case X86::BI__builtin_ia32_gather3div4si:
  2078. case X86::BI__builtin_ia32_gather3div8sf:
  2079. case X86::BI__builtin_ia32_gather3div8si:
  2080. case X86::BI__builtin_ia32_gather3siv2df:
  2081. case X86::BI__builtin_ia32_gather3siv2di:
  2082. case X86::BI__builtin_ia32_gather3siv4df:
  2083. case X86::BI__builtin_ia32_gather3siv4di:
  2084. case X86::BI__builtin_ia32_gather3siv4sf:
  2085. case X86::BI__builtin_ia32_gather3siv4si:
  2086. case X86::BI__builtin_ia32_gather3siv8sf:
  2087. case X86::BI__builtin_ia32_gather3siv8si:
  2088. case X86::BI__builtin_ia32_gathersiv8df:
  2089. case X86::BI__builtin_ia32_gathersiv16sf:
  2090. case X86::BI__builtin_ia32_gatherdiv8df:
  2091. case X86::BI__builtin_ia32_gatherdiv16sf:
  2092. case X86::BI__builtin_ia32_gathersiv8di:
  2093. case X86::BI__builtin_ia32_gathersiv16si:
  2094. case X86::BI__builtin_ia32_gatherdiv8di:
  2095. case X86::BI__builtin_ia32_gatherdiv16si:
  2096. case X86::BI__builtin_ia32_scatterdiv2df:
  2097. case X86::BI__builtin_ia32_scatterdiv2di:
  2098. case X86::BI__builtin_ia32_scatterdiv4df:
  2099. case X86::BI__builtin_ia32_scatterdiv4di:
  2100. case X86::BI__builtin_ia32_scatterdiv4sf:
  2101. case X86::BI__builtin_ia32_scatterdiv4si:
  2102. case X86::BI__builtin_ia32_scatterdiv8sf:
  2103. case X86::BI__builtin_ia32_scatterdiv8si:
  2104. case X86::BI__builtin_ia32_scattersiv2df:
  2105. case X86::BI__builtin_ia32_scattersiv2di:
  2106. case X86::BI__builtin_ia32_scattersiv4df:
  2107. case X86::BI__builtin_ia32_scattersiv4di:
  2108. case X86::BI__builtin_ia32_scattersiv4sf:
  2109. case X86::BI__builtin_ia32_scattersiv4si:
  2110. case X86::BI__builtin_ia32_scattersiv8sf:
  2111. case X86::BI__builtin_ia32_scattersiv8si:
  2112. case X86::BI__builtin_ia32_scattersiv8df:
  2113. case X86::BI__builtin_ia32_scattersiv16sf:
  2114. case X86::BI__builtin_ia32_scatterdiv8df:
  2115. case X86::BI__builtin_ia32_scatterdiv16sf:
  2116. case X86::BI__builtin_ia32_scattersiv8di:
  2117. case X86::BI__builtin_ia32_scattersiv16si:
  2118. case X86::BI__builtin_ia32_scatterdiv8di:
  2119. case X86::BI__builtin_ia32_scatterdiv16si:
  2120. ArgNum = 4;
  2121. break;
  2122. }
  2123. llvm::APSInt Result;
  2124. // We can't check the value of a dependent argument.
  2125. Expr *Arg = TheCall->getArg(ArgNum);
  2126. if (Arg->isTypeDependent() || Arg->isValueDependent())
  2127. return false;
  2128. // Check constant-ness first.
  2129. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  2130. return true;
  2131. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  2132. return false;
  2133. return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
  2134. << Arg->getSourceRange();
  2135. }
  2136. static bool isX86_32Builtin(unsigned BuiltinID) {
  2137. // These builtins only work on x86-32 targets.
  2138. switch (BuiltinID) {
  2139. case X86::BI__builtin_ia32_readeflags_u32:
  2140. case X86::BI__builtin_ia32_writeeflags_u32:
  2141. return true;
  2142. }
  2143. return false;
  2144. }
  2145. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2146. if (BuiltinID == X86::BI__builtin_cpu_supports)
  2147. return SemaBuiltinCpuSupports(*this, TheCall);
  2148. if (BuiltinID == X86::BI__builtin_cpu_is)
  2149. return SemaBuiltinCpuIs(*this, TheCall);
  2150. // Check for 32-bit only builtins on a 64-bit target.
  2151. const llvm::Triple &TT = Context.getTargetInfo().getTriple();
  2152. if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
  2153. return Diag(TheCall->getCallee()->getLocStart(),
  2154. diag::err_32_bit_builtin_64_bit_tgt);
  2155. // If the intrinsic has rounding or SAE make sure its valid.
  2156. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  2157. return true;
  2158. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  2159. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  2160. return true;
  2161. // For intrinsics which take an immediate value as part of the instruction,
  2162. // range check them here.
  2163. int i = 0, l = 0, u = 0;
  2164. switch (BuiltinID) {
  2165. default:
  2166. return false;
  2167. case X86::BI_mm_prefetch:
  2168. i = 1; l = 0; u = 7;
  2169. break;
  2170. case X86::BI__builtin_ia32_sha1rnds4:
  2171. case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
  2172. case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
  2173. case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
  2174. case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
  2175. i = 2; l = 0; u = 3;
  2176. break;
  2177. case X86::BI__builtin_ia32_vpermil2pd:
  2178. case X86::BI__builtin_ia32_vpermil2pd256:
  2179. case X86::BI__builtin_ia32_vpermil2ps:
  2180. case X86::BI__builtin_ia32_vpermil2ps256:
  2181. i = 3; l = 0; u = 3;
  2182. break;
  2183. case X86::BI__builtin_ia32_cmpb128_mask:
  2184. case X86::BI__builtin_ia32_cmpw128_mask:
  2185. case X86::BI__builtin_ia32_cmpd128_mask:
  2186. case X86::BI__builtin_ia32_cmpq128_mask:
  2187. case X86::BI__builtin_ia32_cmpb256_mask:
  2188. case X86::BI__builtin_ia32_cmpw256_mask:
  2189. case X86::BI__builtin_ia32_cmpd256_mask:
  2190. case X86::BI__builtin_ia32_cmpq256_mask:
  2191. case X86::BI__builtin_ia32_cmpb512_mask:
  2192. case X86::BI__builtin_ia32_cmpw512_mask:
  2193. case X86::BI__builtin_ia32_cmpd512_mask:
  2194. case X86::BI__builtin_ia32_cmpq512_mask:
  2195. case X86::BI__builtin_ia32_ucmpb128_mask:
  2196. case X86::BI__builtin_ia32_ucmpw128_mask:
  2197. case X86::BI__builtin_ia32_ucmpd128_mask:
  2198. case X86::BI__builtin_ia32_ucmpq128_mask:
  2199. case X86::BI__builtin_ia32_ucmpb256_mask:
  2200. case X86::BI__builtin_ia32_ucmpw256_mask:
  2201. case X86::BI__builtin_ia32_ucmpd256_mask:
  2202. case X86::BI__builtin_ia32_ucmpq256_mask:
  2203. case X86::BI__builtin_ia32_ucmpb512_mask:
  2204. case X86::BI__builtin_ia32_ucmpw512_mask:
  2205. case X86::BI__builtin_ia32_ucmpd512_mask:
  2206. case X86::BI__builtin_ia32_ucmpq512_mask:
  2207. case X86::BI__builtin_ia32_vpcomub:
  2208. case X86::BI__builtin_ia32_vpcomuw:
  2209. case X86::BI__builtin_ia32_vpcomud:
  2210. case X86::BI__builtin_ia32_vpcomuq:
  2211. case X86::BI__builtin_ia32_vpcomb:
  2212. case X86::BI__builtin_ia32_vpcomw:
  2213. case X86::BI__builtin_ia32_vpcomd:
  2214. case X86::BI__builtin_ia32_vpcomq:
  2215. i = 2; l = 0; u = 7;
  2216. break;
  2217. case X86::BI__builtin_ia32_roundps:
  2218. case X86::BI__builtin_ia32_roundpd:
  2219. case X86::BI__builtin_ia32_roundps256:
  2220. case X86::BI__builtin_ia32_roundpd256:
  2221. i = 1; l = 0; u = 15;
  2222. break;
  2223. case X86::BI__builtin_ia32_roundss:
  2224. case X86::BI__builtin_ia32_roundsd:
  2225. case X86::BI__builtin_ia32_rangepd128_mask:
  2226. case X86::BI__builtin_ia32_rangepd256_mask:
  2227. case X86::BI__builtin_ia32_rangepd512_mask:
  2228. case X86::BI__builtin_ia32_rangeps128_mask:
  2229. case X86::BI__builtin_ia32_rangeps256_mask:
  2230. case X86::BI__builtin_ia32_rangeps512_mask:
  2231. case X86::BI__builtin_ia32_getmantsd_round_mask:
  2232. case X86::BI__builtin_ia32_getmantss_round_mask:
  2233. i = 2; l = 0; u = 15;
  2234. break;
  2235. case X86::BI__builtin_ia32_cmpps:
  2236. case X86::BI__builtin_ia32_cmpss:
  2237. case X86::BI__builtin_ia32_cmppd:
  2238. case X86::BI__builtin_ia32_cmpsd:
  2239. case X86::BI__builtin_ia32_cmpps256:
  2240. case X86::BI__builtin_ia32_cmppd256:
  2241. case X86::BI__builtin_ia32_cmpps128_mask:
  2242. case X86::BI__builtin_ia32_cmppd128_mask:
  2243. case X86::BI__builtin_ia32_cmpps256_mask:
  2244. case X86::BI__builtin_ia32_cmppd256_mask:
  2245. case X86::BI__builtin_ia32_cmpps512_mask:
  2246. case X86::BI__builtin_ia32_cmppd512_mask:
  2247. case X86::BI__builtin_ia32_cmpsd_mask:
  2248. case X86::BI__builtin_ia32_cmpss_mask:
  2249. i = 2; l = 0; u = 31;
  2250. break;
  2251. case X86::BI__builtin_ia32_vcvtps2ph:
  2252. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  2253. case X86::BI__builtin_ia32_vcvtps2ph256:
  2254. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  2255. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  2256. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  2257. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  2258. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  2259. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  2260. case X86::BI__builtin_ia32_rndscaleps_mask:
  2261. case X86::BI__builtin_ia32_rndscalepd_mask:
  2262. case X86::BI__builtin_ia32_reducepd128_mask:
  2263. case X86::BI__builtin_ia32_reducepd256_mask:
  2264. case X86::BI__builtin_ia32_reducepd512_mask:
  2265. case X86::BI__builtin_ia32_reduceps128_mask:
  2266. case X86::BI__builtin_ia32_reduceps256_mask:
  2267. case X86::BI__builtin_ia32_reduceps512_mask:
  2268. case X86::BI__builtin_ia32_prold512_mask:
  2269. case X86::BI__builtin_ia32_prolq512_mask:
  2270. case X86::BI__builtin_ia32_prold128_mask:
  2271. case X86::BI__builtin_ia32_prold256_mask:
  2272. case X86::BI__builtin_ia32_prolq128_mask:
  2273. case X86::BI__builtin_ia32_prolq256_mask:
  2274. case X86::BI__builtin_ia32_prord128_mask:
  2275. case X86::BI__builtin_ia32_prord256_mask:
  2276. case X86::BI__builtin_ia32_prorq128_mask:
  2277. case X86::BI__builtin_ia32_prorq256_mask:
  2278. case X86::BI__builtin_ia32_fpclasspd128_mask:
  2279. case X86::BI__builtin_ia32_fpclasspd256_mask:
  2280. case X86::BI__builtin_ia32_fpclassps128_mask:
  2281. case X86::BI__builtin_ia32_fpclassps256_mask:
  2282. case X86::BI__builtin_ia32_fpclassps512_mask:
  2283. case X86::BI__builtin_ia32_fpclasspd512_mask:
  2284. case X86::BI__builtin_ia32_fpclasssd_mask:
  2285. case X86::BI__builtin_ia32_fpclassss_mask:
  2286. i = 1; l = 0; u = 255;
  2287. break;
  2288. case X86::BI__builtin_ia32_palignr128:
  2289. case X86::BI__builtin_ia32_palignr256:
  2290. case X86::BI__builtin_ia32_palignr512_mask:
  2291. case X86::BI__builtin_ia32_vcomisd:
  2292. case X86::BI__builtin_ia32_vcomiss:
  2293. case X86::BI__builtin_ia32_shuf_f32x4_mask:
  2294. case X86::BI__builtin_ia32_shuf_f64x2_mask:
  2295. case X86::BI__builtin_ia32_shuf_i32x4_mask:
  2296. case X86::BI__builtin_ia32_shuf_i64x2_mask:
  2297. case X86::BI__builtin_ia32_dbpsadbw128_mask:
  2298. case X86::BI__builtin_ia32_dbpsadbw256_mask:
  2299. case X86::BI__builtin_ia32_dbpsadbw512_mask:
  2300. case X86::BI__builtin_ia32_vpshldd128_mask:
  2301. case X86::BI__builtin_ia32_vpshldd256_mask:
  2302. case X86::BI__builtin_ia32_vpshldd512_mask:
  2303. case X86::BI__builtin_ia32_vpshldq128_mask:
  2304. case X86::BI__builtin_ia32_vpshldq256_mask:
  2305. case X86::BI__builtin_ia32_vpshldq512_mask:
  2306. case X86::BI__builtin_ia32_vpshldw128_mask:
  2307. case X86::BI__builtin_ia32_vpshldw256_mask:
  2308. case X86::BI__builtin_ia32_vpshldw512_mask:
  2309. case X86::BI__builtin_ia32_vpshrdd128_mask:
  2310. case X86::BI__builtin_ia32_vpshrdd256_mask:
  2311. case X86::BI__builtin_ia32_vpshrdd512_mask:
  2312. case X86::BI__builtin_ia32_vpshrdq128_mask:
  2313. case X86::BI__builtin_ia32_vpshrdq256_mask:
  2314. case X86::BI__builtin_ia32_vpshrdq512_mask:
  2315. case X86::BI__builtin_ia32_vpshrdw128_mask:
  2316. case X86::BI__builtin_ia32_vpshrdw256_mask:
  2317. case X86::BI__builtin_ia32_vpshrdw512_mask:
  2318. i = 2; l = 0; u = 255;
  2319. break;
  2320. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  2321. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  2322. case X86::BI__builtin_ia32_fixupimmps512_mask:
  2323. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  2324. case X86::BI__builtin_ia32_fixupimmsd_mask:
  2325. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  2326. case X86::BI__builtin_ia32_fixupimmss_mask:
  2327. case X86::BI__builtin_ia32_fixupimmss_maskz:
  2328. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  2329. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  2330. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  2331. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  2332. case X86::BI__builtin_ia32_fixupimmps128_mask:
  2333. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  2334. case X86::BI__builtin_ia32_fixupimmps256_mask:
  2335. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  2336. case X86::BI__builtin_ia32_pternlogd512_mask:
  2337. case X86::BI__builtin_ia32_pternlogd512_maskz:
  2338. case X86::BI__builtin_ia32_pternlogq512_mask:
  2339. case X86::BI__builtin_ia32_pternlogq512_maskz:
  2340. case X86::BI__builtin_ia32_pternlogd128_mask:
  2341. case X86::BI__builtin_ia32_pternlogd128_maskz:
  2342. case X86::BI__builtin_ia32_pternlogd256_mask:
  2343. case X86::BI__builtin_ia32_pternlogd256_maskz:
  2344. case X86::BI__builtin_ia32_pternlogq128_mask:
  2345. case X86::BI__builtin_ia32_pternlogq128_maskz:
  2346. case X86::BI__builtin_ia32_pternlogq256_mask:
  2347. case X86::BI__builtin_ia32_pternlogq256_maskz:
  2348. i = 3; l = 0; u = 255;
  2349. break;
  2350. case X86::BI__builtin_ia32_gatherpfdpd:
  2351. case X86::BI__builtin_ia32_gatherpfdps:
  2352. case X86::BI__builtin_ia32_gatherpfqpd:
  2353. case X86::BI__builtin_ia32_gatherpfqps:
  2354. case X86::BI__builtin_ia32_scatterpfdpd:
  2355. case X86::BI__builtin_ia32_scatterpfdps:
  2356. case X86::BI__builtin_ia32_scatterpfqpd:
  2357. case X86::BI__builtin_ia32_scatterpfqps:
  2358. i = 4; l = 2; u = 3;
  2359. break;
  2360. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  2361. case X86::BI__builtin_ia32_rndscaless_round_mask:
  2362. i = 4; l = 0; u = 255;
  2363. break;
  2364. }
  2365. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2366. }
  2367. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  2368. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  2369. /// Returns true when the format fits the function and the FormatStringInfo has
  2370. /// been populated.
  2371. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  2372. FormatStringInfo *FSI) {
  2373. FSI->HasVAListArg = Format->getFirstArg() == 0;
  2374. FSI->FormatIdx = Format->getFormatIdx() - 1;
  2375. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  2376. // The way the format attribute works in GCC, the implicit this argument
  2377. // of member functions is counted. However, it doesn't appear in our own
  2378. // lists, so decrement format_idx in that case.
  2379. if (IsCXXMember) {
  2380. if(FSI->FormatIdx == 0)
  2381. return false;
  2382. --FSI->FormatIdx;
  2383. if (FSI->FirstDataArg != 0)
  2384. --FSI->FirstDataArg;
  2385. }
  2386. return true;
  2387. }
  2388. /// Checks if a the given expression evaluates to null.
  2389. ///
  2390. /// \brief Returns true if the value evaluates to null.
  2391. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  2392. // If the expression has non-null type, it doesn't evaluate to null.
  2393. if (auto nullability
  2394. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  2395. if (*nullability == NullabilityKind::NonNull)
  2396. return false;
  2397. }
  2398. // As a special case, transparent unions initialized with zero are
  2399. // considered null for the purposes of the nonnull attribute.
  2400. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  2401. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  2402. if (const CompoundLiteralExpr *CLE =
  2403. dyn_cast<CompoundLiteralExpr>(Expr))
  2404. if (const InitListExpr *ILE =
  2405. dyn_cast<InitListExpr>(CLE->getInitializer()))
  2406. Expr = ILE->getInit(0);
  2407. }
  2408. bool Result;
  2409. return (!Expr->isValueDependent() &&
  2410. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  2411. !Result);
  2412. }
  2413. static void CheckNonNullArgument(Sema &S,
  2414. const Expr *ArgExpr,
  2415. SourceLocation CallSiteLoc) {
  2416. if (CheckNonNullExpr(S, ArgExpr))
  2417. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  2418. S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
  2419. }
  2420. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  2421. FormatStringInfo FSI;
  2422. if ((GetFormatStringType(Format) == FST_NSString) &&
  2423. getFormatStringInfo(Format, false, &FSI)) {
  2424. Idx = FSI.FormatIdx;
  2425. return true;
  2426. }
  2427. return false;
  2428. }
  2429. /// \brief Diagnose use of %s directive in an NSString which is being passed
  2430. /// as formatting string to formatting method.
  2431. static void
  2432. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  2433. const NamedDecl *FDecl,
  2434. Expr **Args,
  2435. unsigned NumArgs) {
  2436. unsigned Idx = 0;
  2437. bool Format = false;
  2438. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  2439. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  2440. Idx = 2;
  2441. Format = true;
  2442. }
  2443. else
  2444. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  2445. if (S.GetFormatNSStringIdx(I, Idx)) {
  2446. Format = true;
  2447. break;
  2448. }
  2449. }
  2450. if (!Format || NumArgs <= Idx)
  2451. return;
  2452. const Expr *FormatExpr = Args[Idx];
  2453. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  2454. FormatExpr = CSCE->getSubExpr();
  2455. const StringLiteral *FormatString;
  2456. if (const ObjCStringLiteral *OSL =
  2457. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  2458. FormatString = OSL->getString();
  2459. else
  2460. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  2461. if (!FormatString)
  2462. return;
  2463. if (S.FormatStringHasSArg(FormatString)) {
  2464. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  2465. << "%s" << 1 << 1;
  2466. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  2467. << FDecl->getDeclName();
  2468. }
  2469. }
  2470. /// Determine whether the given type has a non-null nullability annotation.
  2471. static bool isNonNullType(ASTContext &ctx, QualType type) {
  2472. if (auto nullability = type->getNullability(ctx))
  2473. return *nullability == NullabilityKind::NonNull;
  2474. return false;
  2475. }
  2476. static void CheckNonNullArguments(Sema &S,
  2477. const NamedDecl *FDecl,
  2478. const FunctionProtoType *Proto,
  2479. ArrayRef<const Expr *> Args,
  2480. SourceLocation CallSiteLoc) {
  2481. assert((FDecl || Proto) && "Need a function declaration or prototype");
  2482. // Check the attributes attached to the method/function itself.
  2483. llvm::SmallBitVector NonNullArgs;
  2484. if (FDecl) {
  2485. // Handle the nonnull attribute on the function/method declaration itself.
  2486. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  2487. if (!NonNull->args_size()) {
  2488. // Easy case: all pointer arguments are nonnull.
  2489. for (const auto *Arg : Args)
  2490. if (S.isValidPointerAttrType(Arg->getType()))
  2491. CheckNonNullArgument(S, Arg, CallSiteLoc);
  2492. return;
  2493. }
  2494. for (const ParamIdx &Idx : NonNull->args()) {
  2495. unsigned IdxAST = Idx.getASTIndex();
  2496. if (IdxAST >= Args.size())
  2497. continue;
  2498. if (NonNullArgs.empty())
  2499. NonNullArgs.resize(Args.size());
  2500. NonNullArgs.set(IdxAST);
  2501. }
  2502. }
  2503. }
  2504. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  2505. // Handle the nonnull attribute on the parameters of the
  2506. // function/method.
  2507. ArrayRef<ParmVarDecl*> parms;
  2508. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  2509. parms = FD->parameters();
  2510. else
  2511. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  2512. unsigned ParamIndex = 0;
  2513. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  2514. I != E; ++I, ++ParamIndex) {
  2515. const ParmVarDecl *PVD = *I;
  2516. if (PVD->hasAttr<NonNullAttr>() ||
  2517. isNonNullType(S.Context, PVD->getType())) {
  2518. if (NonNullArgs.empty())
  2519. NonNullArgs.resize(Args.size());
  2520. NonNullArgs.set(ParamIndex);
  2521. }
  2522. }
  2523. } else {
  2524. // If we have a non-function, non-method declaration but no
  2525. // function prototype, try to dig out the function prototype.
  2526. if (!Proto) {
  2527. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  2528. QualType type = VD->getType().getNonReferenceType();
  2529. if (auto pointerType = type->getAs<PointerType>())
  2530. type = pointerType->getPointeeType();
  2531. else if (auto blockType = type->getAs<BlockPointerType>())
  2532. type = blockType->getPointeeType();
  2533. // FIXME: data member pointers?
  2534. // Dig out the function prototype, if there is one.
  2535. Proto = type->getAs<FunctionProtoType>();
  2536. }
  2537. }
  2538. // Fill in non-null argument information from the nullability
  2539. // information on the parameter types (if we have them).
  2540. if (Proto) {
  2541. unsigned Index = 0;
  2542. for (auto paramType : Proto->getParamTypes()) {
  2543. if (isNonNullType(S.Context, paramType)) {
  2544. if (NonNullArgs.empty())
  2545. NonNullArgs.resize(Args.size());
  2546. NonNullArgs.set(Index);
  2547. }
  2548. ++Index;
  2549. }
  2550. }
  2551. }
  2552. // Check for non-null arguments.
  2553. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  2554. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  2555. if (NonNullArgs[ArgIndex])
  2556. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  2557. }
  2558. }
  2559. /// Handles the checks for format strings, non-POD arguments to vararg
  2560. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  2561. /// attributes.
  2562. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  2563. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  2564. bool IsMemberFunction, SourceLocation Loc,
  2565. SourceRange Range, VariadicCallType CallType) {
  2566. // FIXME: We should check as much as we can in the template definition.
  2567. if (CurContext->isDependentContext())
  2568. return;
  2569. // Printf and scanf checking.
  2570. llvm::SmallBitVector CheckedVarArgs;
  2571. if (FDecl) {
  2572. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  2573. // Only create vector if there are format attributes.
  2574. CheckedVarArgs.resize(Args.size());
  2575. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  2576. CheckedVarArgs);
  2577. }
  2578. }
  2579. // Refuse POD arguments that weren't caught by the format string
  2580. // checks above.
  2581. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  2582. if (CallType != VariadicDoesNotApply &&
  2583. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  2584. unsigned NumParams = Proto ? Proto->getNumParams()
  2585. : FDecl && isa<FunctionDecl>(FDecl)
  2586. ? cast<FunctionDecl>(FDecl)->getNumParams()
  2587. : FDecl && isa<ObjCMethodDecl>(FDecl)
  2588. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  2589. : 0;
  2590. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  2591. // Args[ArgIdx] can be null in malformed code.
  2592. if (const Expr *Arg = Args[ArgIdx]) {
  2593. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  2594. checkVariadicArgument(Arg, CallType);
  2595. }
  2596. }
  2597. }
  2598. if (FDecl || Proto) {
  2599. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  2600. // Type safety checking.
  2601. if (FDecl) {
  2602. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  2603. CheckArgumentWithTypeTag(I, Args, Loc);
  2604. }
  2605. }
  2606. if (FD)
  2607. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  2608. }
  2609. /// CheckConstructorCall - Check a constructor call for correctness and safety
  2610. /// properties not enforced by the C type system.
  2611. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  2612. ArrayRef<const Expr *> Args,
  2613. const FunctionProtoType *Proto,
  2614. SourceLocation Loc) {
  2615. VariadicCallType CallType =
  2616. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  2617. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  2618. Loc, SourceRange(), CallType);
  2619. }
  2620. /// CheckFunctionCall - Check a direct function call for various correctness
  2621. /// and safety properties not strictly enforced by the C type system.
  2622. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  2623. const FunctionProtoType *Proto) {
  2624. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  2625. isa<CXXMethodDecl>(FDecl);
  2626. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  2627. IsMemberOperatorCall;
  2628. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  2629. TheCall->getCallee());
  2630. Expr** Args = TheCall->getArgs();
  2631. unsigned NumArgs = TheCall->getNumArgs();
  2632. Expr *ImplicitThis = nullptr;
  2633. if (IsMemberOperatorCall) {
  2634. // If this is a call to a member operator, hide the first argument
  2635. // from checkCall.
  2636. // FIXME: Our choice of AST representation here is less than ideal.
  2637. ImplicitThis = Args[0];
  2638. ++Args;
  2639. --NumArgs;
  2640. } else if (IsMemberFunction)
  2641. ImplicitThis =
  2642. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  2643. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  2644. IsMemberFunction, TheCall->getRParenLoc(),
  2645. TheCall->getCallee()->getSourceRange(), CallType);
  2646. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  2647. // None of the checks below are needed for functions that don't have
  2648. // simple names (e.g., C++ conversion functions).
  2649. if (!FnInfo)
  2650. return false;
  2651. CheckAbsoluteValueFunction(TheCall, FDecl);
  2652. CheckMaxUnsignedZero(TheCall, FDecl);
  2653. if (getLangOpts().ObjC1)
  2654. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  2655. unsigned CMId = FDecl->getMemoryFunctionKind();
  2656. if (CMId == 0)
  2657. return false;
  2658. // Handle memory setting and copying functions.
  2659. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  2660. CheckStrlcpycatArguments(TheCall, FnInfo);
  2661. else if (CMId == Builtin::BIstrncat)
  2662. CheckStrncatArguments(TheCall, FnInfo);
  2663. else
  2664. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  2665. return false;
  2666. }
  2667. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  2668. ArrayRef<const Expr *> Args) {
  2669. VariadicCallType CallType =
  2670. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  2671. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  2672. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  2673. CallType);
  2674. return false;
  2675. }
  2676. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  2677. const FunctionProtoType *Proto) {
  2678. QualType Ty;
  2679. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  2680. Ty = V->getType().getNonReferenceType();
  2681. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  2682. Ty = F->getType().getNonReferenceType();
  2683. else
  2684. return false;
  2685. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  2686. !Ty->isFunctionProtoType())
  2687. return false;
  2688. VariadicCallType CallType;
  2689. if (!Proto || !Proto->isVariadic()) {
  2690. CallType = VariadicDoesNotApply;
  2691. } else if (Ty->isBlockPointerType()) {
  2692. CallType = VariadicBlock;
  2693. } else { // Ty->isFunctionPointerType()
  2694. CallType = VariadicFunction;
  2695. }
  2696. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  2697. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  2698. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  2699. TheCall->getCallee()->getSourceRange(), CallType);
  2700. return false;
  2701. }
  2702. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  2703. /// such as function pointers returned from functions.
  2704. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  2705. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  2706. TheCall->getCallee());
  2707. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  2708. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  2709. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  2710. TheCall->getCallee()->getSourceRange(), CallType);
  2711. return false;
  2712. }
  2713. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  2714. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  2715. return false;
  2716. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  2717. switch (Op) {
  2718. case AtomicExpr::AO__c11_atomic_init:
  2719. case AtomicExpr::AO__opencl_atomic_init:
  2720. llvm_unreachable("There is no ordering argument for an init");
  2721. case AtomicExpr::AO__c11_atomic_load:
  2722. case AtomicExpr::AO__opencl_atomic_load:
  2723. case AtomicExpr::AO__atomic_load_n:
  2724. case AtomicExpr::AO__atomic_load:
  2725. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  2726. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  2727. case AtomicExpr::AO__c11_atomic_store:
  2728. case AtomicExpr::AO__opencl_atomic_store:
  2729. case AtomicExpr::AO__atomic_store:
  2730. case AtomicExpr::AO__atomic_store_n:
  2731. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  2732. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  2733. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  2734. default:
  2735. return true;
  2736. }
  2737. }
  2738. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  2739. AtomicExpr::AtomicOp Op) {
  2740. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  2741. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  2742. // All the non-OpenCL operations take one of the following forms.
  2743. // The OpenCL operations take the __c11 forms with one extra argument for
  2744. // synchronization scope.
  2745. enum {
  2746. // C __c11_atomic_init(A *, C)
  2747. Init,
  2748. // C __c11_atomic_load(A *, int)
  2749. Load,
  2750. // void __atomic_load(A *, CP, int)
  2751. LoadCopy,
  2752. // void __atomic_store(A *, CP, int)
  2753. Copy,
  2754. // C __c11_atomic_add(A *, M, int)
  2755. Arithmetic,
  2756. // C __atomic_exchange_n(A *, CP, int)
  2757. Xchg,
  2758. // void __atomic_exchange(A *, C *, CP, int)
  2759. GNUXchg,
  2760. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  2761. C11CmpXchg,
  2762. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  2763. GNUCmpXchg
  2764. } Form = Init;
  2765. const unsigned NumForm = GNUCmpXchg + 1;
  2766. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  2767. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  2768. // where:
  2769. // C is an appropriate type,
  2770. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  2771. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  2772. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  2773. // the int parameters are for orderings.
  2774. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  2775. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  2776. "need to update code for modified forms");
  2777. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  2778. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  2779. AtomicExpr::AO__atomic_load,
  2780. "need to update code for modified C11 atomics");
  2781. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  2782. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  2783. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  2784. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  2785. IsOpenCL;
  2786. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  2787. Op == AtomicExpr::AO__atomic_store_n ||
  2788. Op == AtomicExpr::AO__atomic_exchange_n ||
  2789. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  2790. bool IsAddSub = false;
  2791. switch (Op) {
  2792. case AtomicExpr::AO__c11_atomic_init:
  2793. case AtomicExpr::AO__opencl_atomic_init:
  2794. Form = Init;
  2795. break;
  2796. case AtomicExpr::AO__c11_atomic_load:
  2797. case AtomicExpr::AO__opencl_atomic_load:
  2798. case AtomicExpr::AO__atomic_load_n:
  2799. Form = Load;
  2800. break;
  2801. case AtomicExpr::AO__atomic_load:
  2802. Form = LoadCopy;
  2803. break;
  2804. case AtomicExpr::AO__c11_atomic_store:
  2805. case AtomicExpr::AO__opencl_atomic_store:
  2806. case AtomicExpr::AO__atomic_store:
  2807. case AtomicExpr::AO__atomic_store_n:
  2808. Form = Copy;
  2809. break;
  2810. case AtomicExpr::AO__c11_atomic_fetch_add:
  2811. case AtomicExpr::AO__c11_atomic_fetch_sub:
  2812. case AtomicExpr::AO__opencl_atomic_fetch_add:
  2813. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  2814. case AtomicExpr::AO__opencl_atomic_fetch_min:
  2815. case AtomicExpr::AO__opencl_atomic_fetch_max:
  2816. case AtomicExpr::AO__atomic_fetch_add:
  2817. case AtomicExpr::AO__atomic_fetch_sub:
  2818. case AtomicExpr::AO__atomic_add_fetch:
  2819. case AtomicExpr::AO__atomic_sub_fetch:
  2820. IsAddSub = true;
  2821. LLVM_FALLTHROUGH;
  2822. case AtomicExpr::AO__c11_atomic_fetch_and:
  2823. case AtomicExpr::AO__c11_atomic_fetch_or:
  2824. case AtomicExpr::AO__c11_atomic_fetch_xor:
  2825. case AtomicExpr::AO__opencl_atomic_fetch_and:
  2826. case AtomicExpr::AO__opencl_atomic_fetch_or:
  2827. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  2828. case AtomicExpr::AO__atomic_fetch_and:
  2829. case AtomicExpr::AO__atomic_fetch_or:
  2830. case AtomicExpr::AO__atomic_fetch_xor:
  2831. case AtomicExpr::AO__atomic_fetch_nand:
  2832. case AtomicExpr::AO__atomic_and_fetch:
  2833. case AtomicExpr::AO__atomic_or_fetch:
  2834. case AtomicExpr::AO__atomic_xor_fetch:
  2835. case AtomicExpr::AO__atomic_nand_fetch:
  2836. Form = Arithmetic;
  2837. break;
  2838. case AtomicExpr::AO__c11_atomic_exchange:
  2839. case AtomicExpr::AO__opencl_atomic_exchange:
  2840. case AtomicExpr::AO__atomic_exchange_n:
  2841. Form = Xchg;
  2842. break;
  2843. case AtomicExpr::AO__atomic_exchange:
  2844. Form = GNUXchg;
  2845. break;
  2846. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  2847. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  2848. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  2849. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  2850. Form = C11CmpXchg;
  2851. break;
  2852. case AtomicExpr::AO__atomic_compare_exchange:
  2853. case AtomicExpr::AO__atomic_compare_exchange_n:
  2854. Form = GNUCmpXchg;
  2855. break;
  2856. }
  2857. unsigned AdjustedNumArgs = NumArgs[Form];
  2858. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  2859. ++AdjustedNumArgs;
  2860. // Check we have the right number of arguments.
  2861. if (TheCall->getNumArgs() < AdjustedNumArgs) {
  2862. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  2863. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  2864. << TheCall->getCallee()->getSourceRange();
  2865. return ExprError();
  2866. } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
  2867. Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
  2868. diag::err_typecheck_call_too_many_args)
  2869. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  2870. << TheCall->getCallee()->getSourceRange();
  2871. return ExprError();
  2872. }
  2873. // Inspect the first argument of the atomic operation.
  2874. Expr *Ptr = TheCall->getArg(0);
  2875. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  2876. if (ConvertedPtr.isInvalid())
  2877. return ExprError();
  2878. Ptr = ConvertedPtr.get();
  2879. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  2880. if (!pointerType) {
  2881. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  2882. << Ptr->getType() << Ptr->getSourceRange();
  2883. return ExprError();
  2884. }
  2885. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  2886. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  2887. QualType ValType = AtomTy; // 'C'
  2888. if (IsC11) {
  2889. if (!AtomTy->isAtomicType()) {
  2890. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  2891. << Ptr->getType() << Ptr->getSourceRange();
  2892. return ExprError();
  2893. }
  2894. if (AtomTy.isConstQualified() ||
  2895. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  2896. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
  2897. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  2898. << Ptr->getSourceRange();
  2899. return ExprError();
  2900. }
  2901. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  2902. } else if (Form != Load && Form != LoadCopy) {
  2903. if (ValType.isConstQualified()) {
  2904. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
  2905. << Ptr->getType() << Ptr->getSourceRange();
  2906. return ExprError();
  2907. }
  2908. }
  2909. // For an arithmetic operation, the implied arithmetic must be well-formed.
  2910. if (Form == Arithmetic) {
  2911. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  2912. if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
  2913. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  2914. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  2915. return ExprError();
  2916. }
  2917. if (!IsAddSub && !ValType->isIntegerType()) {
  2918. Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
  2919. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  2920. return ExprError();
  2921. }
  2922. if (IsC11 && ValType->isPointerType() &&
  2923. RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
  2924. diag::err_incomplete_type)) {
  2925. return ExprError();
  2926. }
  2927. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  2928. // For __atomic_*_n operations, the value type must be a scalar integral or
  2929. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  2930. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  2931. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  2932. return ExprError();
  2933. }
  2934. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  2935. !AtomTy->isScalarType()) {
  2936. // For GNU atomics, require a trivially-copyable type. This is not part of
  2937. // the GNU atomics specification, but we enforce it for sanity.
  2938. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
  2939. << Ptr->getType() << Ptr->getSourceRange();
  2940. return ExprError();
  2941. }
  2942. switch (ValType.getObjCLifetime()) {
  2943. case Qualifiers::OCL_None:
  2944. case Qualifiers::OCL_ExplicitNone:
  2945. // okay
  2946. break;
  2947. case Qualifiers::OCL_Weak:
  2948. case Qualifiers::OCL_Strong:
  2949. case Qualifiers::OCL_Autoreleasing:
  2950. // FIXME: Can this happen? By this point, ValType should be known
  2951. // to be trivially copyable.
  2952. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  2953. << ValType << Ptr->getSourceRange();
  2954. return ExprError();
  2955. }
  2956. // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
  2957. // volatile-ness of the pointee-type inject itself into the result or the
  2958. // other operands. Similarly atomic_load can take a pointer to a const 'A'.
  2959. ValType.removeLocalVolatile();
  2960. ValType.removeLocalConst();
  2961. QualType ResultType = ValType;
  2962. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  2963. Form == Init)
  2964. ResultType = Context.VoidTy;
  2965. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  2966. ResultType = Context.BoolTy;
  2967. // The type of a parameter passed 'by value'. In the GNU atomics, such
  2968. // arguments are actually passed as pointers.
  2969. QualType ByValType = ValType; // 'CP'
  2970. if (!IsC11 && !IsN)
  2971. ByValType = Ptr->getType();
  2972. // The first argument --- the pointer --- has a fixed type; we
  2973. // deduce the types of the rest of the arguments accordingly. Walk
  2974. // the remaining arguments, converting them to the deduced value type.
  2975. for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
  2976. QualType Ty;
  2977. if (i < NumVals[Form] + 1) {
  2978. switch (i) {
  2979. case 1:
  2980. // The second argument is the non-atomic operand. For arithmetic, this
  2981. // is always passed by value, and for a compare_exchange it is always
  2982. // passed by address. For the rest, GNU uses by-address and C11 uses
  2983. // by-value.
  2984. assert(Form != Load);
  2985. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  2986. Ty = ValType;
  2987. else if (Form == Copy || Form == Xchg)
  2988. Ty = ByValType;
  2989. else if (Form == Arithmetic)
  2990. Ty = Context.getPointerDiffType();
  2991. else {
  2992. Expr *ValArg = TheCall->getArg(i);
  2993. // Treat this argument as _Nonnull as we want to show a warning if
  2994. // NULL is passed into it.
  2995. CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
  2996. LangAS AS = LangAS::Default;
  2997. // Keep address space of non-atomic pointer type.
  2998. if (const PointerType *PtrTy =
  2999. ValArg->getType()->getAs<PointerType>()) {
  3000. AS = PtrTy->getPointeeType().getAddressSpace();
  3001. }
  3002. Ty = Context.getPointerType(
  3003. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  3004. }
  3005. break;
  3006. case 2:
  3007. // The third argument to compare_exchange / GNU exchange is a
  3008. // (pointer to a) desired value.
  3009. Ty = ByValType;
  3010. break;
  3011. case 3:
  3012. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  3013. Ty = Context.BoolTy;
  3014. break;
  3015. }
  3016. } else {
  3017. // The order(s) and scope are always converted to int.
  3018. Ty = Context.IntTy;
  3019. }
  3020. InitializedEntity Entity =
  3021. InitializedEntity::InitializeParameter(Context, Ty, false);
  3022. ExprResult Arg = TheCall->getArg(i);
  3023. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  3024. if (Arg.isInvalid())
  3025. return true;
  3026. TheCall->setArg(i, Arg.get());
  3027. }
  3028. // Permute the arguments into a 'consistent' order.
  3029. SmallVector<Expr*, 5> SubExprs;
  3030. SubExprs.push_back(Ptr);
  3031. switch (Form) {
  3032. case Init:
  3033. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  3034. SubExprs.push_back(TheCall->getArg(1)); // Val1
  3035. break;
  3036. case Load:
  3037. SubExprs.push_back(TheCall->getArg(1)); // Order
  3038. break;
  3039. case LoadCopy:
  3040. case Copy:
  3041. case Arithmetic:
  3042. case Xchg:
  3043. SubExprs.push_back(TheCall->getArg(2)); // Order
  3044. SubExprs.push_back(TheCall->getArg(1)); // Val1
  3045. break;
  3046. case GNUXchg:
  3047. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  3048. SubExprs.push_back(TheCall->getArg(3)); // Order
  3049. SubExprs.push_back(TheCall->getArg(1)); // Val1
  3050. SubExprs.push_back(TheCall->getArg(2)); // Val2
  3051. break;
  3052. case C11CmpXchg:
  3053. SubExprs.push_back(TheCall->getArg(3)); // Order
  3054. SubExprs.push_back(TheCall->getArg(1)); // Val1
  3055. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  3056. SubExprs.push_back(TheCall->getArg(2)); // Val2
  3057. break;
  3058. case GNUCmpXchg:
  3059. SubExprs.push_back(TheCall->getArg(4)); // Order
  3060. SubExprs.push_back(TheCall->getArg(1)); // Val1
  3061. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  3062. SubExprs.push_back(TheCall->getArg(2)); // Val2
  3063. SubExprs.push_back(TheCall->getArg(3)); // Weak
  3064. break;
  3065. }
  3066. if (SubExprs.size() >= 2 && Form != Init) {
  3067. llvm::APSInt Result(32);
  3068. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  3069. !isValidOrderingForOp(Result.getSExtValue(), Op))
  3070. Diag(SubExprs[1]->getLocStart(),
  3071. diag::warn_atomic_op_has_invalid_memory_order)
  3072. << SubExprs[1]->getSourceRange();
  3073. }
  3074. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  3075. auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
  3076. llvm::APSInt Result(32);
  3077. if (Scope->isIntegerConstantExpr(Result, Context) &&
  3078. !ScopeModel->isValid(Result.getZExtValue())) {
  3079. Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
  3080. << Scope->getSourceRange();
  3081. }
  3082. SubExprs.push_back(Scope);
  3083. }
  3084. AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  3085. SubExprs, ResultType, Op,
  3086. TheCall->getRParenLoc());
  3087. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  3088. Op == AtomicExpr::AO__c11_atomic_store ||
  3089. Op == AtomicExpr::AO__opencl_atomic_load ||
  3090. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  3091. Context.AtomicUsesUnsupportedLibcall(AE))
  3092. Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
  3093. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  3094. Op == AtomicExpr::AO__opencl_atomic_load)
  3095. ? 0 : 1);
  3096. return AE;
  3097. }
  3098. /// checkBuiltinArgument - Given a call to a builtin function, perform
  3099. /// normal type-checking on the given argument, updating the call in
  3100. /// place. This is useful when a builtin function requires custom
  3101. /// type-checking for some of its arguments but not necessarily all of
  3102. /// them.
  3103. ///
  3104. /// Returns true on error.
  3105. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  3106. FunctionDecl *Fn = E->getDirectCallee();
  3107. assert(Fn && "builtin call without direct callee!");
  3108. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  3109. InitializedEntity Entity =
  3110. InitializedEntity::InitializeParameter(S.Context, Param);
  3111. ExprResult Arg = E->getArg(0);
  3112. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  3113. if (Arg.isInvalid())
  3114. return true;
  3115. E->setArg(ArgIndex, Arg.get());
  3116. return false;
  3117. }
  3118. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  3119. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  3120. /// type of its first argument. The main ActOnCallExpr routines have already
  3121. /// promoted the types of arguments because all of these calls are prototyped as
  3122. /// void(...).
  3123. ///
  3124. /// This function goes through and does final semantic checking for these
  3125. /// builtins,
  3126. ExprResult
  3127. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  3128. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  3129. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  3130. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  3131. // Ensure that we have at least one argument to do type inference from.
  3132. if (TheCall->getNumArgs() < 1) {
  3133. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  3134. << 0 << 1 << TheCall->getNumArgs()
  3135. << TheCall->getCallee()->getSourceRange();
  3136. return ExprError();
  3137. }
  3138. // Inspect the first argument of the atomic builtin. This should always be
  3139. // a pointer type, whose element is an integral scalar or pointer type.
  3140. // Because it is a pointer type, we don't have to worry about any implicit
  3141. // casts here.
  3142. // FIXME: We don't allow floating point scalars as input.
  3143. Expr *FirstArg = TheCall->getArg(0);
  3144. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  3145. if (FirstArgResult.isInvalid())
  3146. return ExprError();
  3147. FirstArg = FirstArgResult.get();
  3148. TheCall->setArg(0, FirstArg);
  3149. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  3150. if (!pointerType) {
  3151. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  3152. << FirstArg->getType() << FirstArg->getSourceRange();
  3153. return ExprError();
  3154. }
  3155. QualType ValType = pointerType->getPointeeType();
  3156. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  3157. !ValType->isBlockPointerType()) {
  3158. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  3159. << FirstArg->getType() << FirstArg->getSourceRange();
  3160. return ExprError();
  3161. }
  3162. switch (ValType.getObjCLifetime()) {
  3163. case Qualifiers::OCL_None:
  3164. case Qualifiers::OCL_ExplicitNone:
  3165. // okay
  3166. break;
  3167. case Qualifiers::OCL_Weak:
  3168. case Qualifiers::OCL_Strong:
  3169. case Qualifiers::OCL_Autoreleasing:
  3170. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  3171. << ValType << FirstArg->getSourceRange();
  3172. return ExprError();
  3173. }
  3174. // Strip any qualifiers off ValType.
  3175. ValType = ValType.getUnqualifiedType();
  3176. // The majority of builtins return a value, but a few have special return
  3177. // types, so allow them to override appropriately below.
  3178. QualType ResultType = ValType;
  3179. // We need to figure out which concrete builtin this maps onto. For example,
  3180. // __sync_fetch_and_add with a 2 byte object turns into
  3181. // __sync_fetch_and_add_2.
  3182. #define BUILTIN_ROW(x) \
  3183. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  3184. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  3185. static const unsigned BuiltinIndices[][5] = {
  3186. BUILTIN_ROW(__sync_fetch_and_add),
  3187. BUILTIN_ROW(__sync_fetch_and_sub),
  3188. BUILTIN_ROW(__sync_fetch_and_or),
  3189. BUILTIN_ROW(__sync_fetch_and_and),
  3190. BUILTIN_ROW(__sync_fetch_and_xor),
  3191. BUILTIN_ROW(__sync_fetch_and_nand),
  3192. BUILTIN_ROW(__sync_add_and_fetch),
  3193. BUILTIN_ROW(__sync_sub_and_fetch),
  3194. BUILTIN_ROW(__sync_and_and_fetch),
  3195. BUILTIN_ROW(__sync_or_and_fetch),
  3196. BUILTIN_ROW(__sync_xor_and_fetch),
  3197. BUILTIN_ROW(__sync_nand_and_fetch),
  3198. BUILTIN_ROW(__sync_val_compare_and_swap),
  3199. BUILTIN_ROW(__sync_bool_compare_and_swap),
  3200. BUILTIN_ROW(__sync_lock_test_and_set),
  3201. BUILTIN_ROW(__sync_lock_release),
  3202. BUILTIN_ROW(__sync_swap)
  3203. };
  3204. #undef BUILTIN_ROW
  3205. // Determine the index of the size.
  3206. unsigned SizeIndex;
  3207. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  3208. case 1: SizeIndex = 0; break;
  3209. case 2: SizeIndex = 1; break;
  3210. case 4: SizeIndex = 2; break;
  3211. case 8: SizeIndex = 3; break;
  3212. case 16: SizeIndex = 4; break;
  3213. default:
  3214. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  3215. << FirstArg->getType() << FirstArg->getSourceRange();
  3216. return ExprError();
  3217. }
  3218. // Each of these builtins has one pointer argument, followed by some number of
  3219. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  3220. // that we ignore. Find out which row of BuiltinIndices to read from as well
  3221. // as the number of fixed args.
  3222. unsigned BuiltinID = FDecl->getBuiltinID();
  3223. unsigned BuiltinIndex, NumFixed = 1;
  3224. bool WarnAboutSemanticsChange = false;
  3225. switch (BuiltinID) {
  3226. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  3227. case Builtin::BI__sync_fetch_and_add:
  3228. case Builtin::BI__sync_fetch_and_add_1:
  3229. case Builtin::BI__sync_fetch_and_add_2:
  3230. case Builtin::BI__sync_fetch_and_add_4:
  3231. case Builtin::BI__sync_fetch_and_add_8:
  3232. case Builtin::BI__sync_fetch_and_add_16:
  3233. BuiltinIndex = 0;
  3234. break;
  3235. case Builtin::BI__sync_fetch_and_sub:
  3236. case Builtin::BI__sync_fetch_and_sub_1:
  3237. case Builtin::BI__sync_fetch_and_sub_2:
  3238. case Builtin::BI__sync_fetch_and_sub_4:
  3239. case Builtin::BI__sync_fetch_and_sub_8:
  3240. case Builtin::BI__sync_fetch_and_sub_16:
  3241. BuiltinIndex = 1;
  3242. break;
  3243. case Builtin::BI__sync_fetch_and_or:
  3244. case Builtin::BI__sync_fetch_and_or_1:
  3245. case Builtin::BI__sync_fetch_and_or_2:
  3246. case Builtin::BI__sync_fetch_and_or_4:
  3247. case Builtin::BI__sync_fetch_and_or_8:
  3248. case Builtin::BI__sync_fetch_and_or_16:
  3249. BuiltinIndex = 2;
  3250. break;
  3251. case Builtin::BI__sync_fetch_and_and:
  3252. case Builtin::BI__sync_fetch_and_and_1:
  3253. case Builtin::BI__sync_fetch_and_and_2:
  3254. case Builtin::BI__sync_fetch_and_and_4:
  3255. case Builtin::BI__sync_fetch_and_and_8:
  3256. case Builtin::BI__sync_fetch_and_and_16:
  3257. BuiltinIndex = 3;
  3258. break;
  3259. case Builtin::BI__sync_fetch_and_xor:
  3260. case Builtin::BI__sync_fetch_and_xor_1:
  3261. case Builtin::BI__sync_fetch_and_xor_2:
  3262. case Builtin::BI__sync_fetch_and_xor_4:
  3263. case Builtin::BI__sync_fetch_and_xor_8:
  3264. case Builtin::BI__sync_fetch_and_xor_16:
  3265. BuiltinIndex = 4;
  3266. break;
  3267. case Builtin::BI__sync_fetch_and_nand:
  3268. case Builtin::BI__sync_fetch_and_nand_1:
  3269. case Builtin::BI__sync_fetch_and_nand_2:
  3270. case Builtin::BI__sync_fetch_and_nand_4:
  3271. case Builtin::BI__sync_fetch_and_nand_8:
  3272. case Builtin::BI__sync_fetch_and_nand_16:
  3273. BuiltinIndex = 5;
  3274. WarnAboutSemanticsChange = true;
  3275. break;
  3276. case Builtin::BI__sync_add_and_fetch:
  3277. case Builtin::BI__sync_add_and_fetch_1:
  3278. case Builtin::BI__sync_add_and_fetch_2:
  3279. case Builtin::BI__sync_add_and_fetch_4:
  3280. case Builtin::BI__sync_add_and_fetch_8:
  3281. case Builtin::BI__sync_add_and_fetch_16:
  3282. BuiltinIndex = 6;
  3283. break;
  3284. case Builtin::BI__sync_sub_and_fetch:
  3285. case Builtin::BI__sync_sub_and_fetch_1:
  3286. case Builtin::BI__sync_sub_and_fetch_2:
  3287. case Builtin::BI__sync_sub_and_fetch_4:
  3288. case Builtin::BI__sync_sub_and_fetch_8:
  3289. case Builtin::BI__sync_sub_and_fetch_16:
  3290. BuiltinIndex = 7;
  3291. break;
  3292. case Builtin::BI__sync_and_and_fetch:
  3293. case Builtin::BI__sync_and_and_fetch_1:
  3294. case Builtin::BI__sync_and_and_fetch_2:
  3295. case Builtin::BI__sync_and_and_fetch_4:
  3296. case Builtin::BI__sync_and_and_fetch_8:
  3297. case Builtin::BI__sync_and_and_fetch_16:
  3298. BuiltinIndex = 8;
  3299. break;
  3300. case Builtin::BI__sync_or_and_fetch:
  3301. case Builtin::BI__sync_or_and_fetch_1:
  3302. case Builtin::BI__sync_or_and_fetch_2:
  3303. case Builtin::BI__sync_or_and_fetch_4:
  3304. case Builtin::BI__sync_or_and_fetch_8:
  3305. case Builtin::BI__sync_or_and_fetch_16:
  3306. BuiltinIndex = 9;
  3307. break;
  3308. case Builtin::BI__sync_xor_and_fetch:
  3309. case Builtin::BI__sync_xor_and_fetch_1:
  3310. case Builtin::BI__sync_xor_and_fetch_2:
  3311. case Builtin::BI__sync_xor_and_fetch_4:
  3312. case Builtin::BI__sync_xor_and_fetch_8:
  3313. case Builtin::BI__sync_xor_and_fetch_16:
  3314. BuiltinIndex = 10;
  3315. break;
  3316. case Builtin::BI__sync_nand_and_fetch:
  3317. case Builtin::BI__sync_nand_and_fetch_1:
  3318. case Builtin::BI__sync_nand_and_fetch_2:
  3319. case Builtin::BI__sync_nand_and_fetch_4:
  3320. case Builtin::BI__sync_nand_and_fetch_8:
  3321. case Builtin::BI__sync_nand_and_fetch_16:
  3322. BuiltinIndex = 11;
  3323. WarnAboutSemanticsChange = true;
  3324. break;
  3325. case Builtin::BI__sync_val_compare_and_swap:
  3326. case Builtin::BI__sync_val_compare_and_swap_1:
  3327. case Builtin::BI__sync_val_compare_and_swap_2:
  3328. case Builtin::BI__sync_val_compare_and_swap_4:
  3329. case Builtin::BI__sync_val_compare_and_swap_8:
  3330. case Builtin::BI__sync_val_compare_and_swap_16:
  3331. BuiltinIndex = 12;
  3332. NumFixed = 2;
  3333. break;
  3334. case Builtin::BI__sync_bool_compare_and_swap:
  3335. case Builtin::BI__sync_bool_compare_and_swap_1:
  3336. case Builtin::BI__sync_bool_compare_and_swap_2:
  3337. case Builtin::BI__sync_bool_compare_and_swap_4:
  3338. case Builtin::BI__sync_bool_compare_and_swap_8:
  3339. case Builtin::BI__sync_bool_compare_and_swap_16:
  3340. BuiltinIndex = 13;
  3341. NumFixed = 2;
  3342. ResultType = Context.BoolTy;
  3343. break;
  3344. case Builtin::BI__sync_lock_test_and_set:
  3345. case Builtin::BI__sync_lock_test_and_set_1:
  3346. case Builtin::BI__sync_lock_test_and_set_2:
  3347. case Builtin::BI__sync_lock_test_and_set_4:
  3348. case Builtin::BI__sync_lock_test_and_set_8:
  3349. case Builtin::BI__sync_lock_test_and_set_16:
  3350. BuiltinIndex = 14;
  3351. break;
  3352. case Builtin::BI__sync_lock_release:
  3353. case Builtin::BI__sync_lock_release_1:
  3354. case Builtin::BI__sync_lock_release_2:
  3355. case Builtin::BI__sync_lock_release_4:
  3356. case Builtin::BI__sync_lock_release_8:
  3357. case Builtin::BI__sync_lock_release_16:
  3358. BuiltinIndex = 15;
  3359. NumFixed = 0;
  3360. ResultType = Context.VoidTy;
  3361. break;
  3362. case Builtin::BI__sync_swap:
  3363. case Builtin::BI__sync_swap_1:
  3364. case Builtin::BI__sync_swap_2:
  3365. case Builtin::BI__sync_swap_4:
  3366. case Builtin::BI__sync_swap_8:
  3367. case Builtin::BI__sync_swap_16:
  3368. BuiltinIndex = 16;
  3369. break;
  3370. }
  3371. // Now that we know how many fixed arguments we expect, first check that we
  3372. // have at least that many.
  3373. if (TheCall->getNumArgs() < 1+NumFixed) {
  3374. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  3375. << 0 << 1+NumFixed << TheCall->getNumArgs()
  3376. << TheCall->getCallee()->getSourceRange();
  3377. return ExprError();
  3378. }
  3379. if (WarnAboutSemanticsChange) {
  3380. Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
  3381. << TheCall->getCallee()->getSourceRange();
  3382. }
  3383. // Get the decl for the concrete builtin from this, we can tell what the
  3384. // concrete integer type we should convert to is.
  3385. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  3386. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  3387. FunctionDecl *NewBuiltinDecl;
  3388. if (NewBuiltinID == BuiltinID)
  3389. NewBuiltinDecl = FDecl;
  3390. else {
  3391. // Perform builtin lookup to avoid redeclaring it.
  3392. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  3393. LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
  3394. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  3395. assert(Res.getFoundDecl());
  3396. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  3397. if (!NewBuiltinDecl)
  3398. return ExprError();
  3399. }
  3400. // The first argument --- the pointer --- has a fixed type; we
  3401. // deduce the types of the rest of the arguments accordingly. Walk
  3402. // the remaining arguments, converting them to the deduced value type.
  3403. for (unsigned i = 0; i != NumFixed; ++i) {
  3404. ExprResult Arg = TheCall->getArg(i+1);
  3405. // GCC does an implicit conversion to the pointer or integer ValType. This
  3406. // can fail in some cases (1i -> int**), check for this error case now.
  3407. // Initialize the argument.
  3408. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  3409. ValType, /*consume*/ false);
  3410. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  3411. if (Arg.isInvalid())
  3412. return ExprError();
  3413. // Okay, we have something that *can* be converted to the right type. Check
  3414. // to see if there is a potentially weird extension going on here. This can
  3415. // happen when you do an atomic operation on something like an char* and
  3416. // pass in 42. The 42 gets converted to char. This is even more strange
  3417. // for things like 45.123 -> char, etc.
  3418. // FIXME: Do this check.
  3419. TheCall->setArg(i+1, Arg.get());
  3420. }
  3421. ASTContext& Context = this->getASTContext();
  3422. // Create a new DeclRefExpr to refer to the new decl.
  3423. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  3424. Context,
  3425. DRE->getQualifierLoc(),
  3426. SourceLocation(),
  3427. NewBuiltinDecl,
  3428. /*enclosing*/ false,
  3429. DRE->getLocation(),
  3430. Context.BuiltinFnTy,
  3431. DRE->getValueKind());
  3432. // Set the callee in the CallExpr.
  3433. // FIXME: This loses syntactic information.
  3434. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  3435. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  3436. CK_BuiltinFnToFnPtr);
  3437. TheCall->setCallee(PromotedCall.get());
  3438. // Change the result type of the call to match the original value type. This
  3439. // is arbitrary, but the codegen for these builtins ins design to handle it
  3440. // gracefully.
  3441. TheCall->setType(ResultType);
  3442. return TheCallResult;
  3443. }
  3444. /// SemaBuiltinNontemporalOverloaded - We have a call to
  3445. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  3446. /// overloaded function based on the pointer type of its last argument.
  3447. ///
  3448. /// This function goes through and does final semantic checking for these
  3449. /// builtins.
  3450. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  3451. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  3452. DeclRefExpr *DRE =
  3453. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  3454. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  3455. unsigned BuiltinID = FDecl->getBuiltinID();
  3456. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  3457. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  3458. "Unexpected nontemporal load/store builtin!");
  3459. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  3460. unsigned numArgs = isStore ? 2 : 1;
  3461. // Ensure that we have the proper number of arguments.
  3462. if (checkArgCount(*this, TheCall, numArgs))
  3463. return ExprError();
  3464. // Inspect the last argument of the nontemporal builtin. This should always
  3465. // be a pointer type, from which we imply the type of the memory access.
  3466. // Because it is a pointer type, we don't have to worry about any implicit
  3467. // casts here.
  3468. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  3469. ExprResult PointerArgResult =
  3470. DefaultFunctionArrayLvalueConversion(PointerArg);
  3471. if (PointerArgResult.isInvalid())
  3472. return ExprError();
  3473. PointerArg = PointerArgResult.get();
  3474. TheCall->setArg(numArgs - 1, PointerArg);
  3475. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  3476. if (!pointerType) {
  3477. Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
  3478. << PointerArg->getType() << PointerArg->getSourceRange();
  3479. return ExprError();
  3480. }
  3481. QualType ValType = pointerType->getPointeeType();
  3482. // Strip any qualifiers off ValType.
  3483. ValType = ValType.getUnqualifiedType();
  3484. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  3485. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  3486. !ValType->isVectorType()) {
  3487. Diag(DRE->getLocStart(),
  3488. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  3489. << PointerArg->getType() << PointerArg->getSourceRange();
  3490. return ExprError();
  3491. }
  3492. if (!isStore) {
  3493. TheCall->setType(ValType);
  3494. return TheCallResult;
  3495. }
  3496. ExprResult ValArg = TheCall->getArg(0);
  3497. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  3498. Context, ValType, /*consume*/ false);
  3499. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  3500. if (ValArg.isInvalid())
  3501. return ExprError();
  3502. TheCall->setArg(0, ValArg.get());
  3503. TheCall->setType(Context.VoidTy);
  3504. return TheCallResult;
  3505. }
  3506. /// CheckObjCString - Checks that the argument to the builtin
  3507. /// CFString constructor is correct
  3508. /// Note: It might also make sense to do the UTF-16 conversion here (would
  3509. /// simplify the backend).
  3510. bool Sema::CheckObjCString(Expr *Arg) {
  3511. Arg = Arg->IgnoreParenCasts();
  3512. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  3513. if (!Literal || !Literal->isAscii()) {
  3514. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  3515. << Arg->getSourceRange();
  3516. return true;
  3517. }
  3518. if (Literal->containsNonAsciiOrNull()) {
  3519. StringRef String = Literal->getString();
  3520. unsigned NumBytes = String.size();
  3521. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  3522. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  3523. llvm::UTF16 *ToPtr = &ToBuf[0];
  3524. llvm::ConversionResult Result =
  3525. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  3526. ToPtr + NumBytes, llvm::strictConversion);
  3527. // Check for conversion failure.
  3528. if (Result != llvm::conversionOK)
  3529. Diag(Arg->getLocStart(),
  3530. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  3531. }
  3532. return false;
  3533. }
  3534. /// CheckObjCString - Checks that the format string argument to the os_log()
  3535. /// and os_trace() functions is correct, and converts it to const char *.
  3536. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  3537. Arg = Arg->IgnoreParenCasts();
  3538. auto *Literal = dyn_cast<StringLiteral>(Arg);
  3539. if (!Literal) {
  3540. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  3541. Literal = ObjcLiteral->getString();
  3542. }
  3543. }
  3544. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  3545. return ExprError(
  3546. Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
  3547. << Arg->getSourceRange());
  3548. }
  3549. ExprResult Result(Literal);
  3550. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  3551. InitializedEntity Entity =
  3552. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  3553. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  3554. return Result;
  3555. }
  3556. /// Check that the user is calling the appropriate va_start builtin for the
  3557. /// target and calling convention.
  3558. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  3559. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  3560. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  3561. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  3562. bool IsWindows = TT.isOSWindows();
  3563. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  3564. if (IsX64 || IsAArch64) {
  3565. CallingConv CC = CC_C;
  3566. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  3567. CC = FD->getType()->getAs<FunctionType>()->getCallConv();
  3568. if (IsMSVAStart) {
  3569. // Don't allow this in System V ABI functions.
  3570. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  3571. return S.Diag(Fn->getLocStart(),
  3572. diag::err_ms_va_start_used_in_sysv_function);
  3573. } else {
  3574. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  3575. // On x64 Windows, don't allow this in System V ABI functions.
  3576. // (Yes, that means there's no corresponding way to support variadic
  3577. // System V ABI functions on Windows.)
  3578. if ((IsWindows && CC == CC_X86_64SysV) ||
  3579. (!IsWindows && CC == CC_Win64))
  3580. return S.Diag(Fn->getLocStart(),
  3581. diag::err_va_start_used_in_wrong_abi_function)
  3582. << !IsWindows;
  3583. }
  3584. return false;
  3585. }
  3586. if (IsMSVAStart)
  3587. return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
  3588. return false;
  3589. }
  3590. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  3591. ParmVarDecl **LastParam = nullptr) {
  3592. // Determine whether the current function, block, or obj-c method is variadic
  3593. // and get its parameter list.
  3594. bool IsVariadic = false;
  3595. ArrayRef<ParmVarDecl *> Params;
  3596. DeclContext *Caller = S.CurContext;
  3597. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  3598. IsVariadic = Block->isVariadic();
  3599. Params = Block->parameters();
  3600. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  3601. IsVariadic = FD->isVariadic();
  3602. Params = FD->parameters();
  3603. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  3604. IsVariadic = MD->isVariadic();
  3605. // FIXME: This isn't correct for methods (results in bogus warning).
  3606. Params = MD->parameters();
  3607. } else if (isa<CapturedDecl>(Caller)) {
  3608. // We don't support va_start in a CapturedDecl.
  3609. S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
  3610. return true;
  3611. } else {
  3612. // This must be some other declcontext that parses exprs.
  3613. S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
  3614. return true;
  3615. }
  3616. if (!IsVariadic) {
  3617. S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
  3618. return true;
  3619. }
  3620. if (LastParam)
  3621. *LastParam = Params.empty() ? nullptr : Params.back();
  3622. return false;
  3623. }
  3624. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  3625. /// for validity. Emit an error and return true on failure; return false
  3626. /// on success.
  3627. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  3628. Expr *Fn = TheCall->getCallee();
  3629. if (checkVAStartABI(*this, BuiltinID, Fn))
  3630. return true;
  3631. if (TheCall->getNumArgs() > 2) {
  3632. Diag(TheCall->getArg(2)->getLocStart(),
  3633. diag::err_typecheck_call_too_many_args)
  3634. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  3635. << Fn->getSourceRange()
  3636. << SourceRange(TheCall->getArg(2)->getLocStart(),
  3637. (*(TheCall->arg_end()-1))->getLocEnd());
  3638. return true;
  3639. }
  3640. if (TheCall->getNumArgs() < 2) {
  3641. return Diag(TheCall->getLocEnd(),
  3642. diag::err_typecheck_call_too_few_args_at_least)
  3643. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  3644. }
  3645. // Type-check the first argument normally.
  3646. if (checkBuiltinArgument(*this, TheCall, 0))
  3647. return true;
  3648. // Check that the current function is variadic, and get its last parameter.
  3649. ParmVarDecl *LastParam;
  3650. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  3651. return true;
  3652. // Verify that the second argument to the builtin is the last argument of the
  3653. // current function or method.
  3654. bool SecondArgIsLastNamedArgument = false;
  3655. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  3656. // These are valid if SecondArgIsLastNamedArgument is false after the next
  3657. // block.
  3658. QualType Type;
  3659. SourceLocation ParamLoc;
  3660. bool IsCRegister = false;
  3661. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  3662. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  3663. SecondArgIsLastNamedArgument = PV == LastParam;
  3664. Type = PV->getType();
  3665. ParamLoc = PV->getLocation();
  3666. IsCRegister =
  3667. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  3668. }
  3669. }
  3670. if (!SecondArgIsLastNamedArgument)
  3671. Diag(TheCall->getArg(1)->getLocStart(),
  3672. diag::warn_second_arg_of_va_start_not_last_named_param);
  3673. else if (IsCRegister || Type->isReferenceType() ||
  3674. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  3675. // Promotable integers are UB, but enumerations need a bit of
  3676. // extra checking to see what their promotable type actually is.
  3677. if (!Type->isPromotableIntegerType())
  3678. return false;
  3679. if (!Type->isEnumeralType())
  3680. return true;
  3681. const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
  3682. return !(ED &&
  3683. Context.typesAreCompatible(ED->getPromotionType(), Type));
  3684. }()) {
  3685. unsigned Reason = 0;
  3686. if (Type->isReferenceType()) Reason = 1;
  3687. else if (IsCRegister) Reason = 2;
  3688. Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
  3689. Diag(ParamLoc, diag::note_parameter_type) << Type;
  3690. }
  3691. TheCall->setType(Context.VoidTy);
  3692. return false;
  3693. }
  3694. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  3695. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  3696. // const char *named_addr);
  3697. Expr *Func = Call->getCallee();
  3698. if (Call->getNumArgs() < 3)
  3699. return Diag(Call->getLocEnd(),
  3700. diag::err_typecheck_call_too_few_args_at_least)
  3701. << 0 /*function call*/ << 3 << Call->getNumArgs();
  3702. // Type-check the first argument normally.
  3703. if (checkBuiltinArgument(*this, Call, 0))
  3704. return true;
  3705. // Check that the current function is variadic.
  3706. if (checkVAStartIsInVariadicFunction(*this, Func))
  3707. return true;
  3708. // __va_start on Windows does not validate the parameter qualifiers
  3709. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  3710. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  3711. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  3712. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  3713. const QualType &ConstCharPtrTy =
  3714. Context.getPointerType(Context.CharTy.withConst());
  3715. if (!Arg1Ty->isPointerType() ||
  3716. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  3717. Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
  3718. << Arg1->getType() << ConstCharPtrTy
  3719. << 1 /* different class */
  3720. << 0 /* qualifier difference */
  3721. << 3 /* parameter mismatch */
  3722. << 2 << Arg1->getType() << ConstCharPtrTy;
  3723. const QualType SizeTy = Context.getSizeType();
  3724. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  3725. Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
  3726. << Arg2->getType() << SizeTy
  3727. << 1 /* different class */
  3728. << 0 /* qualifier difference */
  3729. << 3 /* parameter mismatch */
  3730. << 3 << Arg2->getType() << SizeTy;
  3731. return false;
  3732. }
  3733. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  3734. /// friends. This is declared to take (...), so we have to check everything.
  3735. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  3736. if (TheCall->getNumArgs() < 2)
  3737. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  3738. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  3739. if (TheCall->getNumArgs() > 2)
  3740. return Diag(TheCall->getArg(2)->getLocStart(),
  3741. diag::err_typecheck_call_too_many_args)
  3742. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  3743. << SourceRange(TheCall->getArg(2)->getLocStart(),
  3744. (*(TheCall->arg_end()-1))->getLocEnd());
  3745. ExprResult OrigArg0 = TheCall->getArg(0);
  3746. ExprResult OrigArg1 = TheCall->getArg(1);
  3747. // Do standard promotions between the two arguments, returning their common
  3748. // type.
  3749. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  3750. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  3751. return true;
  3752. // Make sure any conversions are pushed back into the call; this is
  3753. // type safe since unordered compare builtins are declared as "_Bool
  3754. // foo(...)".
  3755. TheCall->setArg(0, OrigArg0.get());
  3756. TheCall->setArg(1, OrigArg1.get());
  3757. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  3758. return false;
  3759. // If the common type isn't a real floating type, then the arguments were
  3760. // invalid for this operation.
  3761. if (Res.isNull() || !Res->isRealFloatingType())
  3762. return Diag(OrigArg0.get()->getLocStart(),
  3763. diag::err_typecheck_call_invalid_ordered_compare)
  3764. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  3765. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  3766. return false;
  3767. }
  3768. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  3769. /// __builtin_isnan and friends. This is declared to take (...), so we have
  3770. /// to check everything. We expect the last argument to be a floating point
  3771. /// value.
  3772. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  3773. if (TheCall->getNumArgs() < NumArgs)
  3774. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  3775. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  3776. if (TheCall->getNumArgs() > NumArgs)
  3777. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  3778. diag::err_typecheck_call_too_many_args)
  3779. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  3780. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  3781. (*(TheCall->arg_end()-1))->getLocEnd());
  3782. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  3783. if (OrigArg->isTypeDependent())
  3784. return false;
  3785. // This operation requires a non-_Complex floating-point number.
  3786. if (!OrigArg->getType()->isRealFloatingType())
  3787. return Diag(OrigArg->getLocStart(),
  3788. diag::err_typecheck_call_invalid_unary_fp)
  3789. << OrigArg->getType() << OrigArg->getSourceRange();
  3790. // If this is an implicit conversion from float -> float or double, remove it.
  3791. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  3792. // Only remove standard FloatCasts, leaving other casts inplace
  3793. if (Cast->getCastKind() == CK_FloatingCast) {
  3794. Expr *CastArg = Cast->getSubExpr();
  3795. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  3796. assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  3797. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
  3798. "promotion from float to either float or double is the only expected cast here");
  3799. Cast->setSubExpr(nullptr);
  3800. TheCall->setArg(NumArgs-1, CastArg);
  3801. }
  3802. }
  3803. }
  3804. return false;
  3805. }
  3806. // Customized Sema Checking for VSX builtins that have the following signature:
  3807. // vector [...] builtinName(vector [...], vector [...], const int);
  3808. // Which takes the same type of vectors (any legal vector type) for the first
  3809. // two arguments and takes compile time constant for the third argument.
  3810. // Example builtins are :
  3811. // vector double vec_xxpermdi(vector double, vector double, int);
  3812. // vector short vec_xxsldwi(vector short, vector short, int);
  3813. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  3814. unsigned ExpectedNumArgs = 3;
  3815. if (TheCall->getNumArgs() < ExpectedNumArgs)
  3816. return Diag(TheCall->getLocEnd(),
  3817. diag::err_typecheck_call_too_few_args_at_least)
  3818. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  3819. << TheCall->getSourceRange();
  3820. if (TheCall->getNumArgs() > ExpectedNumArgs)
  3821. return Diag(TheCall->getLocEnd(),
  3822. diag::err_typecheck_call_too_many_args_at_most)
  3823. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  3824. << TheCall->getSourceRange();
  3825. // Check the third argument is a compile time constant
  3826. llvm::APSInt Value;
  3827. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  3828. return Diag(TheCall->getLocStart(),
  3829. diag::err_vsx_builtin_nonconstant_argument)
  3830. << 3 /* argument index */ << TheCall->getDirectCallee()
  3831. << SourceRange(TheCall->getArg(2)->getLocStart(),
  3832. TheCall->getArg(2)->getLocEnd());
  3833. QualType Arg1Ty = TheCall->getArg(0)->getType();
  3834. QualType Arg2Ty = TheCall->getArg(1)->getType();
  3835. // Check the type of argument 1 and argument 2 are vectors.
  3836. SourceLocation BuiltinLoc = TheCall->getLocStart();
  3837. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  3838. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  3839. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  3840. << TheCall->getDirectCallee()
  3841. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3842. TheCall->getArg(1)->getLocEnd());
  3843. }
  3844. // Check the first two arguments are the same type.
  3845. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  3846. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  3847. << TheCall->getDirectCallee()
  3848. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3849. TheCall->getArg(1)->getLocEnd());
  3850. }
  3851. // When default clang type checking is turned off and the customized type
  3852. // checking is used, the returning type of the function must be explicitly
  3853. // set. Otherwise it is _Bool by default.
  3854. TheCall->setType(Arg1Ty);
  3855. return false;
  3856. }
  3857. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  3858. // This is declared to take (...), so we have to check everything.
  3859. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  3860. if (TheCall->getNumArgs() < 2)
  3861. return ExprError(Diag(TheCall->getLocEnd(),
  3862. diag::err_typecheck_call_too_few_args_at_least)
  3863. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  3864. << TheCall->getSourceRange());
  3865. // Determine which of the following types of shufflevector we're checking:
  3866. // 1) unary, vector mask: (lhs, mask)
  3867. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  3868. QualType resType = TheCall->getArg(0)->getType();
  3869. unsigned numElements = 0;
  3870. if (!TheCall->getArg(0)->isTypeDependent() &&
  3871. !TheCall->getArg(1)->isTypeDependent()) {
  3872. QualType LHSType = TheCall->getArg(0)->getType();
  3873. QualType RHSType = TheCall->getArg(1)->getType();
  3874. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  3875. return ExprError(Diag(TheCall->getLocStart(),
  3876. diag::err_vec_builtin_non_vector)
  3877. << TheCall->getDirectCallee()
  3878. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3879. TheCall->getArg(1)->getLocEnd()));
  3880. numElements = LHSType->getAs<VectorType>()->getNumElements();
  3881. unsigned numResElements = TheCall->getNumArgs() - 2;
  3882. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  3883. // with mask. If so, verify that RHS is an integer vector type with the
  3884. // same number of elts as lhs.
  3885. if (TheCall->getNumArgs() == 2) {
  3886. if (!RHSType->hasIntegerRepresentation() ||
  3887. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  3888. return ExprError(Diag(TheCall->getLocStart(),
  3889. diag::err_vec_builtin_incompatible_vector)
  3890. << TheCall->getDirectCallee()
  3891. << SourceRange(TheCall->getArg(1)->getLocStart(),
  3892. TheCall->getArg(1)->getLocEnd()));
  3893. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  3894. return ExprError(Diag(TheCall->getLocStart(),
  3895. diag::err_vec_builtin_incompatible_vector)
  3896. << TheCall->getDirectCallee()
  3897. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3898. TheCall->getArg(1)->getLocEnd()));
  3899. } else if (numElements != numResElements) {
  3900. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  3901. resType = Context.getVectorType(eltType, numResElements,
  3902. VectorType::GenericVector);
  3903. }
  3904. }
  3905. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  3906. if (TheCall->getArg(i)->isTypeDependent() ||
  3907. TheCall->getArg(i)->isValueDependent())
  3908. continue;
  3909. llvm::APSInt Result(32);
  3910. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  3911. return ExprError(Diag(TheCall->getLocStart(),
  3912. diag::err_shufflevector_nonconstant_argument)
  3913. << TheCall->getArg(i)->getSourceRange());
  3914. // Allow -1 which will be translated to undef in the IR.
  3915. if (Result.isSigned() && Result.isAllOnesValue())
  3916. continue;
  3917. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  3918. return ExprError(Diag(TheCall->getLocStart(),
  3919. diag::err_shufflevector_argument_too_large)
  3920. << TheCall->getArg(i)->getSourceRange());
  3921. }
  3922. SmallVector<Expr*, 32> exprs;
  3923. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  3924. exprs.push_back(TheCall->getArg(i));
  3925. TheCall->setArg(i, nullptr);
  3926. }
  3927. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  3928. TheCall->getCallee()->getLocStart(),
  3929. TheCall->getRParenLoc());
  3930. }
  3931. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  3932. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  3933. SourceLocation BuiltinLoc,
  3934. SourceLocation RParenLoc) {
  3935. ExprValueKind VK = VK_RValue;
  3936. ExprObjectKind OK = OK_Ordinary;
  3937. QualType DstTy = TInfo->getType();
  3938. QualType SrcTy = E->getType();
  3939. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  3940. return ExprError(Diag(BuiltinLoc,
  3941. diag::err_convertvector_non_vector)
  3942. << E->getSourceRange());
  3943. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  3944. return ExprError(Diag(BuiltinLoc,
  3945. diag::err_convertvector_non_vector_type));
  3946. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  3947. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  3948. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  3949. if (SrcElts != DstElts)
  3950. return ExprError(Diag(BuiltinLoc,
  3951. diag::err_convertvector_incompatible_vector)
  3952. << E->getSourceRange());
  3953. }
  3954. return new (Context)
  3955. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  3956. }
  3957. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  3958. // This is declared to take (const void*, ...) and can take two
  3959. // optional constant int args.
  3960. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  3961. unsigned NumArgs = TheCall->getNumArgs();
  3962. if (NumArgs > 3)
  3963. return Diag(TheCall->getLocEnd(),
  3964. diag::err_typecheck_call_too_many_args_at_most)
  3965. << 0 /*function call*/ << 3 << NumArgs
  3966. << TheCall->getSourceRange();
  3967. // Argument 0 is checked for us and the remaining arguments must be
  3968. // constant integers.
  3969. for (unsigned i = 1; i != NumArgs; ++i)
  3970. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  3971. return true;
  3972. return false;
  3973. }
  3974. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  3975. // __assume does not evaluate its arguments, and should warn if its argument
  3976. // has side effects.
  3977. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  3978. Expr *Arg = TheCall->getArg(0);
  3979. if (Arg->isInstantiationDependent()) return false;
  3980. if (Arg->HasSideEffects(Context))
  3981. Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
  3982. << Arg->getSourceRange()
  3983. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  3984. return false;
  3985. }
  3986. /// Handle __builtin_alloca_with_align. This is declared
  3987. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  3988. /// than 8.
  3989. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  3990. // The alignment must be a constant integer.
  3991. Expr *Arg = TheCall->getArg(1);
  3992. // We can't check the value of a dependent argument.
  3993. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  3994. if (const auto *UE =
  3995. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  3996. if (UE->getKind() == UETT_AlignOf)
  3997. Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
  3998. << Arg->getSourceRange();
  3999. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  4000. if (!Result.isPowerOf2())
  4001. return Diag(TheCall->getLocStart(),
  4002. diag::err_alignment_not_power_of_two)
  4003. << Arg->getSourceRange();
  4004. if (Result < Context.getCharWidth())
  4005. return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
  4006. << (unsigned)Context.getCharWidth()
  4007. << Arg->getSourceRange();
  4008. if (Result > std::numeric_limits<int32_t>::max())
  4009. return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
  4010. << std::numeric_limits<int32_t>::max()
  4011. << Arg->getSourceRange();
  4012. }
  4013. return false;
  4014. }
  4015. /// Handle __builtin_assume_aligned. This is declared
  4016. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  4017. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  4018. unsigned NumArgs = TheCall->getNumArgs();
  4019. if (NumArgs > 3)
  4020. return Diag(TheCall->getLocEnd(),
  4021. diag::err_typecheck_call_too_many_args_at_most)
  4022. << 0 /*function call*/ << 3 << NumArgs
  4023. << TheCall->getSourceRange();
  4024. // The alignment must be a constant integer.
  4025. Expr *Arg = TheCall->getArg(1);
  4026. // We can't check the value of a dependent argument.
  4027. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  4028. llvm::APSInt Result;
  4029. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  4030. return true;
  4031. if (!Result.isPowerOf2())
  4032. return Diag(TheCall->getLocStart(),
  4033. diag::err_alignment_not_power_of_two)
  4034. << Arg->getSourceRange();
  4035. }
  4036. if (NumArgs > 2) {
  4037. ExprResult Arg(TheCall->getArg(2));
  4038. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  4039. Context.getSizeType(), false);
  4040. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4041. if (Arg.isInvalid()) return true;
  4042. TheCall->setArg(2, Arg.get());
  4043. }
  4044. return false;
  4045. }
  4046. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  4047. unsigned BuiltinID =
  4048. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  4049. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  4050. unsigned NumArgs = TheCall->getNumArgs();
  4051. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  4052. if (NumArgs < NumRequiredArgs) {
  4053. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  4054. << 0 /* function call */ << NumRequiredArgs << NumArgs
  4055. << TheCall->getSourceRange();
  4056. }
  4057. if (NumArgs >= NumRequiredArgs + 0x100) {
  4058. return Diag(TheCall->getLocEnd(),
  4059. diag::err_typecheck_call_too_many_args_at_most)
  4060. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  4061. << TheCall->getSourceRange();
  4062. }
  4063. unsigned i = 0;
  4064. // For formatting call, check buffer arg.
  4065. if (!IsSizeCall) {
  4066. ExprResult Arg(TheCall->getArg(i));
  4067. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4068. Context, Context.VoidPtrTy, false);
  4069. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4070. if (Arg.isInvalid())
  4071. return true;
  4072. TheCall->setArg(i, Arg.get());
  4073. i++;
  4074. }
  4075. // Check string literal arg.
  4076. unsigned FormatIdx = i;
  4077. {
  4078. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  4079. if (Arg.isInvalid())
  4080. return true;
  4081. TheCall->setArg(i, Arg.get());
  4082. i++;
  4083. }
  4084. // Make sure variadic args are scalar.
  4085. unsigned FirstDataArg = i;
  4086. while (i < NumArgs) {
  4087. ExprResult Arg = DefaultVariadicArgumentPromotion(
  4088. TheCall->getArg(i), VariadicFunction, nullptr);
  4089. if (Arg.isInvalid())
  4090. return true;
  4091. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  4092. if (ArgSize.getQuantity() >= 0x100) {
  4093. return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
  4094. << i << (int)ArgSize.getQuantity() << 0xff
  4095. << TheCall->getSourceRange();
  4096. }
  4097. TheCall->setArg(i, Arg.get());
  4098. i++;
  4099. }
  4100. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  4101. // call to avoid duplicate diagnostics.
  4102. if (!IsSizeCall) {
  4103. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  4104. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  4105. bool Success = CheckFormatArguments(
  4106. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  4107. VariadicFunction, TheCall->getLocStart(), SourceRange(),
  4108. CheckedVarArgs);
  4109. if (!Success)
  4110. return true;
  4111. }
  4112. if (IsSizeCall) {
  4113. TheCall->setType(Context.getSizeType());
  4114. } else {
  4115. TheCall->setType(Context.VoidPtrTy);
  4116. }
  4117. return false;
  4118. }
  4119. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  4120. /// TheCall is a constant expression.
  4121. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  4122. llvm::APSInt &Result) {
  4123. Expr *Arg = TheCall->getArg(ArgNum);
  4124. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4125. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4126. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  4127. if (!Arg->isIntegerConstantExpr(Result, Context))
  4128. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  4129. << FDecl->getDeclName() << Arg->getSourceRange();
  4130. return false;
  4131. }
  4132. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  4133. /// TheCall is a constant expression in the range [Low, High].
  4134. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  4135. int Low, int High) {
  4136. llvm::APSInt Result;
  4137. // We can't check the value of a dependent argument.
  4138. Expr *Arg = TheCall->getArg(ArgNum);
  4139. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4140. return false;
  4141. // Check constant-ness first.
  4142. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4143. return true;
  4144. if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
  4145. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  4146. << Low << High << Arg->getSourceRange();
  4147. return false;
  4148. }
  4149. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  4150. /// TheCall is a constant expression is a multiple of Num..
  4151. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  4152. unsigned Num) {
  4153. llvm::APSInt Result;
  4154. // We can't check the value of a dependent argument.
  4155. Expr *Arg = TheCall->getArg(ArgNum);
  4156. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4157. return false;
  4158. // Check constant-ness first.
  4159. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4160. return true;
  4161. if (Result.getSExtValue() % Num != 0)
  4162. return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
  4163. << Num << Arg->getSourceRange();
  4164. return false;
  4165. }
  4166. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  4167. /// TheCall is an ARM/AArch64 special register string literal.
  4168. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  4169. int ArgNum, unsigned ExpectedFieldNum,
  4170. bool AllowName) {
  4171. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  4172. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  4173. BuiltinID == ARM::BI__builtin_arm_rsr ||
  4174. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  4175. BuiltinID == ARM::BI__builtin_arm_wsr ||
  4176. BuiltinID == ARM::BI__builtin_arm_wsrp;
  4177. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  4178. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  4179. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  4180. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  4181. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  4182. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  4183. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  4184. // We can't check the value of a dependent argument.
  4185. Expr *Arg = TheCall->getArg(ArgNum);
  4186. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4187. return false;
  4188. // Check if the argument is a string literal.
  4189. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  4190. return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  4191. << Arg->getSourceRange();
  4192. // Check the type of special register given.
  4193. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  4194. SmallVector<StringRef, 6> Fields;
  4195. Reg.split(Fields, ":");
  4196. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  4197. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  4198. << Arg->getSourceRange();
  4199. // If the string is the name of a register then we cannot check that it is
  4200. // valid here but if the string is of one the forms described in ACLE then we
  4201. // can check that the supplied fields are integers and within the valid
  4202. // ranges.
  4203. if (Fields.size() > 1) {
  4204. bool FiveFields = Fields.size() == 5;
  4205. bool ValidString = true;
  4206. if (IsARMBuiltin) {
  4207. ValidString &= Fields[0].startswith_lower("cp") ||
  4208. Fields[0].startswith_lower("p");
  4209. if (ValidString)
  4210. Fields[0] =
  4211. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  4212. ValidString &= Fields[2].startswith_lower("c");
  4213. if (ValidString)
  4214. Fields[2] = Fields[2].drop_front(1);
  4215. if (FiveFields) {
  4216. ValidString &= Fields[3].startswith_lower("c");
  4217. if (ValidString)
  4218. Fields[3] = Fields[3].drop_front(1);
  4219. }
  4220. }
  4221. SmallVector<int, 5> Ranges;
  4222. if (FiveFields)
  4223. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  4224. else
  4225. Ranges.append({15, 7, 15});
  4226. for (unsigned i=0; i<Fields.size(); ++i) {
  4227. int IntField;
  4228. ValidString &= !Fields[i].getAsInteger(10, IntField);
  4229. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  4230. }
  4231. if (!ValidString)
  4232. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  4233. << Arg->getSourceRange();
  4234. } else if (IsAArch64Builtin && Fields.size() == 1) {
  4235. // If the register name is one of those that appear in the condition below
  4236. // and the special register builtin being used is one of the write builtins,
  4237. // then we require that the argument provided for writing to the register
  4238. // is an integer constant expression. This is because it will be lowered to
  4239. // an MSR (immediate) instruction, so we need to know the immediate at
  4240. // compile time.
  4241. if (TheCall->getNumArgs() != 2)
  4242. return false;
  4243. std::string RegLower = Reg.lower();
  4244. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  4245. RegLower != "pan" && RegLower != "uao")
  4246. return false;
  4247. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  4248. }
  4249. return false;
  4250. }
  4251. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  4252. /// This checks that the target supports __builtin_longjmp and
  4253. /// that val is a constant 1.
  4254. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  4255. if (!Context.getTargetInfo().hasSjLjLowering())
  4256. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
  4257. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  4258. Expr *Arg = TheCall->getArg(1);
  4259. llvm::APSInt Result;
  4260. // TODO: This is less than ideal. Overload this to take a value.
  4261. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  4262. return true;
  4263. if (Result != 1)
  4264. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  4265. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  4266. return false;
  4267. }
  4268. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  4269. /// This checks that the target supports __builtin_setjmp.
  4270. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  4271. if (!Context.getTargetInfo().hasSjLjLowering())
  4272. return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
  4273. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  4274. return false;
  4275. }
  4276. namespace {
  4277. class UncoveredArgHandler {
  4278. enum { Unknown = -1, AllCovered = -2 };
  4279. signed FirstUncoveredArg = Unknown;
  4280. SmallVector<const Expr *, 4> DiagnosticExprs;
  4281. public:
  4282. UncoveredArgHandler() = default;
  4283. bool hasUncoveredArg() const {
  4284. return (FirstUncoveredArg >= 0);
  4285. }
  4286. unsigned getUncoveredArg() const {
  4287. assert(hasUncoveredArg() && "no uncovered argument");
  4288. return FirstUncoveredArg;
  4289. }
  4290. void setAllCovered() {
  4291. // A string has been found with all arguments covered, so clear out
  4292. // the diagnostics.
  4293. DiagnosticExprs.clear();
  4294. FirstUncoveredArg = AllCovered;
  4295. }
  4296. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  4297. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  4298. // Don't update if a previous string covers all arguments.
  4299. if (FirstUncoveredArg == AllCovered)
  4300. return;
  4301. // UncoveredArgHandler tracks the highest uncovered argument index
  4302. // and with it all the strings that match this index.
  4303. if (NewFirstUncoveredArg == FirstUncoveredArg)
  4304. DiagnosticExprs.push_back(StrExpr);
  4305. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  4306. DiagnosticExprs.clear();
  4307. DiagnosticExprs.push_back(StrExpr);
  4308. FirstUncoveredArg = NewFirstUncoveredArg;
  4309. }
  4310. }
  4311. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  4312. };
  4313. enum StringLiteralCheckType {
  4314. SLCT_NotALiteral,
  4315. SLCT_UncheckedLiteral,
  4316. SLCT_CheckedLiteral
  4317. };
  4318. } // namespace
  4319. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  4320. BinaryOperatorKind BinOpKind,
  4321. bool AddendIsRight) {
  4322. unsigned BitWidth = Offset.getBitWidth();
  4323. unsigned AddendBitWidth = Addend.getBitWidth();
  4324. // There might be negative interim results.
  4325. if (Addend.isUnsigned()) {
  4326. Addend = Addend.zext(++AddendBitWidth);
  4327. Addend.setIsSigned(true);
  4328. }
  4329. // Adjust the bit width of the APSInts.
  4330. if (AddendBitWidth > BitWidth) {
  4331. Offset = Offset.sext(AddendBitWidth);
  4332. BitWidth = AddendBitWidth;
  4333. } else if (BitWidth > AddendBitWidth) {
  4334. Addend = Addend.sext(BitWidth);
  4335. }
  4336. bool Ov = false;
  4337. llvm::APSInt ResOffset = Offset;
  4338. if (BinOpKind == BO_Add)
  4339. ResOffset = Offset.sadd_ov(Addend, Ov);
  4340. else {
  4341. assert(AddendIsRight && BinOpKind == BO_Sub &&
  4342. "operator must be add or sub with addend on the right");
  4343. ResOffset = Offset.ssub_ov(Addend, Ov);
  4344. }
  4345. // We add an offset to a pointer here so we should support an offset as big as
  4346. // possible.
  4347. if (Ov) {
  4348. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  4349. "index (intermediate) result too big");
  4350. Offset = Offset.sext(2 * BitWidth);
  4351. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  4352. return;
  4353. }
  4354. Offset = ResOffset;
  4355. }
  4356. namespace {
  4357. // This is a wrapper class around StringLiteral to support offsetted string
  4358. // literals as format strings. It takes the offset into account when returning
  4359. // the string and its length or the source locations to display notes correctly.
  4360. class FormatStringLiteral {
  4361. const StringLiteral *FExpr;
  4362. int64_t Offset;
  4363. public:
  4364. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  4365. : FExpr(fexpr), Offset(Offset) {}
  4366. StringRef getString() const {
  4367. return FExpr->getString().drop_front(Offset);
  4368. }
  4369. unsigned getByteLength() const {
  4370. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  4371. }
  4372. unsigned getLength() const { return FExpr->getLength() - Offset; }
  4373. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  4374. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  4375. QualType getType() const { return FExpr->getType(); }
  4376. bool isAscii() const { return FExpr->isAscii(); }
  4377. bool isWide() const { return FExpr->isWide(); }
  4378. bool isUTF8() const { return FExpr->isUTF8(); }
  4379. bool isUTF16() const { return FExpr->isUTF16(); }
  4380. bool isUTF32() const { return FExpr->isUTF32(); }
  4381. bool isPascal() const { return FExpr->isPascal(); }
  4382. SourceLocation getLocationOfByte(
  4383. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  4384. const TargetInfo &Target, unsigned *StartToken = nullptr,
  4385. unsigned *StartTokenByteOffset = nullptr) const {
  4386. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  4387. StartToken, StartTokenByteOffset);
  4388. }
  4389. SourceLocation getLocStart() const LLVM_READONLY {
  4390. return FExpr->getLocStart().getLocWithOffset(Offset);
  4391. }
  4392. SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
  4393. };
  4394. } // namespace
  4395. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  4396. const Expr *OrigFormatExpr,
  4397. ArrayRef<const Expr *> Args,
  4398. bool HasVAListArg, unsigned format_idx,
  4399. unsigned firstDataArg,
  4400. Sema::FormatStringType Type,
  4401. bool inFunctionCall,
  4402. Sema::VariadicCallType CallType,
  4403. llvm::SmallBitVector &CheckedVarArgs,
  4404. UncoveredArgHandler &UncoveredArg);
  4405. // Determine if an expression is a string literal or constant string.
  4406. // If this function returns false on the arguments to a function expecting a
  4407. // format string, we will usually need to emit a warning.
  4408. // True string literals are then checked by CheckFormatString.
  4409. static StringLiteralCheckType
  4410. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  4411. bool HasVAListArg, unsigned format_idx,
  4412. unsigned firstDataArg, Sema::FormatStringType Type,
  4413. Sema::VariadicCallType CallType, bool InFunctionCall,
  4414. llvm::SmallBitVector &CheckedVarArgs,
  4415. UncoveredArgHandler &UncoveredArg,
  4416. llvm::APSInt Offset) {
  4417. tryAgain:
  4418. assert(Offset.isSigned() && "invalid offset");
  4419. if (E->isTypeDependent() || E->isValueDependent())
  4420. return SLCT_NotALiteral;
  4421. E = E->IgnoreParenCasts();
  4422. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  4423. // Technically -Wformat-nonliteral does not warn about this case.
  4424. // The behavior of printf and friends in this case is implementation
  4425. // dependent. Ideally if the format string cannot be null then
  4426. // it should have a 'nonnull' attribute in the function prototype.
  4427. return SLCT_UncheckedLiteral;
  4428. switch (E->getStmtClass()) {
  4429. case Stmt::BinaryConditionalOperatorClass:
  4430. case Stmt::ConditionalOperatorClass: {
  4431. // The expression is a literal if both sub-expressions were, and it was
  4432. // completely checked only if both sub-expressions were checked.
  4433. const AbstractConditionalOperator *C =
  4434. cast<AbstractConditionalOperator>(E);
  4435. // Determine whether it is necessary to check both sub-expressions, for
  4436. // example, because the condition expression is a constant that can be
  4437. // evaluated at compile time.
  4438. bool CheckLeft = true, CheckRight = true;
  4439. bool Cond;
  4440. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
  4441. if (Cond)
  4442. CheckRight = false;
  4443. else
  4444. CheckLeft = false;
  4445. }
  4446. // We need to maintain the offsets for the right and the left hand side
  4447. // separately to check if every possible indexed expression is a valid
  4448. // string literal. They might have different offsets for different string
  4449. // literals in the end.
  4450. StringLiteralCheckType Left;
  4451. if (!CheckLeft)
  4452. Left = SLCT_UncheckedLiteral;
  4453. else {
  4454. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  4455. HasVAListArg, format_idx, firstDataArg,
  4456. Type, CallType, InFunctionCall,
  4457. CheckedVarArgs, UncoveredArg, Offset);
  4458. if (Left == SLCT_NotALiteral || !CheckRight) {
  4459. return Left;
  4460. }
  4461. }
  4462. StringLiteralCheckType Right =
  4463. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  4464. HasVAListArg, format_idx, firstDataArg,
  4465. Type, CallType, InFunctionCall, CheckedVarArgs,
  4466. UncoveredArg, Offset);
  4467. return (CheckLeft && Left < Right) ? Left : Right;
  4468. }
  4469. case Stmt::ImplicitCastExprClass:
  4470. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  4471. goto tryAgain;
  4472. case Stmt::OpaqueValueExprClass:
  4473. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  4474. E = src;
  4475. goto tryAgain;
  4476. }
  4477. return SLCT_NotALiteral;
  4478. case Stmt::PredefinedExprClass:
  4479. // While __func__, etc., are technically not string literals, they
  4480. // cannot contain format specifiers and thus are not a security
  4481. // liability.
  4482. return SLCT_UncheckedLiteral;
  4483. case Stmt::DeclRefExprClass: {
  4484. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  4485. // As an exception, do not flag errors for variables binding to
  4486. // const string literals.
  4487. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  4488. bool isConstant = false;
  4489. QualType T = DR->getType();
  4490. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  4491. isConstant = AT->getElementType().isConstant(S.Context);
  4492. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  4493. isConstant = T.isConstant(S.Context) &&
  4494. PT->getPointeeType().isConstant(S.Context);
  4495. } else if (T->isObjCObjectPointerType()) {
  4496. // In ObjC, there is usually no "const ObjectPointer" type,
  4497. // so don't check if the pointee type is constant.
  4498. isConstant = T.isConstant(S.Context);
  4499. }
  4500. if (isConstant) {
  4501. if (const Expr *Init = VD->getAnyInitializer()) {
  4502. // Look through initializers like const char c[] = { "foo" }
  4503. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  4504. if (InitList->isStringLiteralInit())
  4505. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  4506. }
  4507. return checkFormatStringExpr(S, Init, Args,
  4508. HasVAListArg, format_idx,
  4509. firstDataArg, Type, CallType,
  4510. /*InFunctionCall*/ false, CheckedVarArgs,
  4511. UncoveredArg, Offset);
  4512. }
  4513. }
  4514. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  4515. // special check to see if the format string is a function parameter
  4516. // of the function calling the printf function. If the function
  4517. // has an attribute indicating it is a printf-like function, then we
  4518. // should suppress warnings concerning non-literals being used in a call
  4519. // to a vprintf function. For example:
  4520. //
  4521. // void
  4522. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  4523. // va_list ap;
  4524. // va_start(ap, fmt);
  4525. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  4526. // ...
  4527. // }
  4528. if (HasVAListArg) {
  4529. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  4530. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  4531. int PVIndex = PV->getFunctionScopeIndex() + 1;
  4532. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  4533. // adjust for implicit parameter
  4534. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  4535. if (MD->isInstance())
  4536. ++PVIndex;
  4537. // We also check if the formats are compatible.
  4538. // We can't pass a 'scanf' string to a 'printf' function.
  4539. if (PVIndex == PVFormat->getFormatIdx() &&
  4540. Type == S.GetFormatStringType(PVFormat))
  4541. return SLCT_UncheckedLiteral;
  4542. }
  4543. }
  4544. }
  4545. }
  4546. }
  4547. return SLCT_NotALiteral;
  4548. }
  4549. case Stmt::CallExprClass:
  4550. case Stmt::CXXMemberCallExprClass: {
  4551. const CallExpr *CE = cast<CallExpr>(E);
  4552. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  4553. if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
  4554. const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
  4555. return checkFormatStringExpr(S, Arg, Args,
  4556. HasVAListArg, format_idx, firstDataArg,
  4557. Type, CallType, InFunctionCall,
  4558. CheckedVarArgs, UncoveredArg, Offset);
  4559. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  4560. unsigned BuiltinID = FD->getBuiltinID();
  4561. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  4562. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  4563. const Expr *Arg = CE->getArg(0);
  4564. return checkFormatStringExpr(S, Arg, Args,
  4565. HasVAListArg, format_idx,
  4566. firstDataArg, Type, CallType,
  4567. InFunctionCall, CheckedVarArgs,
  4568. UncoveredArg, Offset);
  4569. }
  4570. }
  4571. }
  4572. return SLCT_NotALiteral;
  4573. }
  4574. case Stmt::ObjCMessageExprClass: {
  4575. const auto *ME = cast<ObjCMessageExpr>(E);
  4576. if (const auto *ND = ME->getMethodDecl()) {
  4577. if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
  4578. const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
  4579. return checkFormatStringExpr(
  4580. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  4581. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  4582. }
  4583. }
  4584. return SLCT_NotALiteral;
  4585. }
  4586. case Stmt::ObjCStringLiteralClass:
  4587. case Stmt::StringLiteralClass: {
  4588. const StringLiteral *StrE = nullptr;
  4589. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  4590. StrE = ObjCFExpr->getString();
  4591. else
  4592. StrE = cast<StringLiteral>(E);
  4593. if (StrE) {
  4594. if (Offset.isNegative() || Offset > StrE->getLength()) {
  4595. // TODO: It would be better to have an explicit warning for out of
  4596. // bounds literals.
  4597. return SLCT_NotALiteral;
  4598. }
  4599. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  4600. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  4601. firstDataArg, Type, InFunctionCall, CallType,
  4602. CheckedVarArgs, UncoveredArg);
  4603. return SLCT_CheckedLiteral;
  4604. }
  4605. return SLCT_NotALiteral;
  4606. }
  4607. case Stmt::BinaryOperatorClass: {
  4608. llvm::APSInt LResult;
  4609. llvm::APSInt RResult;
  4610. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  4611. // A string literal + an int offset is still a string literal.
  4612. if (BinOp->isAdditiveOp()) {
  4613. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
  4614. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
  4615. if (LIsInt != RIsInt) {
  4616. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  4617. if (LIsInt) {
  4618. if (BinOpKind == BO_Add) {
  4619. sumOffsets(Offset, LResult, BinOpKind, RIsInt);
  4620. E = BinOp->getRHS();
  4621. goto tryAgain;
  4622. }
  4623. } else {
  4624. sumOffsets(Offset, RResult, BinOpKind, RIsInt);
  4625. E = BinOp->getLHS();
  4626. goto tryAgain;
  4627. }
  4628. }
  4629. }
  4630. return SLCT_NotALiteral;
  4631. }
  4632. case Stmt::UnaryOperatorClass: {
  4633. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  4634. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  4635. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  4636. llvm::APSInt IndexResult;
  4637. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
  4638. sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
  4639. E = ASE->getBase();
  4640. goto tryAgain;
  4641. }
  4642. }
  4643. return SLCT_NotALiteral;
  4644. }
  4645. default:
  4646. return SLCT_NotALiteral;
  4647. }
  4648. }
  4649. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  4650. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  4651. .Case("scanf", FST_Scanf)
  4652. .Cases("printf", "printf0", FST_Printf)
  4653. .Cases("NSString", "CFString", FST_NSString)
  4654. .Case("strftime", FST_Strftime)
  4655. .Case("strfmon", FST_Strfmon)
  4656. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  4657. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  4658. .Case("os_trace", FST_OSLog)
  4659. .Case("os_log", FST_OSLog)
  4660. .Default(FST_Unknown);
  4661. }
  4662. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  4663. /// functions) for correct use of format strings.
  4664. /// Returns true if a format string has been fully checked.
  4665. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  4666. ArrayRef<const Expr *> Args,
  4667. bool IsCXXMember,
  4668. VariadicCallType CallType,
  4669. SourceLocation Loc, SourceRange Range,
  4670. llvm::SmallBitVector &CheckedVarArgs) {
  4671. FormatStringInfo FSI;
  4672. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  4673. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  4674. FSI.FirstDataArg, GetFormatStringType(Format),
  4675. CallType, Loc, Range, CheckedVarArgs);
  4676. return false;
  4677. }
  4678. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  4679. bool HasVAListArg, unsigned format_idx,
  4680. unsigned firstDataArg, FormatStringType Type,
  4681. VariadicCallType CallType,
  4682. SourceLocation Loc, SourceRange Range,
  4683. llvm::SmallBitVector &CheckedVarArgs) {
  4684. // CHECK: printf/scanf-like function is called with no format string.
  4685. if (format_idx >= Args.size()) {
  4686. Diag(Loc, diag::warn_missing_format_string) << Range;
  4687. return false;
  4688. }
  4689. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  4690. // CHECK: format string is not a string literal.
  4691. //
  4692. // Dynamically generated format strings are difficult to
  4693. // automatically vet at compile time. Requiring that format strings
  4694. // are string literals: (1) permits the checking of format strings by
  4695. // the compiler and thereby (2) can practically remove the source of
  4696. // many format string exploits.
  4697. // Format string can be either ObjC string (e.g. @"%d") or
  4698. // C string (e.g. "%d")
  4699. // ObjC string uses the same format specifiers as C string, so we can use
  4700. // the same format string checking logic for both ObjC and C strings.
  4701. UncoveredArgHandler UncoveredArg;
  4702. StringLiteralCheckType CT =
  4703. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  4704. format_idx, firstDataArg, Type, CallType,
  4705. /*IsFunctionCall*/ true, CheckedVarArgs,
  4706. UncoveredArg,
  4707. /*no string offset*/ llvm::APSInt(64, false) = 0);
  4708. // Generate a diagnostic where an uncovered argument is detected.
  4709. if (UncoveredArg.hasUncoveredArg()) {
  4710. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  4711. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  4712. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  4713. }
  4714. if (CT != SLCT_NotALiteral)
  4715. // Literal format string found, check done!
  4716. return CT == SLCT_CheckedLiteral;
  4717. // Strftime is particular as it always uses a single 'time' argument,
  4718. // so it is safe to pass a non-literal string.
  4719. if (Type == FST_Strftime)
  4720. return false;
  4721. // Do not emit diag when the string param is a macro expansion and the
  4722. // format is either NSString or CFString. This is a hack to prevent
  4723. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  4724. // which are usually used in place of NS and CF string literals.
  4725. SourceLocation FormatLoc = Args[format_idx]->getLocStart();
  4726. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  4727. return false;
  4728. // If there are no arguments specified, warn with -Wformat-security, otherwise
  4729. // warn only with -Wformat-nonliteral.
  4730. if (Args.size() == firstDataArg) {
  4731. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  4732. << OrigFormatExpr->getSourceRange();
  4733. switch (Type) {
  4734. default:
  4735. break;
  4736. case FST_Kprintf:
  4737. case FST_FreeBSDKPrintf:
  4738. case FST_Printf:
  4739. Diag(FormatLoc, diag::note_format_security_fixit)
  4740. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  4741. break;
  4742. case FST_NSString:
  4743. Diag(FormatLoc, diag::note_format_security_fixit)
  4744. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  4745. break;
  4746. }
  4747. } else {
  4748. Diag(FormatLoc, diag::warn_format_nonliteral)
  4749. << OrigFormatExpr->getSourceRange();
  4750. }
  4751. return false;
  4752. }
  4753. namespace {
  4754. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  4755. protected:
  4756. Sema &S;
  4757. const FormatStringLiteral *FExpr;
  4758. const Expr *OrigFormatExpr;
  4759. const Sema::FormatStringType FSType;
  4760. const unsigned FirstDataArg;
  4761. const unsigned NumDataArgs;
  4762. const char *Beg; // Start of format string.
  4763. const bool HasVAListArg;
  4764. ArrayRef<const Expr *> Args;
  4765. unsigned FormatIdx;
  4766. llvm::SmallBitVector CoveredArgs;
  4767. bool usesPositionalArgs = false;
  4768. bool atFirstArg = true;
  4769. bool inFunctionCall;
  4770. Sema::VariadicCallType CallType;
  4771. llvm::SmallBitVector &CheckedVarArgs;
  4772. UncoveredArgHandler &UncoveredArg;
  4773. public:
  4774. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  4775. const Expr *origFormatExpr,
  4776. const Sema::FormatStringType type, unsigned firstDataArg,
  4777. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  4778. ArrayRef<const Expr *> Args, unsigned formatIdx,
  4779. bool inFunctionCall, Sema::VariadicCallType callType,
  4780. llvm::SmallBitVector &CheckedVarArgs,
  4781. UncoveredArgHandler &UncoveredArg)
  4782. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  4783. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  4784. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  4785. inFunctionCall(inFunctionCall), CallType(callType),
  4786. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  4787. CoveredArgs.resize(numDataArgs);
  4788. CoveredArgs.reset();
  4789. }
  4790. void DoneProcessing();
  4791. void HandleIncompleteSpecifier(const char *startSpecifier,
  4792. unsigned specifierLen) override;
  4793. void HandleInvalidLengthModifier(
  4794. const analyze_format_string::FormatSpecifier &FS,
  4795. const analyze_format_string::ConversionSpecifier &CS,
  4796. const char *startSpecifier, unsigned specifierLen,
  4797. unsigned DiagID);
  4798. void HandleNonStandardLengthModifier(
  4799. const analyze_format_string::FormatSpecifier &FS,
  4800. const char *startSpecifier, unsigned specifierLen);
  4801. void HandleNonStandardConversionSpecifier(
  4802. const analyze_format_string::ConversionSpecifier &CS,
  4803. const char *startSpecifier, unsigned specifierLen);
  4804. void HandlePosition(const char *startPos, unsigned posLen) override;
  4805. void HandleInvalidPosition(const char *startSpecifier,
  4806. unsigned specifierLen,
  4807. analyze_format_string::PositionContext p) override;
  4808. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  4809. void HandleNullChar(const char *nullCharacter) override;
  4810. template <typename Range>
  4811. static void
  4812. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  4813. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  4814. bool IsStringLocation, Range StringRange,
  4815. ArrayRef<FixItHint> Fixit = None);
  4816. protected:
  4817. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  4818. const char *startSpec,
  4819. unsigned specifierLen,
  4820. const char *csStart, unsigned csLen);
  4821. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  4822. const char *startSpec,
  4823. unsigned specifierLen);
  4824. SourceRange getFormatStringRange();
  4825. CharSourceRange getSpecifierRange(const char *startSpecifier,
  4826. unsigned specifierLen);
  4827. SourceLocation getLocationOfByte(const char *x);
  4828. const Expr *getDataArg(unsigned i) const;
  4829. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  4830. const analyze_format_string::ConversionSpecifier &CS,
  4831. const char *startSpecifier, unsigned specifierLen,
  4832. unsigned argIndex);
  4833. template <typename Range>
  4834. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  4835. bool IsStringLocation, Range StringRange,
  4836. ArrayRef<FixItHint> Fixit = None);
  4837. };
  4838. } // namespace
  4839. SourceRange CheckFormatHandler::getFormatStringRange() {
  4840. return OrigFormatExpr->getSourceRange();
  4841. }
  4842. CharSourceRange CheckFormatHandler::
  4843. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  4844. SourceLocation Start = getLocationOfByte(startSpecifier);
  4845. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  4846. // Advance the end SourceLocation by one due to half-open ranges.
  4847. End = End.getLocWithOffset(1);
  4848. return CharSourceRange::getCharRange(Start, End);
  4849. }
  4850. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  4851. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  4852. S.getLangOpts(), S.Context.getTargetInfo());
  4853. }
  4854. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  4855. unsigned specifierLen){
  4856. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  4857. getLocationOfByte(startSpecifier),
  4858. /*IsStringLocation*/true,
  4859. getSpecifierRange(startSpecifier, specifierLen));
  4860. }
  4861. void CheckFormatHandler::HandleInvalidLengthModifier(
  4862. const analyze_format_string::FormatSpecifier &FS,
  4863. const analyze_format_string::ConversionSpecifier &CS,
  4864. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  4865. using namespace analyze_format_string;
  4866. const LengthModifier &LM = FS.getLengthModifier();
  4867. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  4868. // See if we know how to fix this length modifier.
  4869. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  4870. if (FixedLM) {
  4871. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  4872. getLocationOfByte(LM.getStart()),
  4873. /*IsStringLocation*/true,
  4874. getSpecifierRange(startSpecifier, specifierLen));
  4875. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  4876. << FixedLM->toString()
  4877. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  4878. } else {
  4879. FixItHint Hint;
  4880. if (DiagID == diag::warn_format_nonsensical_length)
  4881. Hint = FixItHint::CreateRemoval(LMRange);
  4882. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  4883. getLocationOfByte(LM.getStart()),
  4884. /*IsStringLocation*/true,
  4885. getSpecifierRange(startSpecifier, specifierLen),
  4886. Hint);
  4887. }
  4888. }
  4889. void CheckFormatHandler::HandleNonStandardLengthModifier(
  4890. const analyze_format_string::FormatSpecifier &FS,
  4891. const char *startSpecifier, unsigned specifierLen) {
  4892. using namespace analyze_format_string;
  4893. const LengthModifier &LM = FS.getLengthModifier();
  4894. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  4895. // See if we know how to fix this length modifier.
  4896. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  4897. if (FixedLM) {
  4898. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4899. << LM.toString() << 0,
  4900. getLocationOfByte(LM.getStart()),
  4901. /*IsStringLocation*/true,
  4902. getSpecifierRange(startSpecifier, specifierLen));
  4903. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  4904. << FixedLM->toString()
  4905. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  4906. } else {
  4907. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4908. << LM.toString() << 0,
  4909. getLocationOfByte(LM.getStart()),
  4910. /*IsStringLocation*/true,
  4911. getSpecifierRange(startSpecifier, specifierLen));
  4912. }
  4913. }
  4914. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  4915. const analyze_format_string::ConversionSpecifier &CS,
  4916. const char *startSpecifier, unsigned specifierLen) {
  4917. using namespace analyze_format_string;
  4918. // See if we know how to fix this conversion specifier.
  4919. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  4920. if (FixedCS) {
  4921. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4922. << CS.toString() << /*conversion specifier*/1,
  4923. getLocationOfByte(CS.getStart()),
  4924. /*IsStringLocation*/true,
  4925. getSpecifierRange(startSpecifier, specifierLen));
  4926. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  4927. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  4928. << FixedCS->toString()
  4929. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  4930. } else {
  4931. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4932. << CS.toString() << /*conversion specifier*/1,
  4933. getLocationOfByte(CS.getStart()),
  4934. /*IsStringLocation*/true,
  4935. getSpecifierRange(startSpecifier, specifierLen));
  4936. }
  4937. }
  4938. void CheckFormatHandler::HandlePosition(const char *startPos,
  4939. unsigned posLen) {
  4940. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  4941. getLocationOfByte(startPos),
  4942. /*IsStringLocation*/true,
  4943. getSpecifierRange(startPos, posLen));
  4944. }
  4945. void
  4946. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  4947. analyze_format_string::PositionContext p) {
  4948. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  4949. << (unsigned) p,
  4950. getLocationOfByte(startPos), /*IsStringLocation*/true,
  4951. getSpecifierRange(startPos, posLen));
  4952. }
  4953. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  4954. unsigned posLen) {
  4955. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  4956. getLocationOfByte(startPos),
  4957. /*IsStringLocation*/true,
  4958. getSpecifierRange(startPos, posLen));
  4959. }
  4960. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  4961. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  4962. // The presence of a null character is likely an error.
  4963. EmitFormatDiagnostic(
  4964. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  4965. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  4966. getFormatStringRange());
  4967. }
  4968. }
  4969. // Note that this may return NULL if there was an error parsing or building
  4970. // one of the argument expressions.
  4971. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  4972. return Args[FirstDataArg + i];
  4973. }
  4974. void CheckFormatHandler::DoneProcessing() {
  4975. // Does the number of data arguments exceed the number of
  4976. // format conversions in the format string?
  4977. if (!HasVAListArg) {
  4978. // Find any arguments that weren't covered.
  4979. CoveredArgs.flip();
  4980. signed notCoveredArg = CoveredArgs.find_first();
  4981. if (notCoveredArg >= 0) {
  4982. assert((unsigned)notCoveredArg < NumDataArgs);
  4983. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  4984. } else {
  4985. UncoveredArg.setAllCovered();
  4986. }
  4987. }
  4988. }
  4989. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  4990. const Expr *ArgExpr) {
  4991. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  4992. "Invalid state");
  4993. if (!ArgExpr)
  4994. return;
  4995. SourceLocation Loc = ArgExpr->getLocStart();
  4996. if (S.getSourceManager().isInSystemMacro(Loc))
  4997. return;
  4998. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  4999. for (auto E : DiagnosticExprs)
  5000. PDiag << E->getSourceRange();
  5001. CheckFormatHandler::EmitFormatDiagnostic(
  5002. S, IsFunctionCall, DiagnosticExprs[0],
  5003. PDiag, Loc, /*IsStringLocation*/false,
  5004. DiagnosticExprs[0]->getSourceRange());
  5005. }
  5006. bool
  5007. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  5008. SourceLocation Loc,
  5009. const char *startSpec,
  5010. unsigned specifierLen,
  5011. const char *csStart,
  5012. unsigned csLen) {
  5013. bool keepGoing = true;
  5014. if (argIndex < NumDataArgs) {
  5015. // Consider the argument coverered, even though the specifier doesn't
  5016. // make sense.
  5017. CoveredArgs.set(argIndex);
  5018. }
  5019. else {
  5020. // If argIndex exceeds the number of data arguments we
  5021. // don't issue a warning because that is just a cascade of warnings (and
  5022. // they may have intended '%%' anyway). We don't want to continue processing
  5023. // the format string after this point, however, as we will like just get
  5024. // gibberish when trying to match arguments.
  5025. keepGoing = false;
  5026. }
  5027. StringRef Specifier(csStart, csLen);
  5028. // If the specifier in non-printable, it could be the first byte of a UTF-8
  5029. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  5030. // hex value.
  5031. std::string CodePointStr;
  5032. if (!llvm::sys::locale::isPrint(*csStart)) {
  5033. llvm::UTF32 CodePoint;
  5034. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  5035. const llvm::UTF8 *E =
  5036. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  5037. llvm::ConversionResult Result =
  5038. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  5039. if (Result != llvm::conversionOK) {
  5040. unsigned char FirstChar = *csStart;
  5041. CodePoint = (llvm::UTF32)FirstChar;
  5042. }
  5043. llvm::raw_string_ostream OS(CodePointStr);
  5044. if (CodePoint < 256)
  5045. OS << "\\x" << llvm::format("%02x", CodePoint);
  5046. else if (CodePoint <= 0xFFFF)
  5047. OS << "\\u" << llvm::format("%04x", CodePoint);
  5048. else
  5049. OS << "\\U" << llvm::format("%08x", CodePoint);
  5050. OS.flush();
  5051. Specifier = CodePointStr;
  5052. }
  5053. EmitFormatDiagnostic(
  5054. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  5055. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  5056. return keepGoing;
  5057. }
  5058. void
  5059. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  5060. const char *startSpec,
  5061. unsigned specifierLen) {
  5062. EmitFormatDiagnostic(
  5063. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  5064. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  5065. }
  5066. bool
  5067. CheckFormatHandler::CheckNumArgs(
  5068. const analyze_format_string::FormatSpecifier &FS,
  5069. const analyze_format_string::ConversionSpecifier &CS,
  5070. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  5071. if (argIndex >= NumDataArgs) {
  5072. PartialDiagnostic PDiag = FS.usesPositionalArg()
  5073. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  5074. << (argIndex+1) << NumDataArgs)
  5075. : S.PDiag(diag::warn_printf_insufficient_data_args);
  5076. EmitFormatDiagnostic(
  5077. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  5078. getSpecifierRange(startSpecifier, specifierLen));
  5079. // Since more arguments than conversion tokens are given, by extension
  5080. // all arguments are covered, so mark this as so.
  5081. UncoveredArg.setAllCovered();
  5082. return false;
  5083. }
  5084. return true;
  5085. }
  5086. template<typename Range>
  5087. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  5088. SourceLocation Loc,
  5089. bool IsStringLocation,
  5090. Range StringRange,
  5091. ArrayRef<FixItHint> FixIt) {
  5092. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  5093. Loc, IsStringLocation, StringRange, FixIt);
  5094. }
  5095. /// \brief If the format string is not within the function call, emit a note
  5096. /// so that the function call and string are in diagnostic messages.
  5097. ///
  5098. /// \param InFunctionCall if true, the format string is within the function
  5099. /// call and only one diagnostic message will be produced. Otherwise, an
  5100. /// extra note will be emitted pointing to location of the format string.
  5101. ///
  5102. /// \param ArgumentExpr the expression that is passed as the format string
  5103. /// argument in the function call. Used for getting locations when two
  5104. /// diagnostics are emitted.
  5105. ///
  5106. /// \param PDiag the callee should already have provided any strings for the
  5107. /// diagnostic message. This function only adds locations and fixits
  5108. /// to diagnostics.
  5109. ///
  5110. /// \param Loc primary location for diagnostic. If two diagnostics are
  5111. /// required, one will be at Loc and a new SourceLocation will be created for
  5112. /// the other one.
  5113. ///
  5114. /// \param IsStringLocation if true, Loc points to the format string should be
  5115. /// used for the note. Otherwise, Loc points to the argument list and will
  5116. /// be used with PDiag.
  5117. ///
  5118. /// \param StringRange some or all of the string to highlight. This is
  5119. /// templated so it can accept either a CharSourceRange or a SourceRange.
  5120. ///
  5121. /// \param FixIt optional fix it hint for the format string.
  5122. template <typename Range>
  5123. void CheckFormatHandler::EmitFormatDiagnostic(
  5124. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  5125. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  5126. Range StringRange, ArrayRef<FixItHint> FixIt) {
  5127. if (InFunctionCall) {
  5128. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  5129. D << StringRange;
  5130. D << FixIt;
  5131. } else {
  5132. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  5133. << ArgumentExpr->getSourceRange();
  5134. const Sema::SemaDiagnosticBuilder &Note =
  5135. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  5136. diag::note_format_string_defined);
  5137. Note << StringRange;
  5138. Note << FixIt;
  5139. }
  5140. }
  5141. //===--- CHECK: Printf format string checking ------------------------------===//
  5142. namespace {
  5143. class CheckPrintfHandler : public CheckFormatHandler {
  5144. public:
  5145. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  5146. const Expr *origFormatExpr,
  5147. const Sema::FormatStringType type, unsigned firstDataArg,
  5148. unsigned numDataArgs, bool isObjC, const char *beg,
  5149. bool hasVAListArg, ArrayRef<const Expr *> Args,
  5150. unsigned formatIdx, bool inFunctionCall,
  5151. Sema::VariadicCallType CallType,
  5152. llvm::SmallBitVector &CheckedVarArgs,
  5153. UncoveredArgHandler &UncoveredArg)
  5154. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  5155. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  5156. inFunctionCall, CallType, CheckedVarArgs,
  5157. UncoveredArg) {}
  5158. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  5159. /// Returns true if '%@' specifiers are allowed in the format string.
  5160. bool allowsObjCArg() const {
  5161. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  5162. FSType == Sema::FST_OSTrace;
  5163. }
  5164. bool HandleInvalidPrintfConversionSpecifier(
  5165. const analyze_printf::PrintfSpecifier &FS,
  5166. const char *startSpecifier,
  5167. unsigned specifierLen) override;
  5168. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  5169. const char *startSpecifier,
  5170. unsigned specifierLen) override;
  5171. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  5172. const char *StartSpecifier,
  5173. unsigned SpecifierLen,
  5174. const Expr *E);
  5175. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  5176. const char *startSpecifier, unsigned specifierLen);
  5177. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  5178. const analyze_printf::OptionalAmount &Amt,
  5179. unsigned type,
  5180. const char *startSpecifier, unsigned specifierLen);
  5181. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  5182. const analyze_printf::OptionalFlag &flag,
  5183. const char *startSpecifier, unsigned specifierLen);
  5184. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  5185. const analyze_printf::OptionalFlag &ignoredFlag,
  5186. const analyze_printf::OptionalFlag &flag,
  5187. const char *startSpecifier, unsigned specifierLen);
  5188. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  5189. const Expr *E);
  5190. void HandleEmptyObjCModifierFlag(const char *startFlag,
  5191. unsigned flagLen) override;
  5192. void HandleInvalidObjCModifierFlag(const char *startFlag,
  5193. unsigned flagLen) override;
  5194. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  5195. const char *flagsEnd,
  5196. const char *conversionPosition)
  5197. override;
  5198. };
  5199. } // namespace
  5200. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  5201. const analyze_printf::PrintfSpecifier &FS,
  5202. const char *startSpecifier,
  5203. unsigned specifierLen) {
  5204. const analyze_printf::PrintfConversionSpecifier &CS =
  5205. FS.getConversionSpecifier();
  5206. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  5207. getLocationOfByte(CS.getStart()),
  5208. startSpecifier, specifierLen,
  5209. CS.getStart(), CS.getLength());
  5210. }
  5211. bool CheckPrintfHandler::HandleAmount(
  5212. const analyze_format_string::OptionalAmount &Amt,
  5213. unsigned k, const char *startSpecifier,
  5214. unsigned specifierLen) {
  5215. if (Amt.hasDataArgument()) {
  5216. if (!HasVAListArg) {
  5217. unsigned argIndex = Amt.getArgIndex();
  5218. if (argIndex >= NumDataArgs) {
  5219. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  5220. << k,
  5221. getLocationOfByte(Amt.getStart()),
  5222. /*IsStringLocation*/true,
  5223. getSpecifierRange(startSpecifier, specifierLen));
  5224. // Don't do any more checking. We will just emit
  5225. // spurious errors.
  5226. return false;
  5227. }
  5228. // Type check the data argument. It should be an 'int'.
  5229. // Although not in conformance with C99, we also allow the argument to be
  5230. // an 'unsigned int' as that is a reasonably safe case. GCC also
  5231. // doesn't emit a warning for that case.
  5232. CoveredArgs.set(argIndex);
  5233. const Expr *Arg = getDataArg(argIndex);
  5234. if (!Arg)
  5235. return false;
  5236. QualType T = Arg->getType();
  5237. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  5238. assert(AT.isValid());
  5239. if (!AT.matchesType(S.Context, T)) {
  5240. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  5241. << k << AT.getRepresentativeTypeName(S.Context)
  5242. << T << Arg->getSourceRange(),
  5243. getLocationOfByte(Amt.getStart()),
  5244. /*IsStringLocation*/true,
  5245. getSpecifierRange(startSpecifier, specifierLen));
  5246. // Don't do any more checking. We will just emit
  5247. // spurious errors.
  5248. return false;
  5249. }
  5250. }
  5251. }
  5252. return true;
  5253. }
  5254. void CheckPrintfHandler::HandleInvalidAmount(
  5255. const analyze_printf::PrintfSpecifier &FS,
  5256. const analyze_printf::OptionalAmount &Amt,
  5257. unsigned type,
  5258. const char *startSpecifier,
  5259. unsigned specifierLen) {
  5260. const analyze_printf::PrintfConversionSpecifier &CS =
  5261. FS.getConversionSpecifier();
  5262. FixItHint fixit =
  5263. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  5264. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  5265. Amt.getConstantLength()))
  5266. : FixItHint();
  5267. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  5268. << type << CS.toString(),
  5269. getLocationOfByte(Amt.getStart()),
  5270. /*IsStringLocation*/true,
  5271. getSpecifierRange(startSpecifier, specifierLen),
  5272. fixit);
  5273. }
  5274. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  5275. const analyze_printf::OptionalFlag &flag,
  5276. const char *startSpecifier,
  5277. unsigned specifierLen) {
  5278. // Warn about pointless flag with a fixit removal.
  5279. const analyze_printf::PrintfConversionSpecifier &CS =
  5280. FS.getConversionSpecifier();
  5281. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  5282. << flag.toString() << CS.toString(),
  5283. getLocationOfByte(flag.getPosition()),
  5284. /*IsStringLocation*/true,
  5285. getSpecifierRange(startSpecifier, specifierLen),
  5286. FixItHint::CreateRemoval(
  5287. getSpecifierRange(flag.getPosition(), 1)));
  5288. }
  5289. void CheckPrintfHandler::HandleIgnoredFlag(
  5290. const analyze_printf::PrintfSpecifier &FS,
  5291. const analyze_printf::OptionalFlag &ignoredFlag,
  5292. const analyze_printf::OptionalFlag &flag,
  5293. const char *startSpecifier,
  5294. unsigned specifierLen) {
  5295. // Warn about ignored flag with a fixit removal.
  5296. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  5297. << ignoredFlag.toString() << flag.toString(),
  5298. getLocationOfByte(ignoredFlag.getPosition()),
  5299. /*IsStringLocation*/true,
  5300. getSpecifierRange(startSpecifier, specifierLen),
  5301. FixItHint::CreateRemoval(
  5302. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  5303. }
  5304. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  5305. unsigned flagLen) {
  5306. // Warn about an empty flag.
  5307. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  5308. getLocationOfByte(startFlag),
  5309. /*IsStringLocation*/true,
  5310. getSpecifierRange(startFlag, flagLen));
  5311. }
  5312. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  5313. unsigned flagLen) {
  5314. // Warn about an invalid flag.
  5315. auto Range = getSpecifierRange(startFlag, flagLen);
  5316. StringRef flag(startFlag, flagLen);
  5317. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  5318. getLocationOfByte(startFlag),
  5319. /*IsStringLocation*/true,
  5320. Range, FixItHint::CreateRemoval(Range));
  5321. }
  5322. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  5323. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  5324. // Warn about using '[...]' without a '@' conversion.
  5325. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  5326. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  5327. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  5328. getLocationOfByte(conversionPosition),
  5329. /*IsStringLocation*/true,
  5330. Range, FixItHint::CreateRemoval(Range));
  5331. }
  5332. // Determines if the specified is a C++ class or struct containing
  5333. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  5334. // "c_str()").
  5335. template<typename MemberKind>
  5336. static llvm::SmallPtrSet<MemberKind*, 1>
  5337. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  5338. const RecordType *RT = Ty->getAs<RecordType>();
  5339. llvm::SmallPtrSet<MemberKind*, 1> Results;
  5340. if (!RT)
  5341. return Results;
  5342. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  5343. if (!RD || !RD->getDefinition())
  5344. return Results;
  5345. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  5346. Sema::LookupMemberName);
  5347. R.suppressDiagnostics();
  5348. // We just need to include all members of the right kind turned up by the
  5349. // filter, at this point.
  5350. if (S.LookupQualifiedName(R, RT->getDecl()))
  5351. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  5352. NamedDecl *decl = (*I)->getUnderlyingDecl();
  5353. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  5354. Results.insert(FK);
  5355. }
  5356. return Results;
  5357. }
  5358. /// Check if we could call '.c_str()' on an object.
  5359. ///
  5360. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  5361. /// allow the call, or if it would be ambiguous).
  5362. bool Sema::hasCStrMethod(const Expr *E) {
  5363. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  5364. MethodSet Results =
  5365. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  5366. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  5367. MI != ME; ++MI)
  5368. if ((*MI)->getMinRequiredArguments() == 0)
  5369. return true;
  5370. return false;
  5371. }
  5372. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  5373. // better diagnostic if so. AT is assumed to be valid.
  5374. // Returns true when a c_str() conversion method is found.
  5375. bool CheckPrintfHandler::checkForCStrMembers(
  5376. const analyze_printf::ArgType &AT, const Expr *E) {
  5377. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  5378. MethodSet Results =
  5379. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  5380. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  5381. MI != ME; ++MI) {
  5382. const CXXMethodDecl *Method = *MI;
  5383. if (Method->getMinRequiredArguments() == 0 &&
  5384. AT.matchesType(S.Context, Method->getReturnType())) {
  5385. // FIXME: Suggest parens if the expression needs them.
  5386. SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
  5387. S.Diag(E->getLocStart(), diag::note_printf_c_str)
  5388. << "c_str()"
  5389. << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  5390. return true;
  5391. }
  5392. }
  5393. return false;
  5394. }
  5395. bool
  5396. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  5397. &FS,
  5398. const char *startSpecifier,
  5399. unsigned specifierLen) {
  5400. using namespace analyze_format_string;
  5401. using namespace analyze_printf;
  5402. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  5403. if (FS.consumesDataArgument()) {
  5404. if (atFirstArg) {
  5405. atFirstArg = false;
  5406. usesPositionalArgs = FS.usesPositionalArg();
  5407. }
  5408. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  5409. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  5410. startSpecifier, specifierLen);
  5411. return false;
  5412. }
  5413. }
  5414. // First check if the field width, precision, and conversion specifier
  5415. // have matching data arguments.
  5416. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  5417. startSpecifier, specifierLen)) {
  5418. return false;
  5419. }
  5420. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  5421. startSpecifier, specifierLen)) {
  5422. return false;
  5423. }
  5424. if (!CS.consumesDataArgument()) {
  5425. // FIXME: Technically specifying a precision or field width here
  5426. // makes no sense. Worth issuing a warning at some point.
  5427. return true;
  5428. }
  5429. // Consume the argument.
  5430. unsigned argIndex = FS.getArgIndex();
  5431. if (argIndex < NumDataArgs) {
  5432. // The check to see if the argIndex is valid will come later.
  5433. // We set the bit here because we may exit early from this
  5434. // function if we encounter some other error.
  5435. CoveredArgs.set(argIndex);
  5436. }
  5437. // FreeBSD kernel extensions.
  5438. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  5439. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  5440. // We need at least two arguments.
  5441. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  5442. return false;
  5443. // Claim the second argument.
  5444. CoveredArgs.set(argIndex + 1);
  5445. // Type check the first argument (int for %b, pointer for %D)
  5446. const Expr *Ex = getDataArg(argIndex);
  5447. const analyze_printf::ArgType &AT =
  5448. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  5449. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  5450. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  5451. EmitFormatDiagnostic(
  5452. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  5453. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  5454. << false << Ex->getSourceRange(),
  5455. Ex->getLocStart(), /*IsStringLocation*/false,
  5456. getSpecifierRange(startSpecifier, specifierLen));
  5457. // Type check the second argument (char * for both %b and %D)
  5458. Ex = getDataArg(argIndex + 1);
  5459. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  5460. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  5461. EmitFormatDiagnostic(
  5462. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  5463. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  5464. << false << Ex->getSourceRange(),
  5465. Ex->getLocStart(), /*IsStringLocation*/false,
  5466. getSpecifierRange(startSpecifier, specifierLen));
  5467. return true;
  5468. }
  5469. // Check for using an Objective-C specific conversion specifier
  5470. // in a non-ObjC literal.
  5471. if (!allowsObjCArg() && CS.isObjCArg()) {
  5472. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  5473. specifierLen);
  5474. }
  5475. // %P can only be used with os_log.
  5476. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  5477. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  5478. specifierLen);
  5479. }
  5480. // %n is not allowed with os_log.
  5481. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  5482. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  5483. getLocationOfByte(CS.getStart()),
  5484. /*IsStringLocation*/ false,
  5485. getSpecifierRange(startSpecifier, specifierLen));
  5486. return true;
  5487. }
  5488. // Only scalars are allowed for os_trace.
  5489. if (FSType == Sema::FST_OSTrace &&
  5490. (CS.getKind() == ConversionSpecifier::PArg ||
  5491. CS.getKind() == ConversionSpecifier::sArg ||
  5492. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  5493. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  5494. specifierLen);
  5495. }
  5496. // Check for use of public/private annotation outside of os_log().
  5497. if (FSType != Sema::FST_OSLog) {
  5498. if (FS.isPublic().isSet()) {
  5499. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  5500. << "public",
  5501. getLocationOfByte(FS.isPublic().getPosition()),
  5502. /*IsStringLocation*/ false,
  5503. getSpecifierRange(startSpecifier, specifierLen));
  5504. }
  5505. if (FS.isPrivate().isSet()) {
  5506. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  5507. << "private",
  5508. getLocationOfByte(FS.isPrivate().getPosition()),
  5509. /*IsStringLocation*/ false,
  5510. getSpecifierRange(startSpecifier, specifierLen));
  5511. }
  5512. }
  5513. // Check for invalid use of field width
  5514. if (!FS.hasValidFieldWidth()) {
  5515. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  5516. startSpecifier, specifierLen);
  5517. }
  5518. // Check for invalid use of precision
  5519. if (!FS.hasValidPrecision()) {
  5520. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  5521. startSpecifier, specifierLen);
  5522. }
  5523. // Precision is mandatory for %P specifier.
  5524. if (CS.getKind() == ConversionSpecifier::PArg &&
  5525. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  5526. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  5527. getLocationOfByte(startSpecifier),
  5528. /*IsStringLocation*/ false,
  5529. getSpecifierRange(startSpecifier, specifierLen));
  5530. }
  5531. // Check each flag does not conflict with any other component.
  5532. if (!FS.hasValidThousandsGroupingPrefix())
  5533. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  5534. if (!FS.hasValidLeadingZeros())
  5535. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  5536. if (!FS.hasValidPlusPrefix())
  5537. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  5538. if (!FS.hasValidSpacePrefix())
  5539. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  5540. if (!FS.hasValidAlternativeForm())
  5541. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  5542. if (!FS.hasValidLeftJustified())
  5543. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  5544. // Check that flags are not ignored by another flag
  5545. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  5546. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  5547. startSpecifier, specifierLen);
  5548. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  5549. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  5550. startSpecifier, specifierLen);
  5551. // Check the length modifier is valid with the given conversion specifier.
  5552. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  5553. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5554. diag::warn_format_nonsensical_length);
  5555. else if (!FS.hasStandardLengthModifier())
  5556. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  5557. else if (!FS.hasStandardLengthConversionCombination())
  5558. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5559. diag::warn_format_non_standard_conversion_spec);
  5560. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  5561. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  5562. // The remaining checks depend on the data arguments.
  5563. if (HasVAListArg)
  5564. return true;
  5565. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  5566. return false;
  5567. const Expr *Arg = getDataArg(argIndex);
  5568. if (!Arg)
  5569. return true;
  5570. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  5571. }
  5572. static bool requiresParensToAddCast(const Expr *E) {
  5573. // FIXME: We should have a general way to reason about operator
  5574. // precedence and whether parens are actually needed here.
  5575. // Take care of a few common cases where they aren't.
  5576. const Expr *Inside = E->IgnoreImpCasts();
  5577. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  5578. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  5579. switch (Inside->getStmtClass()) {
  5580. case Stmt::ArraySubscriptExprClass:
  5581. case Stmt::CallExprClass:
  5582. case Stmt::CharacterLiteralClass:
  5583. case Stmt::CXXBoolLiteralExprClass:
  5584. case Stmt::DeclRefExprClass:
  5585. case Stmt::FloatingLiteralClass:
  5586. case Stmt::IntegerLiteralClass:
  5587. case Stmt::MemberExprClass:
  5588. case Stmt::ObjCArrayLiteralClass:
  5589. case Stmt::ObjCBoolLiteralExprClass:
  5590. case Stmt::ObjCBoxedExprClass:
  5591. case Stmt::ObjCDictionaryLiteralClass:
  5592. case Stmt::ObjCEncodeExprClass:
  5593. case Stmt::ObjCIvarRefExprClass:
  5594. case Stmt::ObjCMessageExprClass:
  5595. case Stmt::ObjCPropertyRefExprClass:
  5596. case Stmt::ObjCStringLiteralClass:
  5597. case Stmt::ObjCSubscriptRefExprClass:
  5598. case Stmt::ParenExprClass:
  5599. case Stmt::StringLiteralClass:
  5600. case Stmt::UnaryOperatorClass:
  5601. return false;
  5602. default:
  5603. return true;
  5604. }
  5605. }
  5606. static std::pair<QualType, StringRef>
  5607. shouldNotPrintDirectly(const ASTContext &Context,
  5608. QualType IntendedTy,
  5609. const Expr *E) {
  5610. // Use a 'while' to peel off layers of typedefs.
  5611. QualType TyTy = IntendedTy;
  5612. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  5613. StringRef Name = UserTy->getDecl()->getName();
  5614. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  5615. .Case("CFIndex", Context.getNSIntegerType())
  5616. .Case("NSInteger", Context.getNSIntegerType())
  5617. .Case("NSUInteger", Context.getNSUIntegerType())
  5618. .Case("SInt32", Context.IntTy)
  5619. .Case("UInt32", Context.UnsignedIntTy)
  5620. .Default(QualType());
  5621. if (!CastTy.isNull())
  5622. return std::make_pair(CastTy, Name);
  5623. TyTy = UserTy->desugar();
  5624. }
  5625. // Strip parens if necessary.
  5626. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  5627. return shouldNotPrintDirectly(Context,
  5628. PE->getSubExpr()->getType(),
  5629. PE->getSubExpr());
  5630. // If this is a conditional expression, then its result type is constructed
  5631. // via usual arithmetic conversions and thus there might be no necessary
  5632. // typedef sugar there. Recurse to operands to check for NSInteger &
  5633. // Co. usage condition.
  5634. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  5635. QualType TrueTy, FalseTy;
  5636. StringRef TrueName, FalseName;
  5637. std::tie(TrueTy, TrueName) =
  5638. shouldNotPrintDirectly(Context,
  5639. CO->getTrueExpr()->getType(),
  5640. CO->getTrueExpr());
  5641. std::tie(FalseTy, FalseName) =
  5642. shouldNotPrintDirectly(Context,
  5643. CO->getFalseExpr()->getType(),
  5644. CO->getFalseExpr());
  5645. if (TrueTy == FalseTy)
  5646. return std::make_pair(TrueTy, TrueName);
  5647. else if (TrueTy.isNull())
  5648. return std::make_pair(FalseTy, FalseName);
  5649. else if (FalseTy.isNull())
  5650. return std::make_pair(TrueTy, TrueName);
  5651. }
  5652. return std::make_pair(QualType(), StringRef());
  5653. }
  5654. bool
  5655. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  5656. const char *StartSpecifier,
  5657. unsigned SpecifierLen,
  5658. const Expr *E) {
  5659. using namespace analyze_format_string;
  5660. using namespace analyze_printf;
  5661. // Now type check the data expression that matches the
  5662. // format specifier.
  5663. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  5664. if (!AT.isValid())
  5665. return true;
  5666. QualType ExprTy = E->getType();
  5667. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  5668. ExprTy = TET->getUnderlyingExpr()->getType();
  5669. }
  5670. analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
  5671. if (match == analyze_printf::ArgType::Match) {
  5672. return true;
  5673. }
  5674. // Look through argument promotions for our error message's reported type.
  5675. // This includes the integral and floating promotions, but excludes array
  5676. // and function pointer decay; seeing that an argument intended to be a
  5677. // string has type 'char [6]' is probably more confusing than 'char *'.
  5678. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  5679. if (ICE->getCastKind() == CK_IntegralCast ||
  5680. ICE->getCastKind() == CK_FloatingCast) {
  5681. E = ICE->getSubExpr();
  5682. ExprTy = E->getType();
  5683. // Check if we didn't match because of an implicit cast from a 'char'
  5684. // or 'short' to an 'int'. This is done because printf is a varargs
  5685. // function.
  5686. if (ICE->getType() == S.Context.IntTy ||
  5687. ICE->getType() == S.Context.UnsignedIntTy) {
  5688. // All further checking is done on the subexpression.
  5689. if (AT.matchesType(S.Context, ExprTy))
  5690. return true;
  5691. }
  5692. }
  5693. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  5694. // Special case for 'a', which has type 'int' in C.
  5695. // Note, however, that we do /not/ want to treat multibyte constants like
  5696. // 'MooV' as characters! This form is deprecated but still exists.
  5697. if (ExprTy == S.Context.IntTy)
  5698. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  5699. ExprTy = S.Context.CharTy;
  5700. }
  5701. // Look through enums to their underlying type.
  5702. bool IsEnum = false;
  5703. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  5704. ExprTy = EnumTy->getDecl()->getIntegerType();
  5705. IsEnum = true;
  5706. }
  5707. // %C in an Objective-C context prints a unichar, not a wchar_t.
  5708. // If the argument is an integer of some kind, believe the %C and suggest
  5709. // a cast instead of changing the conversion specifier.
  5710. QualType IntendedTy = ExprTy;
  5711. if (isObjCContext() &&
  5712. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  5713. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  5714. !ExprTy->isCharType()) {
  5715. // 'unichar' is defined as a typedef of unsigned short, but we should
  5716. // prefer using the typedef if it is visible.
  5717. IntendedTy = S.Context.UnsignedShortTy;
  5718. // While we are here, check if the value is an IntegerLiteral that happens
  5719. // to be within the valid range.
  5720. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  5721. const llvm::APInt &V = IL->getValue();
  5722. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  5723. return true;
  5724. }
  5725. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
  5726. Sema::LookupOrdinaryName);
  5727. if (S.LookupName(Result, S.getCurScope())) {
  5728. NamedDecl *ND = Result.getFoundDecl();
  5729. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  5730. if (TD->getUnderlyingType() == IntendedTy)
  5731. IntendedTy = S.Context.getTypedefType(TD);
  5732. }
  5733. }
  5734. }
  5735. // Special-case some of Darwin's platform-independence types by suggesting
  5736. // casts to primitive types that are known to be large enough.
  5737. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  5738. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  5739. QualType CastTy;
  5740. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  5741. if (!CastTy.isNull()) {
  5742. IntendedTy = CastTy;
  5743. ShouldNotPrintDirectly = true;
  5744. }
  5745. }
  5746. // We may be able to offer a FixItHint if it is a supported type.
  5747. PrintfSpecifier fixedFS = FS;
  5748. bool success =
  5749. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  5750. if (success) {
  5751. // Get the fix string from the fixed format specifier
  5752. SmallString<16> buf;
  5753. llvm::raw_svector_ostream os(buf);
  5754. fixedFS.toString(os);
  5755. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  5756. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  5757. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  5758. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  5759. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  5760. }
  5761. // In this case, the specifier is wrong and should be changed to match
  5762. // the argument.
  5763. EmitFormatDiagnostic(S.PDiag(diag)
  5764. << AT.getRepresentativeTypeName(S.Context)
  5765. << IntendedTy << IsEnum << E->getSourceRange(),
  5766. E->getLocStart(),
  5767. /*IsStringLocation*/ false, SpecRange,
  5768. FixItHint::CreateReplacement(SpecRange, os.str()));
  5769. } else {
  5770. // The canonical type for formatting this value is different from the
  5771. // actual type of the expression. (This occurs, for example, with Darwin's
  5772. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  5773. // should be printed as 'long' for 64-bit compatibility.)
  5774. // Rather than emitting a normal format/argument mismatch, we want to
  5775. // add a cast to the recommended type (and correct the format string
  5776. // if necessary).
  5777. SmallString<16> CastBuf;
  5778. llvm::raw_svector_ostream CastFix(CastBuf);
  5779. CastFix << "(";
  5780. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  5781. CastFix << ")";
  5782. SmallVector<FixItHint,4> Hints;
  5783. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  5784. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  5785. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  5786. // If there's already a cast present, just replace it.
  5787. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  5788. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  5789. } else if (!requiresParensToAddCast(E)) {
  5790. // If the expression has high enough precedence,
  5791. // just write the C-style cast.
  5792. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  5793. CastFix.str()));
  5794. } else {
  5795. // Otherwise, add parens around the expression as well as the cast.
  5796. CastFix << "(";
  5797. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  5798. CastFix.str()));
  5799. SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
  5800. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  5801. }
  5802. if (ShouldNotPrintDirectly) {
  5803. // The expression has a type that should not be printed directly.
  5804. // We extract the name from the typedef because we don't want to show
  5805. // the underlying type in the diagnostic.
  5806. StringRef Name;
  5807. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  5808. Name = TypedefTy->getDecl()->getName();
  5809. else
  5810. Name = CastTyName;
  5811. EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
  5812. << Name << IntendedTy << IsEnum
  5813. << E->getSourceRange(),
  5814. E->getLocStart(), /*IsStringLocation=*/false,
  5815. SpecRange, Hints);
  5816. } else {
  5817. // In this case, the expression could be printed using a different
  5818. // specifier, but we've decided that the specifier is probably correct
  5819. // and we should cast instead. Just use the normal warning message.
  5820. EmitFormatDiagnostic(
  5821. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  5822. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  5823. << E->getSourceRange(),
  5824. E->getLocStart(), /*IsStringLocation*/false,
  5825. SpecRange, Hints);
  5826. }
  5827. }
  5828. } else {
  5829. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  5830. SpecifierLen);
  5831. // Since the warning for passing non-POD types to variadic functions
  5832. // was deferred until now, we emit a warning for non-POD
  5833. // arguments here.
  5834. switch (S.isValidVarArgType(ExprTy)) {
  5835. case Sema::VAK_Valid:
  5836. case Sema::VAK_ValidInCXX11: {
  5837. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  5838. if (match == analyze_printf::ArgType::NoMatchPedantic) {
  5839. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  5840. }
  5841. EmitFormatDiagnostic(
  5842. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  5843. << IsEnum << CSR << E->getSourceRange(),
  5844. E->getLocStart(), /*IsStringLocation*/ false, CSR);
  5845. break;
  5846. }
  5847. case Sema::VAK_Undefined:
  5848. case Sema::VAK_MSVCUndefined:
  5849. EmitFormatDiagnostic(
  5850. S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  5851. << S.getLangOpts().CPlusPlus11
  5852. << ExprTy
  5853. << CallType
  5854. << AT.getRepresentativeTypeName(S.Context)
  5855. << CSR
  5856. << E->getSourceRange(),
  5857. E->getLocStart(), /*IsStringLocation*/false, CSR);
  5858. checkForCStrMembers(AT, E);
  5859. break;
  5860. case Sema::VAK_Invalid:
  5861. if (ExprTy->isObjCObjectType())
  5862. EmitFormatDiagnostic(
  5863. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  5864. << S.getLangOpts().CPlusPlus11
  5865. << ExprTy
  5866. << CallType
  5867. << AT.getRepresentativeTypeName(S.Context)
  5868. << CSR
  5869. << E->getSourceRange(),
  5870. E->getLocStart(), /*IsStringLocation*/false, CSR);
  5871. else
  5872. // FIXME: If this is an initializer list, suggest removing the braces
  5873. // or inserting a cast to the target type.
  5874. S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
  5875. << isa<InitListExpr>(E) << ExprTy << CallType
  5876. << AT.getRepresentativeTypeName(S.Context)
  5877. << E->getSourceRange();
  5878. break;
  5879. }
  5880. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  5881. "format string specifier index out of range");
  5882. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  5883. }
  5884. return true;
  5885. }
  5886. //===--- CHECK: Scanf format string checking ------------------------------===//
  5887. namespace {
  5888. class CheckScanfHandler : public CheckFormatHandler {
  5889. public:
  5890. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  5891. const Expr *origFormatExpr, Sema::FormatStringType type,
  5892. unsigned firstDataArg, unsigned numDataArgs,
  5893. const char *beg, bool hasVAListArg,
  5894. ArrayRef<const Expr *> Args, unsigned formatIdx,
  5895. bool inFunctionCall, Sema::VariadicCallType CallType,
  5896. llvm::SmallBitVector &CheckedVarArgs,
  5897. UncoveredArgHandler &UncoveredArg)
  5898. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  5899. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  5900. inFunctionCall, CallType, CheckedVarArgs,
  5901. UncoveredArg) {}
  5902. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  5903. const char *startSpecifier,
  5904. unsigned specifierLen) override;
  5905. bool HandleInvalidScanfConversionSpecifier(
  5906. const analyze_scanf::ScanfSpecifier &FS,
  5907. const char *startSpecifier,
  5908. unsigned specifierLen) override;
  5909. void HandleIncompleteScanList(const char *start, const char *end) override;
  5910. };
  5911. } // namespace
  5912. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  5913. const char *end) {
  5914. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  5915. getLocationOfByte(end), /*IsStringLocation*/true,
  5916. getSpecifierRange(start, end - start));
  5917. }
  5918. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  5919. const analyze_scanf::ScanfSpecifier &FS,
  5920. const char *startSpecifier,
  5921. unsigned specifierLen) {
  5922. const analyze_scanf::ScanfConversionSpecifier &CS =
  5923. FS.getConversionSpecifier();
  5924. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  5925. getLocationOfByte(CS.getStart()),
  5926. startSpecifier, specifierLen,
  5927. CS.getStart(), CS.getLength());
  5928. }
  5929. bool CheckScanfHandler::HandleScanfSpecifier(
  5930. const analyze_scanf::ScanfSpecifier &FS,
  5931. const char *startSpecifier,
  5932. unsigned specifierLen) {
  5933. using namespace analyze_scanf;
  5934. using namespace analyze_format_string;
  5935. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  5936. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  5937. // be used to decide if we are using positional arguments consistently.
  5938. if (FS.consumesDataArgument()) {
  5939. if (atFirstArg) {
  5940. atFirstArg = false;
  5941. usesPositionalArgs = FS.usesPositionalArg();
  5942. }
  5943. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  5944. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  5945. startSpecifier, specifierLen);
  5946. return false;
  5947. }
  5948. }
  5949. // Check if the field with is non-zero.
  5950. const OptionalAmount &Amt = FS.getFieldWidth();
  5951. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  5952. if (Amt.getConstantAmount() == 0) {
  5953. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  5954. Amt.getConstantLength());
  5955. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  5956. getLocationOfByte(Amt.getStart()),
  5957. /*IsStringLocation*/true, R,
  5958. FixItHint::CreateRemoval(R));
  5959. }
  5960. }
  5961. if (!FS.consumesDataArgument()) {
  5962. // FIXME: Technically specifying a precision or field width here
  5963. // makes no sense. Worth issuing a warning at some point.
  5964. return true;
  5965. }
  5966. // Consume the argument.
  5967. unsigned argIndex = FS.getArgIndex();
  5968. if (argIndex < NumDataArgs) {
  5969. // The check to see if the argIndex is valid will come later.
  5970. // We set the bit here because we may exit early from this
  5971. // function if we encounter some other error.
  5972. CoveredArgs.set(argIndex);
  5973. }
  5974. // Check the length modifier is valid with the given conversion specifier.
  5975. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  5976. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5977. diag::warn_format_nonsensical_length);
  5978. else if (!FS.hasStandardLengthModifier())
  5979. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  5980. else if (!FS.hasStandardLengthConversionCombination())
  5981. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5982. diag::warn_format_non_standard_conversion_spec);
  5983. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  5984. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  5985. // The remaining checks depend on the data arguments.
  5986. if (HasVAListArg)
  5987. return true;
  5988. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  5989. return false;
  5990. // Check that the argument type matches the format specifier.
  5991. const Expr *Ex = getDataArg(argIndex);
  5992. if (!Ex)
  5993. return true;
  5994. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  5995. if (!AT.isValid()) {
  5996. return true;
  5997. }
  5998. analyze_format_string::ArgType::MatchKind match =
  5999. AT.matchesType(S.Context, Ex->getType());
  6000. if (match == analyze_format_string::ArgType::Match) {
  6001. return true;
  6002. }
  6003. ScanfSpecifier fixedFS = FS;
  6004. bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  6005. S.getLangOpts(), S.Context);
  6006. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  6007. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  6008. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  6009. }
  6010. if (success) {
  6011. // Get the fix string from the fixed format specifier.
  6012. SmallString<128> buf;
  6013. llvm::raw_svector_ostream os(buf);
  6014. fixedFS.toString(os);
  6015. EmitFormatDiagnostic(
  6016. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
  6017. << Ex->getType() << false << Ex->getSourceRange(),
  6018. Ex->getLocStart(),
  6019. /*IsStringLocation*/ false,
  6020. getSpecifierRange(startSpecifier, specifierLen),
  6021. FixItHint::CreateReplacement(
  6022. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  6023. } else {
  6024. EmitFormatDiagnostic(S.PDiag(diag)
  6025. << AT.getRepresentativeTypeName(S.Context)
  6026. << Ex->getType() << false << Ex->getSourceRange(),
  6027. Ex->getLocStart(),
  6028. /*IsStringLocation*/ false,
  6029. getSpecifierRange(startSpecifier, specifierLen));
  6030. }
  6031. return true;
  6032. }
  6033. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  6034. const Expr *OrigFormatExpr,
  6035. ArrayRef<const Expr *> Args,
  6036. bool HasVAListArg, unsigned format_idx,
  6037. unsigned firstDataArg,
  6038. Sema::FormatStringType Type,
  6039. bool inFunctionCall,
  6040. Sema::VariadicCallType CallType,
  6041. llvm::SmallBitVector &CheckedVarArgs,
  6042. UncoveredArgHandler &UncoveredArg) {
  6043. // CHECK: is the format string a wide literal?
  6044. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  6045. CheckFormatHandler::EmitFormatDiagnostic(
  6046. S, inFunctionCall, Args[format_idx],
  6047. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  6048. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  6049. return;
  6050. }
  6051. // Str - The format string. NOTE: this is NOT null-terminated!
  6052. StringRef StrRef = FExpr->getString();
  6053. const char *Str = StrRef.data();
  6054. // Account for cases where the string literal is truncated in a declaration.
  6055. const ConstantArrayType *T =
  6056. S.Context.getAsConstantArrayType(FExpr->getType());
  6057. assert(T && "String literal not of constant array type!");
  6058. size_t TypeSize = T->getSize().getZExtValue();
  6059. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  6060. const unsigned numDataArgs = Args.size() - firstDataArg;
  6061. // Emit a warning if the string literal is truncated and does not contain an
  6062. // embedded null character.
  6063. if (TypeSize <= StrRef.size() &&
  6064. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  6065. CheckFormatHandler::EmitFormatDiagnostic(
  6066. S, inFunctionCall, Args[format_idx],
  6067. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  6068. FExpr->getLocStart(),
  6069. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  6070. return;
  6071. }
  6072. // CHECK: empty format string?
  6073. if (StrLen == 0 && numDataArgs > 0) {
  6074. CheckFormatHandler::EmitFormatDiagnostic(
  6075. S, inFunctionCall, Args[format_idx],
  6076. S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  6077. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  6078. return;
  6079. }
  6080. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  6081. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  6082. Type == Sema::FST_OSTrace) {
  6083. CheckPrintfHandler H(
  6084. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  6085. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  6086. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  6087. CheckedVarArgs, UncoveredArg);
  6088. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  6089. S.getLangOpts(),
  6090. S.Context.getTargetInfo(),
  6091. Type == Sema::FST_FreeBSDKPrintf))
  6092. H.DoneProcessing();
  6093. } else if (Type == Sema::FST_Scanf) {
  6094. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  6095. numDataArgs, Str, HasVAListArg, Args, format_idx,
  6096. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  6097. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  6098. S.getLangOpts(),
  6099. S.Context.getTargetInfo()))
  6100. H.DoneProcessing();
  6101. } // TODO: handle other formats
  6102. }
  6103. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  6104. // Str - The format string. NOTE: this is NOT null-terminated!
  6105. StringRef StrRef = FExpr->getString();
  6106. const char *Str = StrRef.data();
  6107. // Account for cases where the string literal is truncated in a declaration.
  6108. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  6109. assert(T && "String literal not of constant array type!");
  6110. size_t TypeSize = T->getSize().getZExtValue();
  6111. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  6112. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  6113. getLangOpts(),
  6114. Context.getTargetInfo());
  6115. }
  6116. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  6117. // Returns the related absolute value function that is larger, of 0 if one
  6118. // does not exist.
  6119. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  6120. switch (AbsFunction) {
  6121. default:
  6122. return 0;
  6123. case Builtin::BI__builtin_abs:
  6124. return Builtin::BI__builtin_labs;
  6125. case Builtin::BI__builtin_labs:
  6126. return Builtin::BI__builtin_llabs;
  6127. case Builtin::BI__builtin_llabs:
  6128. return 0;
  6129. case Builtin::BI__builtin_fabsf:
  6130. return Builtin::BI__builtin_fabs;
  6131. case Builtin::BI__builtin_fabs:
  6132. return Builtin::BI__builtin_fabsl;
  6133. case Builtin::BI__builtin_fabsl:
  6134. return 0;
  6135. case Builtin::BI__builtin_cabsf:
  6136. return Builtin::BI__builtin_cabs;
  6137. case Builtin::BI__builtin_cabs:
  6138. return Builtin::BI__builtin_cabsl;
  6139. case Builtin::BI__builtin_cabsl:
  6140. return 0;
  6141. case Builtin::BIabs:
  6142. return Builtin::BIlabs;
  6143. case Builtin::BIlabs:
  6144. return Builtin::BIllabs;
  6145. case Builtin::BIllabs:
  6146. return 0;
  6147. case Builtin::BIfabsf:
  6148. return Builtin::BIfabs;
  6149. case Builtin::BIfabs:
  6150. return Builtin::BIfabsl;
  6151. case Builtin::BIfabsl:
  6152. return 0;
  6153. case Builtin::BIcabsf:
  6154. return Builtin::BIcabs;
  6155. case Builtin::BIcabs:
  6156. return Builtin::BIcabsl;
  6157. case Builtin::BIcabsl:
  6158. return 0;
  6159. }
  6160. }
  6161. // Returns the argument type of the absolute value function.
  6162. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  6163. unsigned AbsType) {
  6164. if (AbsType == 0)
  6165. return QualType();
  6166. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  6167. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  6168. if (Error != ASTContext::GE_None)
  6169. return QualType();
  6170. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  6171. if (!FT)
  6172. return QualType();
  6173. if (FT->getNumParams() != 1)
  6174. return QualType();
  6175. return FT->getParamType(0);
  6176. }
  6177. // Returns the best absolute value function, or zero, based on type and
  6178. // current absolute value function.
  6179. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  6180. unsigned AbsFunctionKind) {
  6181. unsigned BestKind = 0;
  6182. uint64_t ArgSize = Context.getTypeSize(ArgType);
  6183. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  6184. Kind = getLargerAbsoluteValueFunction(Kind)) {
  6185. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  6186. if (Context.getTypeSize(ParamType) >= ArgSize) {
  6187. if (BestKind == 0)
  6188. BestKind = Kind;
  6189. else if (Context.hasSameType(ParamType, ArgType)) {
  6190. BestKind = Kind;
  6191. break;
  6192. }
  6193. }
  6194. }
  6195. return BestKind;
  6196. }
  6197. enum AbsoluteValueKind {
  6198. AVK_Integer,
  6199. AVK_Floating,
  6200. AVK_Complex
  6201. };
  6202. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  6203. if (T->isIntegralOrEnumerationType())
  6204. return AVK_Integer;
  6205. if (T->isRealFloatingType())
  6206. return AVK_Floating;
  6207. if (T->isAnyComplexType())
  6208. return AVK_Complex;
  6209. llvm_unreachable("Type not integer, floating, or complex");
  6210. }
  6211. // Changes the absolute value function to a different type. Preserves whether
  6212. // the function is a builtin.
  6213. static unsigned changeAbsFunction(unsigned AbsKind,
  6214. AbsoluteValueKind ValueKind) {
  6215. switch (ValueKind) {
  6216. case AVK_Integer:
  6217. switch (AbsKind) {
  6218. default:
  6219. return 0;
  6220. case Builtin::BI__builtin_fabsf:
  6221. case Builtin::BI__builtin_fabs:
  6222. case Builtin::BI__builtin_fabsl:
  6223. case Builtin::BI__builtin_cabsf:
  6224. case Builtin::BI__builtin_cabs:
  6225. case Builtin::BI__builtin_cabsl:
  6226. return Builtin::BI__builtin_abs;
  6227. case Builtin::BIfabsf:
  6228. case Builtin::BIfabs:
  6229. case Builtin::BIfabsl:
  6230. case Builtin::BIcabsf:
  6231. case Builtin::BIcabs:
  6232. case Builtin::BIcabsl:
  6233. return Builtin::BIabs;
  6234. }
  6235. case AVK_Floating:
  6236. switch (AbsKind) {
  6237. default:
  6238. return 0;
  6239. case Builtin::BI__builtin_abs:
  6240. case Builtin::BI__builtin_labs:
  6241. case Builtin::BI__builtin_llabs:
  6242. case Builtin::BI__builtin_cabsf:
  6243. case Builtin::BI__builtin_cabs:
  6244. case Builtin::BI__builtin_cabsl:
  6245. return Builtin::BI__builtin_fabsf;
  6246. case Builtin::BIabs:
  6247. case Builtin::BIlabs:
  6248. case Builtin::BIllabs:
  6249. case Builtin::BIcabsf:
  6250. case Builtin::BIcabs:
  6251. case Builtin::BIcabsl:
  6252. return Builtin::BIfabsf;
  6253. }
  6254. case AVK_Complex:
  6255. switch (AbsKind) {
  6256. default:
  6257. return 0;
  6258. case Builtin::BI__builtin_abs:
  6259. case Builtin::BI__builtin_labs:
  6260. case Builtin::BI__builtin_llabs:
  6261. case Builtin::BI__builtin_fabsf:
  6262. case Builtin::BI__builtin_fabs:
  6263. case Builtin::BI__builtin_fabsl:
  6264. return Builtin::BI__builtin_cabsf;
  6265. case Builtin::BIabs:
  6266. case Builtin::BIlabs:
  6267. case Builtin::BIllabs:
  6268. case Builtin::BIfabsf:
  6269. case Builtin::BIfabs:
  6270. case Builtin::BIfabsl:
  6271. return Builtin::BIcabsf;
  6272. }
  6273. }
  6274. llvm_unreachable("Unable to convert function");
  6275. }
  6276. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  6277. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  6278. if (!FnInfo)
  6279. return 0;
  6280. switch (FDecl->getBuiltinID()) {
  6281. default:
  6282. return 0;
  6283. case Builtin::BI__builtin_abs:
  6284. case Builtin::BI__builtin_fabs:
  6285. case Builtin::BI__builtin_fabsf:
  6286. case Builtin::BI__builtin_fabsl:
  6287. case Builtin::BI__builtin_labs:
  6288. case Builtin::BI__builtin_llabs:
  6289. case Builtin::BI__builtin_cabs:
  6290. case Builtin::BI__builtin_cabsf:
  6291. case Builtin::BI__builtin_cabsl:
  6292. case Builtin::BIabs:
  6293. case Builtin::BIlabs:
  6294. case Builtin::BIllabs:
  6295. case Builtin::BIfabs:
  6296. case Builtin::BIfabsf:
  6297. case Builtin::BIfabsl:
  6298. case Builtin::BIcabs:
  6299. case Builtin::BIcabsf:
  6300. case Builtin::BIcabsl:
  6301. return FDecl->getBuiltinID();
  6302. }
  6303. llvm_unreachable("Unknown Builtin type");
  6304. }
  6305. // If the replacement is valid, emit a note with replacement function.
  6306. // Additionally, suggest including the proper header if not already included.
  6307. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  6308. unsigned AbsKind, QualType ArgType) {
  6309. bool EmitHeaderHint = true;
  6310. const char *HeaderName = nullptr;
  6311. const char *FunctionName = nullptr;
  6312. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  6313. FunctionName = "std::abs";
  6314. if (ArgType->isIntegralOrEnumerationType()) {
  6315. HeaderName = "cstdlib";
  6316. } else if (ArgType->isRealFloatingType()) {
  6317. HeaderName = "cmath";
  6318. } else {
  6319. llvm_unreachable("Invalid Type");
  6320. }
  6321. // Lookup all std::abs
  6322. if (NamespaceDecl *Std = S.getStdNamespace()) {
  6323. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  6324. R.suppressDiagnostics();
  6325. S.LookupQualifiedName(R, Std);
  6326. for (const auto *I : R) {
  6327. const FunctionDecl *FDecl = nullptr;
  6328. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  6329. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  6330. } else {
  6331. FDecl = dyn_cast<FunctionDecl>(I);
  6332. }
  6333. if (!FDecl)
  6334. continue;
  6335. // Found std::abs(), check that they are the right ones.
  6336. if (FDecl->getNumParams() != 1)
  6337. continue;
  6338. // Check that the parameter type can handle the argument.
  6339. QualType ParamType = FDecl->getParamDecl(0)->getType();
  6340. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  6341. S.Context.getTypeSize(ArgType) <=
  6342. S.Context.getTypeSize(ParamType)) {
  6343. // Found a function, don't need the header hint.
  6344. EmitHeaderHint = false;
  6345. break;
  6346. }
  6347. }
  6348. }
  6349. } else {
  6350. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  6351. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  6352. if (HeaderName) {
  6353. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  6354. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  6355. R.suppressDiagnostics();
  6356. S.LookupName(R, S.getCurScope());
  6357. if (R.isSingleResult()) {
  6358. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  6359. if (FD && FD->getBuiltinID() == AbsKind) {
  6360. EmitHeaderHint = false;
  6361. } else {
  6362. return;
  6363. }
  6364. } else if (!R.empty()) {
  6365. return;
  6366. }
  6367. }
  6368. }
  6369. S.Diag(Loc, diag::note_replace_abs_function)
  6370. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  6371. if (!HeaderName)
  6372. return;
  6373. if (!EmitHeaderHint)
  6374. return;
  6375. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  6376. << FunctionName;
  6377. }
  6378. template <std::size_t StrLen>
  6379. static bool IsStdFunction(const FunctionDecl *FDecl,
  6380. const char (&Str)[StrLen]) {
  6381. if (!FDecl)
  6382. return false;
  6383. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  6384. return false;
  6385. if (!FDecl->isInStdNamespace())
  6386. return false;
  6387. return true;
  6388. }
  6389. // Warn when using the wrong abs() function.
  6390. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  6391. const FunctionDecl *FDecl) {
  6392. if (Call->getNumArgs() != 1)
  6393. return;
  6394. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  6395. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  6396. if (AbsKind == 0 && !IsStdAbs)
  6397. return;
  6398. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  6399. QualType ParamType = Call->getArg(0)->getType();
  6400. // Unsigned types cannot be negative. Suggest removing the absolute value
  6401. // function call.
  6402. if (ArgType->isUnsignedIntegerType()) {
  6403. const char *FunctionName =
  6404. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  6405. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  6406. Diag(Call->getExprLoc(), diag::note_remove_abs)
  6407. << FunctionName
  6408. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  6409. return;
  6410. }
  6411. // Taking the absolute value of a pointer is very suspicious, they probably
  6412. // wanted to index into an array, dereference a pointer, call a function, etc.
  6413. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  6414. unsigned DiagType = 0;
  6415. if (ArgType->isFunctionType())
  6416. DiagType = 1;
  6417. else if (ArgType->isArrayType())
  6418. DiagType = 2;
  6419. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  6420. return;
  6421. }
  6422. // std::abs has overloads which prevent most of the absolute value problems
  6423. // from occurring.
  6424. if (IsStdAbs)
  6425. return;
  6426. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  6427. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  6428. // The argument and parameter are the same kind. Check if they are the right
  6429. // size.
  6430. if (ArgValueKind == ParamValueKind) {
  6431. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  6432. return;
  6433. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  6434. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  6435. << FDecl << ArgType << ParamType;
  6436. if (NewAbsKind == 0)
  6437. return;
  6438. emitReplacement(*this, Call->getExprLoc(),
  6439. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  6440. return;
  6441. }
  6442. // ArgValueKind != ParamValueKind
  6443. // The wrong type of absolute value function was used. Attempt to find the
  6444. // proper one.
  6445. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  6446. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  6447. if (NewAbsKind == 0)
  6448. return;
  6449. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  6450. << FDecl << ParamValueKind << ArgValueKind;
  6451. emitReplacement(*this, Call->getExprLoc(),
  6452. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  6453. }
  6454. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  6455. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  6456. const FunctionDecl *FDecl) {
  6457. if (!Call || !FDecl) return;
  6458. // Ignore template specializations and macros.
  6459. if (inTemplateInstantiation()) return;
  6460. if (Call->getExprLoc().isMacroID()) return;
  6461. // Only care about the one template argument, two function parameter std::max
  6462. if (Call->getNumArgs() != 2) return;
  6463. if (!IsStdFunction(FDecl, "max")) return;
  6464. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  6465. if (!ArgList) return;
  6466. if (ArgList->size() != 1) return;
  6467. // Check that template type argument is unsigned integer.
  6468. const auto& TA = ArgList->get(0);
  6469. if (TA.getKind() != TemplateArgument::Type) return;
  6470. QualType ArgType = TA.getAsType();
  6471. if (!ArgType->isUnsignedIntegerType()) return;
  6472. // See if either argument is a literal zero.
  6473. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  6474. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  6475. if (!MTE) return false;
  6476. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  6477. if (!Num) return false;
  6478. if (Num->getValue() != 0) return false;
  6479. return true;
  6480. };
  6481. const Expr *FirstArg = Call->getArg(0);
  6482. const Expr *SecondArg = Call->getArg(1);
  6483. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  6484. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  6485. // Only warn when exactly one argument is zero.
  6486. if (IsFirstArgZero == IsSecondArgZero) return;
  6487. SourceRange FirstRange = FirstArg->getSourceRange();
  6488. SourceRange SecondRange = SecondArg->getSourceRange();
  6489. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  6490. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  6491. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  6492. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  6493. SourceRange RemovalRange;
  6494. if (IsFirstArgZero) {
  6495. RemovalRange = SourceRange(FirstRange.getBegin(),
  6496. SecondRange.getBegin().getLocWithOffset(-1));
  6497. } else {
  6498. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  6499. SecondRange.getEnd());
  6500. }
  6501. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  6502. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  6503. << FixItHint::CreateRemoval(RemovalRange);
  6504. }
  6505. //===--- CHECK: Standard memory functions ---------------------------------===//
  6506. /// \brief Takes the expression passed to the size_t parameter of functions
  6507. /// such as memcmp, strncat, etc and warns if it's a comparison.
  6508. ///
  6509. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  6510. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  6511. IdentifierInfo *FnName,
  6512. SourceLocation FnLoc,
  6513. SourceLocation RParenLoc) {
  6514. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  6515. if (!Size)
  6516. return false;
  6517. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  6518. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  6519. return false;
  6520. SourceRange SizeRange = Size->getSourceRange();
  6521. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  6522. << SizeRange << FnName;
  6523. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  6524. << FnName << FixItHint::CreateInsertion(
  6525. S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
  6526. << FixItHint::CreateRemoval(RParenLoc);
  6527. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  6528. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  6529. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  6530. ")");
  6531. return true;
  6532. }
  6533. /// \brief Determine whether the given type is or contains a dynamic class type
  6534. /// (e.g., whether it has a vtable).
  6535. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  6536. bool &IsContained) {
  6537. // Look through array types while ignoring qualifiers.
  6538. const Type *Ty = T->getBaseElementTypeUnsafe();
  6539. IsContained = false;
  6540. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  6541. RD = RD ? RD->getDefinition() : nullptr;
  6542. if (!RD || RD->isInvalidDecl())
  6543. return nullptr;
  6544. if (RD->isDynamicClass())
  6545. return RD;
  6546. // Check all the fields. If any bases were dynamic, the class is dynamic.
  6547. // It's impossible for a class to transitively contain itself by value, so
  6548. // infinite recursion is impossible.
  6549. for (auto *FD : RD->fields()) {
  6550. bool SubContained;
  6551. if (const CXXRecordDecl *ContainedRD =
  6552. getContainedDynamicClass(FD->getType(), SubContained)) {
  6553. IsContained = true;
  6554. return ContainedRD;
  6555. }
  6556. }
  6557. return nullptr;
  6558. }
  6559. /// \brief If E is a sizeof expression, returns its argument expression,
  6560. /// otherwise returns NULL.
  6561. static const Expr *getSizeOfExprArg(const Expr *E) {
  6562. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  6563. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  6564. if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
  6565. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  6566. return nullptr;
  6567. }
  6568. /// \brief If E is a sizeof expression, returns its argument type.
  6569. static QualType getSizeOfArgType(const Expr *E) {
  6570. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  6571. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  6572. if (SizeOf->getKind() == UETT_SizeOf)
  6573. return SizeOf->getTypeOfArgument();
  6574. return QualType();
  6575. }
  6576. namespace {
  6577. struct SearchNonTrivialToInitializeField
  6578. : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
  6579. using Super =
  6580. DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
  6581. SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
  6582. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
  6583. SourceLocation SL) {
  6584. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  6585. asDerived().visitArray(PDIK, AT, SL);
  6586. return;
  6587. }
  6588. Super::visitWithKind(PDIK, FT, SL);
  6589. }
  6590. void visitARCStrong(QualType FT, SourceLocation SL) {
  6591. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  6592. }
  6593. void visitARCWeak(QualType FT, SourceLocation SL) {
  6594. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  6595. }
  6596. void visitStruct(QualType FT, SourceLocation SL) {
  6597. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  6598. visit(FD->getType(), FD->getLocation());
  6599. }
  6600. void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
  6601. const ArrayType *AT, SourceLocation SL) {
  6602. visit(getContext().getBaseElementType(AT), SL);
  6603. }
  6604. void visitTrivial(QualType FT, SourceLocation SL) {}
  6605. static void diag(QualType RT, const Expr *E, Sema &S) {
  6606. SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
  6607. }
  6608. ASTContext &getContext() { return S.getASTContext(); }
  6609. const Expr *E;
  6610. Sema &S;
  6611. };
  6612. struct SearchNonTrivialToCopyField
  6613. : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
  6614. using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
  6615. SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
  6616. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
  6617. SourceLocation SL) {
  6618. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  6619. asDerived().visitArray(PCK, AT, SL);
  6620. return;
  6621. }
  6622. Super::visitWithKind(PCK, FT, SL);
  6623. }
  6624. void visitARCStrong(QualType FT, SourceLocation SL) {
  6625. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  6626. }
  6627. void visitARCWeak(QualType FT, SourceLocation SL) {
  6628. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  6629. }
  6630. void visitStruct(QualType FT, SourceLocation SL) {
  6631. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  6632. visit(FD->getType(), FD->getLocation());
  6633. }
  6634. void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
  6635. SourceLocation SL) {
  6636. visit(getContext().getBaseElementType(AT), SL);
  6637. }
  6638. void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
  6639. SourceLocation SL) {}
  6640. void visitTrivial(QualType FT, SourceLocation SL) {}
  6641. void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
  6642. static void diag(QualType RT, const Expr *E, Sema &S) {
  6643. SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
  6644. }
  6645. ASTContext &getContext() { return S.getASTContext(); }
  6646. const Expr *E;
  6647. Sema &S;
  6648. };
  6649. }
  6650. /// \brief Check for dangerous or invalid arguments to memset().
  6651. ///
  6652. /// This issues warnings on known problematic, dangerous or unspecified
  6653. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  6654. /// function calls.
  6655. ///
  6656. /// \param Call The call expression to diagnose.
  6657. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  6658. unsigned BId,
  6659. IdentifierInfo *FnName) {
  6660. assert(BId != 0);
  6661. // It is possible to have a non-standard definition of memset. Validate
  6662. // we have enough arguments, and if not, abort further checking.
  6663. unsigned ExpectedNumArgs =
  6664. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  6665. if (Call->getNumArgs() < ExpectedNumArgs)
  6666. return;
  6667. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  6668. BId == Builtin::BIstrndup ? 1 : 2);
  6669. unsigned LenArg =
  6670. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  6671. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  6672. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  6673. Call->getLocStart(), Call->getRParenLoc()))
  6674. return;
  6675. // We have special checking when the length is a sizeof expression.
  6676. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  6677. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  6678. llvm::FoldingSetNodeID SizeOfArgID;
  6679. // Although widely used, 'bzero' is not a standard function. Be more strict
  6680. // with the argument types before allowing diagnostics and only allow the
  6681. // form bzero(ptr, sizeof(...)).
  6682. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  6683. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  6684. return;
  6685. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  6686. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  6687. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  6688. QualType DestTy = Dest->getType();
  6689. QualType PointeeTy;
  6690. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  6691. PointeeTy = DestPtrTy->getPointeeType();
  6692. // Never warn about void type pointers. This can be used to suppress
  6693. // false positives.
  6694. if (PointeeTy->isVoidType())
  6695. continue;
  6696. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  6697. // actually comparing the expressions for equality. Because computing the
  6698. // expression IDs can be expensive, we only do this if the diagnostic is
  6699. // enabled.
  6700. if (SizeOfArg &&
  6701. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  6702. SizeOfArg->getExprLoc())) {
  6703. // We only compute IDs for expressions if the warning is enabled, and
  6704. // cache the sizeof arg's ID.
  6705. if (SizeOfArgID == llvm::FoldingSetNodeID())
  6706. SizeOfArg->Profile(SizeOfArgID, Context, true);
  6707. llvm::FoldingSetNodeID DestID;
  6708. Dest->Profile(DestID, Context, true);
  6709. if (DestID == SizeOfArgID) {
  6710. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  6711. // over sizeof(src) as well.
  6712. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  6713. StringRef ReadableName = FnName->getName();
  6714. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  6715. if (UnaryOp->getOpcode() == UO_AddrOf)
  6716. ActionIdx = 1; // If its an address-of operator, just remove it.
  6717. if (!PointeeTy->isIncompleteType() &&
  6718. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  6719. ActionIdx = 2; // If the pointee's size is sizeof(char),
  6720. // suggest an explicit length.
  6721. // If the function is defined as a builtin macro, do not show macro
  6722. // expansion.
  6723. SourceLocation SL = SizeOfArg->getExprLoc();
  6724. SourceRange DSR = Dest->getSourceRange();
  6725. SourceRange SSR = SizeOfArg->getSourceRange();
  6726. SourceManager &SM = getSourceManager();
  6727. if (SM.isMacroArgExpansion(SL)) {
  6728. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  6729. SL = SM.getSpellingLoc(SL);
  6730. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  6731. SM.getSpellingLoc(DSR.getEnd()));
  6732. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  6733. SM.getSpellingLoc(SSR.getEnd()));
  6734. }
  6735. DiagRuntimeBehavior(SL, SizeOfArg,
  6736. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  6737. << ReadableName
  6738. << PointeeTy
  6739. << DestTy
  6740. << DSR
  6741. << SSR);
  6742. DiagRuntimeBehavior(SL, SizeOfArg,
  6743. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  6744. << ActionIdx
  6745. << SSR);
  6746. break;
  6747. }
  6748. }
  6749. // Also check for cases where the sizeof argument is the exact same
  6750. // type as the memory argument, and where it points to a user-defined
  6751. // record type.
  6752. if (SizeOfArgTy != QualType()) {
  6753. if (PointeeTy->isRecordType() &&
  6754. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  6755. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  6756. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  6757. << FnName << SizeOfArgTy << ArgIdx
  6758. << PointeeTy << Dest->getSourceRange()
  6759. << LenExpr->getSourceRange());
  6760. break;
  6761. }
  6762. }
  6763. } else if (DestTy->isArrayType()) {
  6764. PointeeTy = DestTy;
  6765. }
  6766. if (PointeeTy == QualType())
  6767. continue;
  6768. // Always complain about dynamic classes.
  6769. bool IsContained;
  6770. if (const CXXRecordDecl *ContainedRD =
  6771. getContainedDynamicClass(PointeeTy, IsContained)) {
  6772. unsigned OperationType = 0;
  6773. // "overwritten" if we're warning about the destination for any call
  6774. // but memcmp; otherwise a verb appropriate to the call.
  6775. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  6776. if (BId == Builtin::BImemcpy)
  6777. OperationType = 1;
  6778. else if(BId == Builtin::BImemmove)
  6779. OperationType = 2;
  6780. else if (BId == Builtin::BImemcmp)
  6781. OperationType = 3;
  6782. }
  6783. DiagRuntimeBehavior(
  6784. Dest->getExprLoc(), Dest,
  6785. PDiag(diag::warn_dyn_class_memaccess)
  6786. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  6787. << FnName << IsContained << ContainedRD << OperationType
  6788. << Call->getCallee()->getSourceRange());
  6789. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  6790. BId != Builtin::BImemset)
  6791. DiagRuntimeBehavior(
  6792. Dest->getExprLoc(), Dest,
  6793. PDiag(diag::warn_arc_object_memaccess)
  6794. << ArgIdx << FnName << PointeeTy
  6795. << Call->getCallee()->getSourceRange());
  6796. else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
  6797. if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
  6798. RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
  6799. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  6800. PDiag(diag::warn_cstruct_memaccess)
  6801. << ArgIdx << FnName << PointeeTy << 0);
  6802. SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
  6803. } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  6804. RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
  6805. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  6806. PDiag(diag::warn_cstruct_memaccess)
  6807. << ArgIdx << FnName << PointeeTy << 1);
  6808. SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
  6809. } else {
  6810. continue;
  6811. }
  6812. } else
  6813. continue;
  6814. DiagRuntimeBehavior(
  6815. Dest->getExprLoc(), Dest,
  6816. PDiag(diag::note_bad_memaccess_silence)
  6817. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  6818. break;
  6819. }
  6820. }
  6821. // A little helper routine: ignore addition and subtraction of integer literals.
  6822. // This intentionally does not ignore all integer constant expressions because
  6823. // we don't want to remove sizeof().
  6824. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  6825. Ex = Ex->IgnoreParenCasts();
  6826. while (true) {
  6827. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  6828. if (!BO || !BO->isAdditiveOp())
  6829. break;
  6830. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  6831. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  6832. if (isa<IntegerLiteral>(RHS))
  6833. Ex = LHS;
  6834. else if (isa<IntegerLiteral>(LHS))
  6835. Ex = RHS;
  6836. else
  6837. break;
  6838. }
  6839. return Ex;
  6840. }
  6841. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  6842. ASTContext &Context) {
  6843. // Only handle constant-sized or VLAs, but not flexible members.
  6844. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  6845. // Only issue the FIXIT for arrays of size > 1.
  6846. if (CAT->getSize().getSExtValue() <= 1)
  6847. return false;
  6848. } else if (!Ty->isVariableArrayType()) {
  6849. return false;
  6850. }
  6851. return true;
  6852. }
  6853. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  6854. // be the size of the source, instead of the destination.
  6855. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  6856. IdentifierInfo *FnName) {
  6857. // Don't crash if the user has the wrong number of arguments
  6858. unsigned NumArgs = Call->getNumArgs();
  6859. if ((NumArgs != 3) && (NumArgs != 4))
  6860. return;
  6861. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  6862. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  6863. const Expr *CompareWithSrc = nullptr;
  6864. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  6865. Call->getLocStart(), Call->getRParenLoc()))
  6866. return;
  6867. // Look for 'strlcpy(dst, x, sizeof(x))'
  6868. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  6869. CompareWithSrc = Ex;
  6870. else {
  6871. // Look for 'strlcpy(dst, x, strlen(x))'
  6872. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  6873. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  6874. SizeCall->getNumArgs() == 1)
  6875. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  6876. }
  6877. }
  6878. if (!CompareWithSrc)
  6879. return;
  6880. // Determine if the argument to sizeof/strlen is equal to the source
  6881. // argument. In principle there's all kinds of things you could do
  6882. // here, for instance creating an == expression and evaluating it with
  6883. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  6884. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  6885. if (!SrcArgDRE)
  6886. return;
  6887. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  6888. if (!CompareWithSrcDRE ||
  6889. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  6890. return;
  6891. const Expr *OriginalSizeArg = Call->getArg(2);
  6892. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  6893. << OriginalSizeArg->getSourceRange() << FnName;
  6894. // Output a FIXIT hint if the destination is an array (rather than a
  6895. // pointer to an array). This could be enhanced to handle some
  6896. // pointers if we know the actual size, like if DstArg is 'array+2'
  6897. // we could say 'sizeof(array)-2'.
  6898. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  6899. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  6900. return;
  6901. SmallString<128> sizeString;
  6902. llvm::raw_svector_ostream OS(sizeString);
  6903. OS << "sizeof(";
  6904. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  6905. OS << ")";
  6906. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  6907. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  6908. OS.str());
  6909. }
  6910. /// Check if two expressions refer to the same declaration.
  6911. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  6912. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  6913. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  6914. return D1->getDecl() == D2->getDecl();
  6915. return false;
  6916. }
  6917. static const Expr *getStrlenExprArg(const Expr *E) {
  6918. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  6919. const FunctionDecl *FD = CE->getDirectCallee();
  6920. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  6921. return nullptr;
  6922. return CE->getArg(0)->IgnoreParenCasts();
  6923. }
  6924. return nullptr;
  6925. }
  6926. // Warn on anti-patterns as the 'size' argument to strncat.
  6927. // The correct size argument should look like following:
  6928. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  6929. void Sema::CheckStrncatArguments(const CallExpr *CE,
  6930. IdentifierInfo *FnName) {
  6931. // Don't crash if the user has the wrong number of arguments.
  6932. if (CE->getNumArgs() < 3)
  6933. return;
  6934. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  6935. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  6936. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  6937. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
  6938. CE->getRParenLoc()))
  6939. return;
  6940. // Identify common expressions, which are wrongly used as the size argument
  6941. // to strncat and may lead to buffer overflows.
  6942. unsigned PatternType = 0;
  6943. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  6944. // - sizeof(dst)
  6945. if (referToTheSameDecl(SizeOfArg, DstArg))
  6946. PatternType = 1;
  6947. // - sizeof(src)
  6948. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  6949. PatternType = 2;
  6950. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  6951. if (BE->getOpcode() == BO_Sub) {
  6952. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  6953. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  6954. // - sizeof(dst) - strlen(dst)
  6955. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  6956. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  6957. PatternType = 1;
  6958. // - sizeof(src) - (anything)
  6959. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  6960. PatternType = 2;
  6961. }
  6962. }
  6963. if (PatternType == 0)
  6964. return;
  6965. // Generate the diagnostic.
  6966. SourceLocation SL = LenArg->getLocStart();
  6967. SourceRange SR = LenArg->getSourceRange();
  6968. SourceManager &SM = getSourceManager();
  6969. // If the function is defined as a builtin macro, do not show macro expansion.
  6970. if (SM.isMacroArgExpansion(SL)) {
  6971. SL = SM.getSpellingLoc(SL);
  6972. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  6973. SM.getSpellingLoc(SR.getEnd()));
  6974. }
  6975. // Check if the destination is an array (rather than a pointer to an array).
  6976. QualType DstTy = DstArg->getType();
  6977. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  6978. Context);
  6979. if (!isKnownSizeArray) {
  6980. if (PatternType == 1)
  6981. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  6982. else
  6983. Diag(SL, diag::warn_strncat_src_size) << SR;
  6984. return;
  6985. }
  6986. if (PatternType == 1)
  6987. Diag(SL, diag::warn_strncat_large_size) << SR;
  6988. else
  6989. Diag(SL, diag::warn_strncat_src_size) << SR;
  6990. SmallString<128> sizeString;
  6991. llvm::raw_svector_ostream OS(sizeString);
  6992. OS << "sizeof(";
  6993. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  6994. OS << ") - ";
  6995. OS << "strlen(";
  6996. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  6997. OS << ") - 1";
  6998. Diag(SL, diag::note_strncat_wrong_size)
  6999. << FixItHint::CreateReplacement(SR, OS.str());
  7000. }
  7001. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  7002. static const Expr *EvalVal(const Expr *E,
  7003. SmallVectorImpl<const DeclRefExpr *> &refVars,
  7004. const Decl *ParentDecl);
  7005. static const Expr *EvalAddr(const Expr *E,
  7006. SmallVectorImpl<const DeclRefExpr *> &refVars,
  7007. const Decl *ParentDecl);
  7008. /// CheckReturnStackAddr - Check if a return statement returns the address
  7009. /// of a stack variable.
  7010. static void
  7011. CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
  7012. SourceLocation ReturnLoc) {
  7013. const Expr *stackE = nullptr;
  7014. SmallVector<const DeclRefExpr *, 8> refVars;
  7015. // Perform checking for returned stack addresses, local blocks,
  7016. // label addresses or references to temporaries.
  7017. if (lhsType->isPointerType() ||
  7018. (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  7019. stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
  7020. } else if (lhsType->isReferenceType()) {
  7021. stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
  7022. }
  7023. if (!stackE)
  7024. return; // Nothing suspicious was found.
  7025. // Parameters are initialized in the calling scope, so taking the address
  7026. // of a parameter reference doesn't need a warning.
  7027. for (auto *DRE : refVars)
  7028. if (isa<ParmVarDecl>(DRE->getDecl()))
  7029. return;
  7030. SourceLocation diagLoc;
  7031. SourceRange diagRange;
  7032. if (refVars.empty()) {
  7033. diagLoc = stackE->getLocStart();
  7034. diagRange = stackE->getSourceRange();
  7035. } else {
  7036. // We followed through a reference variable. 'stackE' contains the
  7037. // problematic expression but we will warn at the return statement pointing
  7038. // at the reference variable. We will later display the "trail" of
  7039. // reference variables using notes.
  7040. diagLoc = refVars[0]->getLocStart();
  7041. diagRange = refVars[0]->getSourceRange();
  7042. }
  7043. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
  7044. // address of local var
  7045. S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
  7046. << DR->getDecl()->getDeclName() << diagRange;
  7047. } else if (isa<BlockExpr>(stackE)) { // local block.
  7048. S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  7049. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  7050. S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  7051. } else { // local temporary.
  7052. // If there is an LValue->RValue conversion, then the value of the
  7053. // reference type is used, not the reference.
  7054. if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
  7055. if (ICE->getCastKind() == CK_LValueToRValue) {
  7056. return;
  7057. }
  7058. }
  7059. S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
  7060. << lhsType->isReferenceType() << diagRange;
  7061. }
  7062. // Display the "trail" of reference variables that we followed until we
  7063. // found the problematic expression using notes.
  7064. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  7065. const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  7066. // If this var binds to another reference var, show the range of the next
  7067. // var, otherwise the var binds to the problematic expression, in which case
  7068. // show the range of the expression.
  7069. SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
  7070. : stackE->getSourceRange();
  7071. S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  7072. << VD->getDeclName() << range;
  7073. }
  7074. }
  7075. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  7076. /// check if the expression in a return statement evaluates to an address
  7077. /// to a location on the stack, a local block, an address of a label, or a
  7078. /// reference to local temporary. The recursion is used to traverse the
  7079. /// AST of the return expression, with recursion backtracking when we
  7080. /// encounter a subexpression that (1) clearly does not lead to one of the
  7081. /// above problematic expressions (2) is something we cannot determine leads to
  7082. /// a problematic expression based on such local checking.
  7083. ///
  7084. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  7085. /// the expression that they point to. Such variables are added to the
  7086. /// 'refVars' vector so that we know what the reference variable "trail" was.
  7087. ///
  7088. /// EvalAddr processes expressions that are pointers that are used as
  7089. /// references (and not L-values). EvalVal handles all other values.
  7090. /// At the base case of the recursion is a check for the above problematic
  7091. /// expressions.
  7092. ///
  7093. /// This implementation handles:
  7094. ///
  7095. /// * pointer-to-pointer casts
  7096. /// * implicit conversions from array references to pointers
  7097. /// * taking the address of fields
  7098. /// * arbitrary interplay between "&" and "*" operators
  7099. /// * pointer arithmetic from an address of a stack variable
  7100. /// * taking the address of an array element where the array is on the stack
  7101. static const Expr *EvalAddr(const Expr *E,
  7102. SmallVectorImpl<const DeclRefExpr *> &refVars,
  7103. const Decl *ParentDecl) {
  7104. if (E->isTypeDependent())
  7105. return nullptr;
  7106. // We should only be called for evaluating pointer expressions.
  7107. assert((E->getType()->isAnyPointerType() ||
  7108. E->getType()->isBlockPointerType() ||
  7109. E->getType()->isObjCQualifiedIdType()) &&
  7110. "EvalAddr only works on pointers");
  7111. E = E->IgnoreParens();
  7112. // Our "symbolic interpreter" is just a dispatch off the currently
  7113. // viewed AST node. We then recursively traverse the AST by calling
  7114. // EvalAddr and EvalVal appropriately.
  7115. switch (E->getStmtClass()) {
  7116. case Stmt::DeclRefExprClass: {
  7117. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  7118. // If we leave the immediate function, the lifetime isn't about to end.
  7119. if (DR->refersToEnclosingVariableOrCapture())
  7120. return nullptr;
  7121. if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  7122. // If this is a reference variable, follow through to the expression that
  7123. // it points to.
  7124. if (V->hasLocalStorage() &&
  7125. V->getType()->isReferenceType() && V->hasInit()) {
  7126. // Add the reference variable to the "trail".
  7127. refVars.push_back(DR);
  7128. return EvalAddr(V->getInit(), refVars, ParentDecl);
  7129. }
  7130. return nullptr;
  7131. }
  7132. case Stmt::UnaryOperatorClass: {
  7133. // The only unary operator that make sense to handle here
  7134. // is AddrOf. All others don't make sense as pointers.
  7135. const UnaryOperator *U = cast<UnaryOperator>(E);
  7136. if (U->getOpcode() == UO_AddrOf)
  7137. return EvalVal(U->getSubExpr(), refVars, ParentDecl);
  7138. return nullptr;
  7139. }
  7140. case Stmt::BinaryOperatorClass: {
  7141. // Handle pointer arithmetic. All other binary operators are not valid
  7142. // in this context.
  7143. const BinaryOperator *B = cast<BinaryOperator>(E);
  7144. BinaryOperatorKind op = B->getOpcode();
  7145. if (op != BO_Add && op != BO_Sub)
  7146. return nullptr;
  7147. const Expr *Base = B->getLHS();
  7148. // Determine which argument is the real pointer base. It could be
  7149. // the RHS argument instead of the LHS.
  7150. if (!Base->getType()->isPointerType())
  7151. Base = B->getRHS();
  7152. assert(Base->getType()->isPointerType());
  7153. return EvalAddr(Base, refVars, ParentDecl);
  7154. }
  7155. // For conditional operators we need to see if either the LHS or RHS are
  7156. // valid DeclRefExpr*s. If one of them is valid, we return it.
  7157. case Stmt::ConditionalOperatorClass: {
  7158. const ConditionalOperator *C = cast<ConditionalOperator>(E);
  7159. // Handle the GNU extension for missing LHS.
  7160. // FIXME: That isn't a ConditionalOperator, so doesn't get here.
  7161. if (const Expr *LHSExpr = C->getLHS()) {
  7162. // In C++, we can have a throw-expression, which has 'void' type.
  7163. if (!LHSExpr->getType()->isVoidType())
  7164. if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
  7165. return LHS;
  7166. }
  7167. // In C++, we can have a throw-expression, which has 'void' type.
  7168. if (C->getRHS()->getType()->isVoidType())
  7169. return nullptr;
  7170. return EvalAddr(C->getRHS(), refVars, ParentDecl);
  7171. }
  7172. case Stmt::BlockExprClass:
  7173. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  7174. return E; // local block.
  7175. return nullptr;
  7176. case Stmt::AddrLabelExprClass:
  7177. return E; // address of label.
  7178. case Stmt::ExprWithCleanupsClass:
  7179. return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  7180. ParentDecl);
  7181. // For casts, we need to handle conversions from arrays to
  7182. // pointer values, and pointer-to-pointer conversions.
  7183. case Stmt::ImplicitCastExprClass:
  7184. case Stmt::CStyleCastExprClass:
  7185. case Stmt::CXXFunctionalCastExprClass:
  7186. case Stmt::ObjCBridgedCastExprClass:
  7187. case Stmt::CXXStaticCastExprClass:
  7188. case Stmt::CXXDynamicCastExprClass:
  7189. case Stmt::CXXConstCastExprClass:
  7190. case Stmt::CXXReinterpretCastExprClass: {
  7191. const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  7192. switch (cast<CastExpr>(E)->getCastKind()) {
  7193. case CK_LValueToRValue:
  7194. case CK_NoOp:
  7195. case CK_BaseToDerived:
  7196. case CK_DerivedToBase:
  7197. case CK_UncheckedDerivedToBase:
  7198. case CK_Dynamic:
  7199. case CK_CPointerToObjCPointerCast:
  7200. case CK_BlockPointerToObjCPointerCast:
  7201. case CK_AnyPointerToBlockPointerCast:
  7202. return EvalAddr(SubExpr, refVars, ParentDecl);
  7203. case CK_ArrayToPointerDecay:
  7204. return EvalVal(SubExpr, refVars, ParentDecl);
  7205. case CK_BitCast:
  7206. if (SubExpr->getType()->isAnyPointerType() ||
  7207. SubExpr->getType()->isBlockPointerType() ||
  7208. SubExpr->getType()->isObjCQualifiedIdType())
  7209. return EvalAddr(SubExpr, refVars, ParentDecl);
  7210. else
  7211. return nullptr;
  7212. default:
  7213. return nullptr;
  7214. }
  7215. }
  7216. case Stmt::MaterializeTemporaryExprClass:
  7217. if (const Expr *Result =
  7218. EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  7219. refVars, ParentDecl))
  7220. return Result;
  7221. return E;
  7222. // Everything else: we simply don't reason about them.
  7223. default:
  7224. return nullptr;
  7225. }
  7226. }
  7227. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  7228. /// See the comments for EvalAddr for more details.
  7229. static const Expr *EvalVal(const Expr *E,
  7230. SmallVectorImpl<const DeclRefExpr *> &refVars,
  7231. const Decl *ParentDecl) {
  7232. do {
  7233. // We should only be called for evaluating non-pointer expressions, or
  7234. // expressions with a pointer type that are not used as references but
  7235. // instead
  7236. // are l-values (e.g., DeclRefExpr with a pointer type).
  7237. // Our "symbolic interpreter" is just a dispatch off the currently
  7238. // viewed AST node. We then recursively traverse the AST by calling
  7239. // EvalAddr and EvalVal appropriately.
  7240. E = E->IgnoreParens();
  7241. switch (E->getStmtClass()) {
  7242. case Stmt::ImplicitCastExprClass: {
  7243. const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  7244. if (IE->getValueKind() == VK_LValue) {
  7245. E = IE->getSubExpr();
  7246. continue;
  7247. }
  7248. return nullptr;
  7249. }
  7250. case Stmt::ExprWithCleanupsClass:
  7251. return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  7252. ParentDecl);
  7253. case Stmt::DeclRefExprClass: {
  7254. // When we hit a DeclRefExpr we are looking at code that refers to a
  7255. // variable's name. If it's not a reference variable we check if it has
  7256. // local storage within the function, and if so, return the expression.
  7257. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  7258. // If we leave the immediate function, the lifetime isn't about to end.
  7259. if (DR->refersToEnclosingVariableOrCapture())
  7260. return nullptr;
  7261. if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
  7262. // Check if it refers to itself, e.g. "int& i = i;".
  7263. if (V == ParentDecl)
  7264. return DR;
  7265. if (V->hasLocalStorage()) {
  7266. if (!V->getType()->isReferenceType())
  7267. return DR;
  7268. // Reference variable, follow through to the expression that
  7269. // it points to.
  7270. if (V->hasInit()) {
  7271. // Add the reference variable to the "trail".
  7272. refVars.push_back(DR);
  7273. return EvalVal(V->getInit(), refVars, V);
  7274. }
  7275. }
  7276. }
  7277. return nullptr;
  7278. }
  7279. case Stmt::UnaryOperatorClass: {
  7280. // The only unary operator that make sense to handle here
  7281. // is Deref. All others don't resolve to a "name." This includes
  7282. // handling all sorts of rvalues passed to a unary operator.
  7283. const UnaryOperator *U = cast<UnaryOperator>(E);
  7284. if (U->getOpcode() == UO_Deref)
  7285. return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
  7286. return nullptr;
  7287. }
  7288. case Stmt::ArraySubscriptExprClass: {
  7289. // Array subscripts are potential references to data on the stack. We
  7290. // retrieve the DeclRefExpr* for the array variable if it indeed
  7291. // has local storage.
  7292. const auto *ASE = cast<ArraySubscriptExpr>(E);
  7293. if (ASE->isTypeDependent())
  7294. return nullptr;
  7295. return EvalAddr(ASE->getBase(), refVars, ParentDecl);
  7296. }
  7297. case Stmt::OMPArraySectionExprClass: {
  7298. return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
  7299. ParentDecl);
  7300. }
  7301. case Stmt::ConditionalOperatorClass: {
  7302. // For conditional operators we need to see if either the LHS or RHS are
  7303. // non-NULL Expr's. If one is non-NULL, we return it.
  7304. const ConditionalOperator *C = cast<ConditionalOperator>(E);
  7305. // Handle the GNU extension for missing LHS.
  7306. if (const Expr *LHSExpr = C->getLHS()) {
  7307. // In C++, we can have a throw-expression, which has 'void' type.
  7308. if (!LHSExpr->getType()->isVoidType())
  7309. if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
  7310. return LHS;
  7311. }
  7312. // In C++, we can have a throw-expression, which has 'void' type.
  7313. if (C->getRHS()->getType()->isVoidType())
  7314. return nullptr;
  7315. return EvalVal(C->getRHS(), refVars, ParentDecl);
  7316. }
  7317. // Accesses to members are potential references to data on the stack.
  7318. case Stmt::MemberExprClass: {
  7319. const MemberExpr *M = cast<MemberExpr>(E);
  7320. // Check for indirect access. We only want direct field accesses.
  7321. if (M->isArrow())
  7322. return nullptr;
  7323. // Check whether the member type is itself a reference, in which case
  7324. // we're not going to refer to the member, but to what the member refers
  7325. // to.
  7326. if (M->getMemberDecl()->getType()->isReferenceType())
  7327. return nullptr;
  7328. return EvalVal(M->getBase(), refVars, ParentDecl);
  7329. }
  7330. case Stmt::MaterializeTemporaryExprClass:
  7331. if (const Expr *Result =
  7332. EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  7333. refVars, ParentDecl))
  7334. return Result;
  7335. return E;
  7336. default:
  7337. // Check that we don't return or take the address of a reference to a
  7338. // temporary. This is only useful in C++.
  7339. if (!E->isTypeDependent() && E->isRValue())
  7340. return E;
  7341. // Everything else: we simply don't reason about them.
  7342. return nullptr;
  7343. }
  7344. } while (true);
  7345. }
  7346. void
  7347. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  7348. SourceLocation ReturnLoc,
  7349. bool isObjCMethod,
  7350. const AttrVec *Attrs,
  7351. const FunctionDecl *FD) {
  7352. CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
  7353. // Check if the return value is null but should not be.
  7354. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  7355. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  7356. CheckNonNullExpr(*this, RetValExp))
  7357. Diag(ReturnLoc, diag::warn_null_ret)
  7358. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  7359. // C++11 [basic.stc.dynamic.allocation]p4:
  7360. // If an allocation function declared with a non-throwing
  7361. // exception-specification fails to allocate storage, it shall return
  7362. // a null pointer. Any other allocation function that fails to allocate
  7363. // storage shall indicate failure only by throwing an exception [...]
  7364. if (FD) {
  7365. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  7366. if (Op == OO_New || Op == OO_Array_New) {
  7367. const FunctionProtoType *Proto
  7368. = FD->getType()->castAs<FunctionProtoType>();
  7369. if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
  7370. CheckNonNullExpr(*this, RetValExp))
  7371. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  7372. << FD << getLangOpts().CPlusPlus11;
  7373. }
  7374. }
  7375. }
  7376. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  7377. /// Check for comparisons of floating point operands using != and ==.
  7378. /// Issue a warning if these are no self-comparisons, as they are not likely
  7379. /// to do what the programmer intended.
  7380. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  7381. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  7382. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  7383. // Special case: check for x == x (which is OK).
  7384. // Do not emit warnings for such cases.
  7385. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  7386. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  7387. if (DRL->getDecl() == DRR->getDecl())
  7388. return;
  7389. // Special case: check for comparisons against literals that can be exactly
  7390. // represented by APFloat. In such cases, do not emit a warning. This
  7391. // is a heuristic: often comparison against such literals are used to
  7392. // detect if a value in a variable has not changed. This clearly can
  7393. // lead to false negatives.
  7394. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  7395. if (FLL->isExact())
  7396. return;
  7397. } else
  7398. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  7399. if (FLR->isExact())
  7400. return;
  7401. // Check for comparisons with builtin types.
  7402. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  7403. if (CL->getBuiltinCallee())
  7404. return;
  7405. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  7406. if (CR->getBuiltinCallee())
  7407. return;
  7408. // Emit the diagnostic.
  7409. Diag(Loc, diag::warn_floatingpoint_eq)
  7410. << LHS->getSourceRange() << RHS->getSourceRange();
  7411. }
  7412. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  7413. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  7414. namespace {
  7415. /// Structure recording the 'active' range of an integer-valued
  7416. /// expression.
  7417. struct IntRange {
  7418. /// The number of bits active in the int.
  7419. unsigned Width;
  7420. /// True if the int is known not to have negative values.
  7421. bool NonNegative;
  7422. IntRange(unsigned Width, bool NonNegative)
  7423. : Width(Width), NonNegative(NonNegative) {}
  7424. /// Returns the range of the bool type.
  7425. static IntRange forBoolType() {
  7426. return IntRange(1, true);
  7427. }
  7428. /// Returns the range of an opaque value of the given integral type.
  7429. static IntRange forValueOfType(ASTContext &C, QualType T) {
  7430. return forValueOfCanonicalType(C,
  7431. T->getCanonicalTypeInternal().getTypePtr());
  7432. }
  7433. /// Returns the range of an opaque value of a canonical integral type.
  7434. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  7435. assert(T->isCanonicalUnqualified());
  7436. if (const VectorType *VT = dyn_cast<VectorType>(T))
  7437. T = VT->getElementType().getTypePtr();
  7438. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  7439. T = CT->getElementType().getTypePtr();
  7440. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  7441. T = AT->getValueType().getTypePtr();
  7442. if (!C.getLangOpts().CPlusPlus) {
  7443. // For enum types in C code, use the underlying datatype.
  7444. if (const EnumType *ET = dyn_cast<EnumType>(T))
  7445. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  7446. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  7447. // For enum types in C++, use the known bit width of the enumerators.
  7448. EnumDecl *Enum = ET->getDecl();
  7449. // In C++11, enums can have a fixed underlying type. Use this type to
  7450. // compute the range.
  7451. if (Enum->isFixed()) {
  7452. return IntRange(C.getIntWidth(QualType(T, 0)),
  7453. !ET->isSignedIntegerOrEnumerationType());
  7454. }
  7455. unsigned NumPositive = Enum->getNumPositiveBits();
  7456. unsigned NumNegative = Enum->getNumNegativeBits();
  7457. if (NumNegative == 0)
  7458. return IntRange(NumPositive, true/*NonNegative*/);
  7459. else
  7460. return IntRange(std::max(NumPositive + 1, NumNegative),
  7461. false/*NonNegative*/);
  7462. }
  7463. const BuiltinType *BT = cast<BuiltinType>(T);
  7464. assert(BT->isInteger());
  7465. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  7466. }
  7467. /// Returns the "target" range of a canonical integral type, i.e.
  7468. /// the range of values expressible in the type.
  7469. ///
  7470. /// This matches forValueOfCanonicalType except that enums have the
  7471. /// full range of their type, not the range of their enumerators.
  7472. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  7473. assert(T->isCanonicalUnqualified());
  7474. if (const VectorType *VT = dyn_cast<VectorType>(T))
  7475. T = VT->getElementType().getTypePtr();
  7476. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  7477. T = CT->getElementType().getTypePtr();
  7478. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  7479. T = AT->getValueType().getTypePtr();
  7480. if (const EnumType *ET = dyn_cast<EnumType>(T))
  7481. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  7482. const BuiltinType *BT = cast<BuiltinType>(T);
  7483. assert(BT->isInteger());
  7484. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  7485. }
  7486. /// Returns the supremum of two ranges: i.e. their conservative merge.
  7487. static IntRange join(IntRange L, IntRange R) {
  7488. return IntRange(std::max(L.Width, R.Width),
  7489. L.NonNegative && R.NonNegative);
  7490. }
  7491. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  7492. static IntRange meet(IntRange L, IntRange R) {
  7493. return IntRange(std::min(L.Width, R.Width),
  7494. L.NonNegative || R.NonNegative);
  7495. }
  7496. };
  7497. } // namespace
  7498. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  7499. unsigned MaxWidth) {
  7500. if (value.isSigned() && value.isNegative())
  7501. return IntRange(value.getMinSignedBits(), false);
  7502. if (value.getBitWidth() > MaxWidth)
  7503. value = value.trunc(MaxWidth);
  7504. // isNonNegative() just checks the sign bit without considering
  7505. // signedness.
  7506. return IntRange(value.getActiveBits(), true);
  7507. }
  7508. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  7509. unsigned MaxWidth) {
  7510. if (result.isInt())
  7511. return GetValueRange(C, result.getInt(), MaxWidth);
  7512. if (result.isVector()) {
  7513. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  7514. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  7515. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  7516. R = IntRange::join(R, El);
  7517. }
  7518. return R;
  7519. }
  7520. if (result.isComplexInt()) {
  7521. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  7522. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  7523. return IntRange::join(R, I);
  7524. }
  7525. // This can happen with lossless casts to intptr_t of "based" lvalues.
  7526. // Assume it might use arbitrary bits.
  7527. // FIXME: The only reason we need to pass the type in here is to get
  7528. // the sign right on this one case. It would be nice if APValue
  7529. // preserved this.
  7530. assert(result.isLValue() || result.isAddrLabelDiff());
  7531. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  7532. }
  7533. static QualType GetExprType(const Expr *E) {
  7534. QualType Ty = E->getType();
  7535. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  7536. Ty = AtomicRHS->getValueType();
  7537. return Ty;
  7538. }
  7539. /// Pseudo-evaluate the given integer expression, estimating the
  7540. /// range of values it might take.
  7541. ///
  7542. /// \param MaxWidth - the width to which the value will be truncated
  7543. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
  7544. E = E->IgnoreParens();
  7545. // Try a full evaluation first.
  7546. Expr::EvalResult result;
  7547. if (E->EvaluateAsRValue(result, C))
  7548. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  7549. // I think we only want to look through implicit casts here; if the
  7550. // user has an explicit widening cast, we should treat the value as
  7551. // being of the new, wider type.
  7552. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  7553. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  7554. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  7555. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  7556. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  7557. CE->getCastKind() == CK_BooleanToSignedIntegral;
  7558. // Assume that non-integer casts can span the full range of the type.
  7559. if (!isIntegerCast)
  7560. return OutputTypeRange;
  7561. IntRange SubRange
  7562. = GetExprRange(C, CE->getSubExpr(),
  7563. std::min(MaxWidth, OutputTypeRange.Width));
  7564. // Bail out if the subexpr's range is as wide as the cast type.
  7565. if (SubRange.Width >= OutputTypeRange.Width)
  7566. return OutputTypeRange;
  7567. // Otherwise, we take the smaller width, and we're non-negative if
  7568. // either the output type or the subexpr is.
  7569. return IntRange(SubRange.Width,
  7570. SubRange.NonNegative || OutputTypeRange.NonNegative);
  7571. }
  7572. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  7573. // If we can fold the condition, just take that operand.
  7574. bool CondResult;
  7575. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  7576. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  7577. : CO->getFalseExpr(),
  7578. MaxWidth);
  7579. // Otherwise, conservatively merge.
  7580. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  7581. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  7582. return IntRange::join(L, R);
  7583. }
  7584. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  7585. switch (BO->getOpcode()) {
  7586. case BO_Cmp:
  7587. llvm_unreachable("builtin <=> should have class type");
  7588. // Boolean-valued operations are single-bit and positive.
  7589. case BO_LAnd:
  7590. case BO_LOr:
  7591. case BO_LT:
  7592. case BO_GT:
  7593. case BO_LE:
  7594. case BO_GE:
  7595. case BO_EQ:
  7596. case BO_NE:
  7597. return IntRange::forBoolType();
  7598. // The type of the assignments is the type of the LHS, so the RHS
  7599. // is not necessarily the same type.
  7600. case BO_MulAssign:
  7601. case BO_DivAssign:
  7602. case BO_RemAssign:
  7603. case BO_AddAssign:
  7604. case BO_SubAssign:
  7605. case BO_XorAssign:
  7606. case BO_OrAssign:
  7607. // TODO: bitfields?
  7608. return IntRange::forValueOfType(C, GetExprType(E));
  7609. // Simple assignments just pass through the RHS, which will have
  7610. // been coerced to the LHS type.
  7611. case BO_Assign:
  7612. // TODO: bitfields?
  7613. return GetExprRange(C, BO->getRHS(), MaxWidth);
  7614. // Operations with opaque sources are black-listed.
  7615. case BO_PtrMemD:
  7616. case BO_PtrMemI:
  7617. return IntRange::forValueOfType(C, GetExprType(E));
  7618. // Bitwise-and uses the *infinum* of the two source ranges.
  7619. case BO_And:
  7620. case BO_AndAssign:
  7621. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  7622. GetExprRange(C, BO->getRHS(), MaxWidth));
  7623. // Left shift gets black-listed based on a judgement call.
  7624. case BO_Shl:
  7625. // ...except that we want to treat '1 << (blah)' as logically
  7626. // positive. It's an important idiom.
  7627. if (IntegerLiteral *I
  7628. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  7629. if (I->getValue() == 1) {
  7630. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  7631. return IntRange(R.Width, /*NonNegative*/ true);
  7632. }
  7633. }
  7634. LLVM_FALLTHROUGH;
  7635. case BO_ShlAssign:
  7636. return IntRange::forValueOfType(C, GetExprType(E));
  7637. // Right shift by a constant can narrow its left argument.
  7638. case BO_Shr:
  7639. case BO_ShrAssign: {
  7640. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  7641. // If the shift amount is a positive constant, drop the width by
  7642. // that much.
  7643. llvm::APSInt shift;
  7644. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  7645. shift.isNonNegative()) {
  7646. unsigned zext = shift.getZExtValue();
  7647. if (zext >= L.Width)
  7648. L.Width = (L.NonNegative ? 0 : 1);
  7649. else
  7650. L.Width -= zext;
  7651. }
  7652. return L;
  7653. }
  7654. // Comma acts as its right operand.
  7655. case BO_Comma:
  7656. return GetExprRange(C, BO->getRHS(), MaxWidth);
  7657. // Black-list pointer subtractions.
  7658. case BO_Sub:
  7659. if (BO->getLHS()->getType()->isPointerType())
  7660. return IntRange::forValueOfType(C, GetExprType(E));
  7661. break;
  7662. // The width of a division result is mostly determined by the size
  7663. // of the LHS.
  7664. case BO_Div: {
  7665. // Don't 'pre-truncate' the operands.
  7666. unsigned opWidth = C.getIntWidth(GetExprType(E));
  7667. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  7668. // If the divisor is constant, use that.
  7669. llvm::APSInt divisor;
  7670. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  7671. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  7672. if (log2 >= L.Width)
  7673. L.Width = (L.NonNegative ? 0 : 1);
  7674. else
  7675. L.Width = std::min(L.Width - log2, MaxWidth);
  7676. return L;
  7677. }
  7678. // Otherwise, just use the LHS's width.
  7679. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  7680. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  7681. }
  7682. // The result of a remainder can't be larger than the result of
  7683. // either side.
  7684. case BO_Rem: {
  7685. // Don't 'pre-truncate' the operands.
  7686. unsigned opWidth = C.getIntWidth(GetExprType(E));
  7687. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  7688. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  7689. IntRange meet = IntRange::meet(L, R);
  7690. meet.Width = std::min(meet.Width, MaxWidth);
  7691. return meet;
  7692. }
  7693. // The default behavior is okay for these.
  7694. case BO_Mul:
  7695. case BO_Add:
  7696. case BO_Xor:
  7697. case BO_Or:
  7698. break;
  7699. }
  7700. // The default case is to treat the operation as if it were closed
  7701. // on the narrowest type that encompasses both operands.
  7702. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  7703. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  7704. return IntRange::join(L, R);
  7705. }
  7706. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  7707. switch (UO->getOpcode()) {
  7708. // Boolean-valued operations are white-listed.
  7709. case UO_LNot:
  7710. return IntRange::forBoolType();
  7711. // Operations with opaque sources are black-listed.
  7712. case UO_Deref:
  7713. case UO_AddrOf: // should be impossible
  7714. return IntRange::forValueOfType(C, GetExprType(E));
  7715. default:
  7716. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  7717. }
  7718. }
  7719. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  7720. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
  7721. if (const auto *BitField = E->getSourceBitField())
  7722. return IntRange(BitField->getBitWidthValue(C),
  7723. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  7724. return IntRange::forValueOfType(C, GetExprType(E));
  7725. }
  7726. static IntRange GetExprRange(ASTContext &C, const Expr *E) {
  7727. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
  7728. }
  7729. /// Checks whether the given value, which currently has the given
  7730. /// source semantics, has the same value when coerced through the
  7731. /// target semantics.
  7732. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  7733. const llvm::fltSemantics &Src,
  7734. const llvm::fltSemantics &Tgt) {
  7735. llvm::APFloat truncated = value;
  7736. bool ignored;
  7737. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  7738. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  7739. return truncated.bitwiseIsEqual(value);
  7740. }
  7741. /// Checks whether the given value, which currently has the given
  7742. /// source semantics, has the same value when coerced through the
  7743. /// target semantics.
  7744. ///
  7745. /// The value might be a vector of floats (or a complex number).
  7746. static bool IsSameFloatAfterCast(const APValue &value,
  7747. const llvm::fltSemantics &Src,
  7748. const llvm::fltSemantics &Tgt) {
  7749. if (value.isFloat())
  7750. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  7751. if (value.isVector()) {
  7752. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  7753. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  7754. return false;
  7755. return true;
  7756. }
  7757. assert(value.isComplexFloat());
  7758. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  7759. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  7760. }
  7761. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  7762. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  7763. // Suppress cases where we are comparing against an enum constant.
  7764. if (const DeclRefExpr *DR =
  7765. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  7766. if (isa<EnumConstantDecl>(DR->getDecl()))
  7767. return true;
  7768. // Suppress cases where the '0' value is expanded from a macro.
  7769. if (E->getLocStart().isMacroID())
  7770. return true;
  7771. return false;
  7772. }
  7773. static bool isKnownToHaveUnsignedValue(Expr *E) {
  7774. return E->getType()->isIntegerType() &&
  7775. (!E->getType()->isSignedIntegerType() ||
  7776. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  7777. }
  7778. namespace {
  7779. /// The promoted range of values of a type. In general this has the
  7780. /// following structure:
  7781. ///
  7782. /// |-----------| . . . |-----------|
  7783. /// ^ ^ ^ ^
  7784. /// Min HoleMin HoleMax Max
  7785. ///
  7786. /// ... where there is only a hole if a signed type is promoted to unsigned
  7787. /// (in which case Min and Max are the smallest and largest representable
  7788. /// values).
  7789. struct PromotedRange {
  7790. // Min, or HoleMax if there is a hole.
  7791. llvm::APSInt PromotedMin;
  7792. // Max, or HoleMin if there is a hole.
  7793. llvm::APSInt PromotedMax;
  7794. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  7795. if (R.Width == 0)
  7796. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  7797. else if (R.Width >= BitWidth && !Unsigned) {
  7798. // Promotion made the type *narrower*. This happens when promoting
  7799. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  7800. // Treat all values of 'signed int' as being in range for now.
  7801. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  7802. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  7803. } else {
  7804. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  7805. .extOrTrunc(BitWidth);
  7806. PromotedMin.setIsUnsigned(Unsigned);
  7807. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  7808. .extOrTrunc(BitWidth);
  7809. PromotedMax.setIsUnsigned(Unsigned);
  7810. }
  7811. }
  7812. // Determine whether this range is contiguous (has no hole).
  7813. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  7814. // Where a constant value is within the range.
  7815. enum ComparisonResult {
  7816. LT = 0x1,
  7817. LE = 0x2,
  7818. GT = 0x4,
  7819. GE = 0x8,
  7820. EQ = 0x10,
  7821. NE = 0x20,
  7822. InRangeFlag = 0x40,
  7823. Less = LE | LT | NE,
  7824. Min = LE | InRangeFlag,
  7825. InRange = InRangeFlag,
  7826. Max = GE | InRangeFlag,
  7827. Greater = GE | GT | NE,
  7828. OnlyValue = LE | GE | EQ | InRangeFlag,
  7829. InHole = NE
  7830. };
  7831. ComparisonResult compare(const llvm::APSInt &Value) const {
  7832. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  7833. Value.isUnsigned() == PromotedMin.isUnsigned());
  7834. if (!isContiguous()) {
  7835. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  7836. if (Value.isMinValue()) return Min;
  7837. if (Value.isMaxValue()) return Max;
  7838. if (Value >= PromotedMin) return InRange;
  7839. if (Value <= PromotedMax) return InRange;
  7840. return InHole;
  7841. }
  7842. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  7843. case -1: return Less;
  7844. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  7845. case 1:
  7846. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  7847. case -1: return InRange;
  7848. case 0: return Max;
  7849. case 1: return Greater;
  7850. }
  7851. }
  7852. llvm_unreachable("impossible compare result");
  7853. }
  7854. static llvm::Optional<StringRef>
  7855. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  7856. if (Op == BO_Cmp) {
  7857. ComparisonResult LTFlag = LT, GTFlag = GT;
  7858. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  7859. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  7860. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  7861. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  7862. return llvm::None;
  7863. }
  7864. ComparisonResult TrueFlag, FalseFlag;
  7865. if (Op == BO_EQ) {
  7866. TrueFlag = EQ;
  7867. FalseFlag = NE;
  7868. } else if (Op == BO_NE) {
  7869. TrueFlag = NE;
  7870. FalseFlag = EQ;
  7871. } else {
  7872. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  7873. TrueFlag = LT;
  7874. FalseFlag = GE;
  7875. } else {
  7876. TrueFlag = GT;
  7877. FalseFlag = LE;
  7878. }
  7879. if (Op == BO_GE || Op == BO_LE)
  7880. std::swap(TrueFlag, FalseFlag);
  7881. }
  7882. if (R & TrueFlag)
  7883. return StringRef("true");
  7884. if (R & FalseFlag)
  7885. return StringRef("false");
  7886. return llvm::None;
  7887. }
  7888. };
  7889. }
  7890. static bool HasEnumType(Expr *E) {
  7891. // Strip off implicit integral promotions.
  7892. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  7893. if (ICE->getCastKind() != CK_IntegralCast &&
  7894. ICE->getCastKind() != CK_NoOp)
  7895. break;
  7896. E = ICE->getSubExpr();
  7897. }
  7898. return E->getType()->isEnumeralType();
  7899. }
  7900. static int classifyConstantValue(Expr *Constant) {
  7901. // The values of this enumeration are used in the diagnostics
  7902. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  7903. enum ConstantValueKind {
  7904. Miscellaneous = 0,
  7905. LiteralTrue,
  7906. LiteralFalse
  7907. };
  7908. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  7909. return BL->getValue() ? ConstantValueKind::LiteralTrue
  7910. : ConstantValueKind::LiteralFalse;
  7911. return ConstantValueKind::Miscellaneous;
  7912. }
  7913. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  7914. Expr *Constant, Expr *Other,
  7915. const llvm::APSInt &Value,
  7916. bool RhsConstant) {
  7917. if (S.inTemplateInstantiation())
  7918. return false;
  7919. Expr *OriginalOther = Other;
  7920. Constant = Constant->IgnoreParenImpCasts();
  7921. Other = Other->IgnoreParenImpCasts();
  7922. // Suppress warnings on tautological comparisons between values of the same
  7923. // enumeration type. There are only two ways we could warn on this:
  7924. // - If the constant is outside the range of representable values of
  7925. // the enumeration. In such a case, we should warn about the cast
  7926. // to enumeration type, not about the comparison.
  7927. // - If the constant is the maximum / minimum in-range value. For an
  7928. // enumeratin type, such comparisons can be meaningful and useful.
  7929. if (Constant->getType()->isEnumeralType() &&
  7930. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  7931. return false;
  7932. // TODO: Investigate using GetExprRange() to get tighter bounds
  7933. // on the bit ranges.
  7934. QualType OtherT = Other->getType();
  7935. if (const auto *AT = OtherT->getAs<AtomicType>())
  7936. OtherT = AT->getValueType();
  7937. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  7938. // Whether we're treating Other as being a bool because of the form of
  7939. // expression despite it having another type (typically 'int' in C).
  7940. bool OtherIsBooleanDespiteType =
  7941. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  7942. if (OtherIsBooleanDespiteType)
  7943. OtherRange = IntRange::forBoolType();
  7944. // Determine the promoted range of the other type and see if a comparison of
  7945. // the constant against that range is tautological.
  7946. PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
  7947. Value.isUnsigned());
  7948. auto Cmp = OtherPromotedRange.compare(Value);
  7949. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  7950. if (!Result)
  7951. return false;
  7952. // Suppress the diagnostic for an in-range comparison if the constant comes
  7953. // from a macro or enumerator. We don't want to diagnose
  7954. //
  7955. // some_long_value <= INT_MAX
  7956. //
  7957. // when sizeof(int) == sizeof(long).
  7958. bool InRange = Cmp & PromotedRange::InRangeFlag;
  7959. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  7960. return false;
  7961. // If this is a comparison to an enum constant, include that
  7962. // constant in the diagnostic.
  7963. const EnumConstantDecl *ED = nullptr;
  7964. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  7965. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  7966. // Should be enough for uint128 (39 decimal digits)
  7967. SmallString<64> PrettySourceValue;
  7968. llvm::raw_svector_ostream OS(PrettySourceValue);
  7969. if (ED)
  7970. OS << '\'' << *ED << "' (" << Value << ")";
  7971. else
  7972. OS << Value;
  7973. // FIXME: We use a somewhat different formatting for the in-range cases and
  7974. // cases involving boolean values for historical reasons. We should pick a
  7975. // consistent way of presenting these diagnostics.
  7976. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  7977. S.DiagRuntimeBehavior(
  7978. E->getOperatorLoc(), E,
  7979. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  7980. : diag::warn_tautological_bool_compare)
  7981. << OS.str() << classifyConstantValue(Constant)
  7982. << OtherT << OtherIsBooleanDespiteType << *Result
  7983. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  7984. } else {
  7985. unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  7986. ? (HasEnumType(OriginalOther)
  7987. ? diag::warn_unsigned_enum_always_true_comparison
  7988. : diag::warn_unsigned_always_true_comparison)
  7989. : diag::warn_tautological_constant_compare;
  7990. S.Diag(E->getOperatorLoc(), Diag)
  7991. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  7992. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  7993. }
  7994. return true;
  7995. }
  7996. /// Analyze the operands of the given comparison. Implements the
  7997. /// fallback case from AnalyzeComparison.
  7998. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  7999. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  8000. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  8001. }
  8002. /// \brief Implements -Wsign-compare.
  8003. ///
  8004. /// \param E the binary operator to check for warnings
  8005. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  8006. // The type the comparison is being performed in.
  8007. QualType T = E->getLHS()->getType();
  8008. // Only analyze comparison operators where both sides have been converted to
  8009. // the same type.
  8010. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  8011. return AnalyzeImpConvsInComparison(S, E);
  8012. // Don't analyze value-dependent comparisons directly.
  8013. if (E->isValueDependent())
  8014. return AnalyzeImpConvsInComparison(S, E);
  8015. Expr *LHS = E->getLHS();
  8016. Expr *RHS = E->getRHS();
  8017. if (T->isIntegralType(S.Context)) {
  8018. llvm::APSInt RHSValue;
  8019. llvm::APSInt LHSValue;
  8020. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  8021. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  8022. // We don't care about expressions whose result is a constant.
  8023. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  8024. return AnalyzeImpConvsInComparison(S, E);
  8025. // We only care about expressions where just one side is literal
  8026. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  8027. // Is the constant on the RHS or LHS?
  8028. const bool RhsConstant = IsRHSIntegralLiteral;
  8029. Expr *Const = RhsConstant ? RHS : LHS;
  8030. Expr *Other = RhsConstant ? LHS : RHS;
  8031. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  8032. // Check whether an integer constant comparison results in a value
  8033. // of 'true' or 'false'.
  8034. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  8035. return AnalyzeImpConvsInComparison(S, E);
  8036. }
  8037. }
  8038. if (!T->hasUnsignedIntegerRepresentation()) {
  8039. // We don't do anything special if this isn't an unsigned integral
  8040. // comparison: we're only interested in integral comparisons, and
  8041. // signed comparisons only happen in cases we don't care to warn about.
  8042. return AnalyzeImpConvsInComparison(S, E);
  8043. }
  8044. LHS = LHS->IgnoreParenImpCasts();
  8045. RHS = RHS->IgnoreParenImpCasts();
  8046. if (!S.getLangOpts().CPlusPlus) {
  8047. // Avoid warning about comparison of integers with different signs when
  8048. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  8049. // the type of `E`.
  8050. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  8051. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  8052. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  8053. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  8054. }
  8055. // Check to see if one of the (unmodified) operands is of different
  8056. // signedness.
  8057. Expr *signedOperand, *unsignedOperand;
  8058. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  8059. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  8060. "unsigned comparison between two signed integer expressions?");
  8061. signedOperand = LHS;
  8062. unsignedOperand = RHS;
  8063. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  8064. signedOperand = RHS;
  8065. unsignedOperand = LHS;
  8066. } else {
  8067. return AnalyzeImpConvsInComparison(S, E);
  8068. }
  8069. // Otherwise, calculate the effective range of the signed operand.
  8070. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  8071. // Go ahead and analyze implicit conversions in the operands. Note
  8072. // that we skip the implicit conversions on both sides.
  8073. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  8074. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  8075. // If the signed range is non-negative, -Wsign-compare won't fire.
  8076. if (signedRange.NonNegative)
  8077. return;
  8078. // For (in)equality comparisons, if the unsigned operand is a
  8079. // constant which cannot collide with a overflowed signed operand,
  8080. // then reinterpreting the signed operand as unsigned will not
  8081. // change the result of the comparison.
  8082. if (E->isEqualityOp()) {
  8083. unsigned comparisonWidth = S.Context.getIntWidth(T);
  8084. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  8085. // We should never be unable to prove that the unsigned operand is
  8086. // non-negative.
  8087. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  8088. if (unsignedRange.Width < comparisonWidth)
  8089. return;
  8090. }
  8091. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  8092. S.PDiag(diag::warn_mixed_sign_comparison)
  8093. << LHS->getType() << RHS->getType()
  8094. << LHS->getSourceRange() << RHS->getSourceRange());
  8095. }
  8096. /// Analyzes an attempt to assign the given value to a bitfield.
  8097. ///
  8098. /// Returns true if there was something fishy about the attempt.
  8099. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  8100. SourceLocation InitLoc) {
  8101. assert(Bitfield->isBitField());
  8102. if (Bitfield->isInvalidDecl())
  8103. return false;
  8104. // White-list bool bitfields.
  8105. QualType BitfieldType = Bitfield->getType();
  8106. if (BitfieldType->isBooleanType())
  8107. return false;
  8108. if (BitfieldType->isEnumeralType()) {
  8109. EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
  8110. // If the underlying enum type was not explicitly specified as an unsigned
  8111. // type and the enum contain only positive values, MSVC++ will cause an
  8112. // inconsistency by storing this as a signed type.
  8113. if (S.getLangOpts().CPlusPlus11 &&
  8114. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  8115. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  8116. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  8117. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  8118. << BitfieldEnumDecl->getNameAsString();
  8119. }
  8120. }
  8121. if (Bitfield->getType()->isBooleanType())
  8122. return false;
  8123. // Ignore value- or type-dependent expressions.
  8124. if (Bitfield->getBitWidth()->isValueDependent() ||
  8125. Bitfield->getBitWidth()->isTypeDependent() ||
  8126. Init->isValueDependent() ||
  8127. Init->isTypeDependent())
  8128. return false;
  8129. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  8130. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  8131. llvm::APSInt Value;
  8132. if (!OriginalInit->EvaluateAsInt(Value, S.Context,
  8133. Expr::SE_AllowSideEffects)) {
  8134. // The RHS is not constant. If the RHS has an enum type, make sure the
  8135. // bitfield is wide enough to hold all the values of the enum without
  8136. // truncation.
  8137. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  8138. EnumDecl *ED = EnumTy->getDecl();
  8139. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  8140. // Enum types are implicitly signed on Windows, so check if there are any
  8141. // negative enumerators to see if the enum was intended to be signed or
  8142. // not.
  8143. bool SignedEnum = ED->getNumNegativeBits() > 0;
  8144. // Check for surprising sign changes when assigning enum values to a
  8145. // bitfield of different signedness. If the bitfield is signed and we
  8146. // have exactly the right number of bits to store this unsigned enum,
  8147. // suggest changing the enum to an unsigned type. This typically happens
  8148. // on Windows where unfixed enums always use an underlying type of 'int'.
  8149. unsigned DiagID = 0;
  8150. if (SignedEnum && !SignedBitfield) {
  8151. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  8152. } else if (SignedBitfield && !SignedEnum &&
  8153. ED->getNumPositiveBits() == FieldWidth) {
  8154. DiagID = diag::warn_signed_bitfield_enum_conversion;
  8155. }
  8156. if (DiagID) {
  8157. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  8158. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  8159. SourceRange TypeRange =
  8160. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  8161. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  8162. << SignedEnum << TypeRange;
  8163. }
  8164. // Compute the required bitwidth. If the enum has negative values, we need
  8165. // one more bit than the normal number of positive bits to represent the
  8166. // sign bit.
  8167. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  8168. ED->getNumNegativeBits())
  8169. : ED->getNumPositiveBits();
  8170. // Check the bitwidth.
  8171. if (BitsNeeded > FieldWidth) {
  8172. Expr *WidthExpr = Bitfield->getBitWidth();
  8173. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  8174. << Bitfield << ED;
  8175. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  8176. << BitsNeeded << ED << WidthExpr->getSourceRange();
  8177. }
  8178. }
  8179. return false;
  8180. }
  8181. unsigned OriginalWidth = Value.getBitWidth();
  8182. if (!Value.isSigned() || Value.isNegative())
  8183. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  8184. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  8185. OriginalWidth = Value.getMinSignedBits();
  8186. if (OriginalWidth <= FieldWidth)
  8187. return false;
  8188. // Compute the value which the bitfield will contain.
  8189. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  8190. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  8191. // Check whether the stored value is equal to the original value.
  8192. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  8193. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  8194. return false;
  8195. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  8196. // therefore don't strictly fit into a signed bitfield of width 1.
  8197. if (FieldWidth == 1 && Value == 1)
  8198. return false;
  8199. std::string PrettyValue = Value.toString(10);
  8200. std::string PrettyTrunc = TruncatedValue.toString(10);
  8201. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  8202. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  8203. << Init->getSourceRange();
  8204. return true;
  8205. }
  8206. /// Analyze the given simple or compound assignment for warning-worthy
  8207. /// operations.
  8208. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  8209. // Just recurse on the LHS.
  8210. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  8211. // We want to recurse on the RHS as normal unless we're assigning to
  8212. // a bitfield.
  8213. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  8214. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  8215. E->getOperatorLoc())) {
  8216. // Recurse, ignoring any implicit conversions on the RHS.
  8217. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  8218. E->getOperatorLoc());
  8219. }
  8220. }
  8221. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  8222. }
  8223. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  8224. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  8225. SourceLocation CContext, unsigned diag,
  8226. bool pruneControlFlow = false) {
  8227. if (pruneControlFlow) {
  8228. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  8229. S.PDiag(diag)
  8230. << SourceType << T << E->getSourceRange()
  8231. << SourceRange(CContext));
  8232. return;
  8233. }
  8234. S.Diag(E->getExprLoc(), diag)
  8235. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  8236. }
  8237. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  8238. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  8239. SourceLocation CContext,
  8240. unsigned diag, bool pruneControlFlow = false) {
  8241. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  8242. }
  8243. /// Analyze the given compound assignment for the possible losing of
  8244. /// floating-point precision.
  8245. static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
  8246. assert(isa<CompoundAssignOperator>(E) &&
  8247. "Must be compound assignment operation");
  8248. // Recurse on the LHS and RHS in here
  8249. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  8250. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  8251. // Now check the outermost expression
  8252. const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
  8253. const auto *RBT = cast<CompoundAssignOperator>(E)
  8254. ->getComputationResultType()
  8255. ->getAs<BuiltinType>();
  8256. // If both source and target are floating points.
  8257. if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
  8258. // Builtin FP kinds are ordered by increasing FP rank.
  8259. if (ResultBT->getKind() < RBT->getKind())
  8260. // We don't want to warn for system macro.
  8261. if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
  8262. // warn about dropping FP rank.
  8263. DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
  8264. E->getOperatorLoc(),
  8265. diag::warn_impcast_float_result_precision);
  8266. }
  8267. /// Diagnose an implicit cast from a floating point value to an integer value.
  8268. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  8269. SourceLocation CContext) {
  8270. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  8271. const bool PruneWarnings = S.inTemplateInstantiation();
  8272. Expr *InnerE = E->IgnoreParenImpCasts();
  8273. // We also want to warn on, e.g., "int i = -1.234"
  8274. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  8275. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  8276. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  8277. const bool IsLiteral =
  8278. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  8279. llvm::APFloat Value(0.0);
  8280. bool IsConstant =
  8281. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  8282. if (!IsConstant) {
  8283. return DiagnoseImpCast(S, E, T, CContext,
  8284. diag::warn_impcast_float_integer, PruneWarnings);
  8285. }
  8286. bool isExact = false;
  8287. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  8288. T->hasUnsignedIntegerRepresentation());
  8289. if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
  8290. &isExact) == llvm::APFloat::opOK &&
  8291. isExact) {
  8292. if (IsLiteral) return;
  8293. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  8294. PruneWarnings);
  8295. }
  8296. unsigned DiagID = 0;
  8297. if (IsLiteral) {
  8298. // Warn on floating point literal to integer.
  8299. DiagID = diag::warn_impcast_literal_float_to_integer;
  8300. } else if (IntegerValue == 0) {
  8301. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  8302. return DiagnoseImpCast(S, E, T, CContext,
  8303. diag::warn_impcast_float_integer, PruneWarnings);
  8304. }
  8305. // Warn on non-zero to zero conversion.
  8306. DiagID = diag::warn_impcast_float_to_integer_zero;
  8307. } else {
  8308. if (IntegerValue.isUnsigned()) {
  8309. if (!IntegerValue.isMaxValue()) {
  8310. return DiagnoseImpCast(S, E, T, CContext,
  8311. diag::warn_impcast_float_integer, PruneWarnings);
  8312. }
  8313. } else { // IntegerValue.isSigned()
  8314. if (!IntegerValue.isMaxSignedValue() &&
  8315. !IntegerValue.isMinSignedValue()) {
  8316. return DiagnoseImpCast(S, E, T, CContext,
  8317. diag::warn_impcast_float_integer, PruneWarnings);
  8318. }
  8319. }
  8320. // Warn on evaluatable floating point expression to integer conversion.
  8321. DiagID = diag::warn_impcast_float_to_integer;
  8322. }
  8323. // FIXME: Force the precision of the source value down so we don't print
  8324. // digits which are usually useless (we don't really care here if we
  8325. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  8326. // would automatically print the shortest representation, but it's a bit
  8327. // tricky to implement.
  8328. SmallString<16> PrettySourceValue;
  8329. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  8330. precision = (precision * 59 + 195) / 196;
  8331. Value.toString(PrettySourceValue, precision);
  8332. SmallString<16> PrettyTargetValue;
  8333. if (IsBool)
  8334. PrettyTargetValue = Value.isZero() ? "false" : "true";
  8335. else
  8336. IntegerValue.toString(PrettyTargetValue);
  8337. if (PruneWarnings) {
  8338. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  8339. S.PDiag(DiagID)
  8340. << E->getType() << T.getUnqualifiedType()
  8341. << PrettySourceValue << PrettyTargetValue
  8342. << E->getSourceRange() << SourceRange(CContext));
  8343. } else {
  8344. S.Diag(E->getExprLoc(), DiagID)
  8345. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  8346. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  8347. }
  8348. }
  8349. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  8350. IntRange Range) {
  8351. if (!Range.Width) return "0";
  8352. llvm::APSInt ValueInRange = Value;
  8353. ValueInRange.setIsSigned(!Range.NonNegative);
  8354. ValueInRange = ValueInRange.trunc(Range.Width);
  8355. return ValueInRange.toString(10);
  8356. }
  8357. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  8358. if (!isa<ImplicitCastExpr>(Ex))
  8359. return false;
  8360. Expr *InnerE = Ex->IgnoreParenImpCasts();
  8361. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  8362. const Type *Source =
  8363. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  8364. if (Target->isDependentType())
  8365. return false;
  8366. const BuiltinType *FloatCandidateBT =
  8367. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  8368. const Type *BoolCandidateType = ToBool ? Target : Source;
  8369. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  8370. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  8371. }
  8372. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  8373. SourceLocation CC) {
  8374. unsigned NumArgs = TheCall->getNumArgs();
  8375. for (unsigned i = 0; i < NumArgs; ++i) {
  8376. Expr *CurrA = TheCall->getArg(i);
  8377. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  8378. continue;
  8379. bool IsSwapped = ((i > 0) &&
  8380. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  8381. IsSwapped |= ((i < (NumArgs - 1)) &&
  8382. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  8383. if (IsSwapped) {
  8384. // Warn on this floating-point to bool conversion.
  8385. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  8386. CurrA->getType(), CC,
  8387. diag::warn_impcast_floating_point_to_bool);
  8388. }
  8389. }
  8390. }
  8391. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  8392. SourceLocation CC) {
  8393. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  8394. E->getExprLoc()))
  8395. return;
  8396. // Don't warn on functions which have return type nullptr_t.
  8397. if (isa<CallExpr>(E))
  8398. return;
  8399. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  8400. const Expr::NullPointerConstantKind NullKind =
  8401. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  8402. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  8403. return;
  8404. // Return if target type is a safe conversion.
  8405. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  8406. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  8407. return;
  8408. SourceLocation Loc = E->getSourceRange().getBegin();
  8409. // Venture through the macro stacks to get to the source of macro arguments.
  8410. // The new location is a better location than the complete location that was
  8411. // passed in.
  8412. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  8413. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  8414. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  8415. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  8416. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  8417. Loc, S.SourceMgr, S.getLangOpts());
  8418. if (MacroName == "NULL")
  8419. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
  8420. }
  8421. // Only warn if the null and context location are in the same macro expansion.
  8422. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  8423. return;
  8424. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  8425. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  8426. << FixItHint::CreateReplacement(Loc,
  8427. S.getFixItZeroLiteralForType(T, Loc));
  8428. }
  8429. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  8430. ObjCArrayLiteral *ArrayLiteral);
  8431. static void
  8432. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  8433. ObjCDictionaryLiteral *DictionaryLiteral);
  8434. /// Check a single element within a collection literal against the
  8435. /// target element type.
  8436. static void checkObjCCollectionLiteralElement(Sema &S,
  8437. QualType TargetElementType,
  8438. Expr *Element,
  8439. unsigned ElementKind) {
  8440. // Skip a bitcast to 'id' or qualified 'id'.
  8441. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  8442. if (ICE->getCastKind() == CK_BitCast &&
  8443. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  8444. Element = ICE->getSubExpr();
  8445. }
  8446. QualType ElementType = Element->getType();
  8447. ExprResult ElementResult(Element);
  8448. if (ElementType->getAs<ObjCObjectPointerType>() &&
  8449. S.CheckSingleAssignmentConstraints(TargetElementType,
  8450. ElementResult,
  8451. false, false)
  8452. != Sema::Compatible) {
  8453. S.Diag(Element->getLocStart(),
  8454. diag::warn_objc_collection_literal_element)
  8455. << ElementType << ElementKind << TargetElementType
  8456. << Element->getSourceRange();
  8457. }
  8458. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  8459. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  8460. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  8461. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  8462. }
  8463. /// Check an Objective-C array literal being converted to the given
  8464. /// target type.
  8465. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  8466. ObjCArrayLiteral *ArrayLiteral) {
  8467. if (!S.NSArrayDecl)
  8468. return;
  8469. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  8470. if (!TargetObjCPtr)
  8471. return;
  8472. if (TargetObjCPtr->isUnspecialized() ||
  8473. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  8474. != S.NSArrayDecl->getCanonicalDecl())
  8475. return;
  8476. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  8477. if (TypeArgs.size() != 1)
  8478. return;
  8479. QualType TargetElementType = TypeArgs[0];
  8480. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  8481. checkObjCCollectionLiteralElement(S, TargetElementType,
  8482. ArrayLiteral->getElement(I),
  8483. 0);
  8484. }
  8485. }
  8486. /// Check an Objective-C dictionary literal being converted to the given
  8487. /// target type.
  8488. static void
  8489. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  8490. ObjCDictionaryLiteral *DictionaryLiteral) {
  8491. if (!S.NSDictionaryDecl)
  8492. return;
  8493. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  8494. if (!TargetObjCPtr)
  8495. return;
  8496. if (TargetObjCPtr->isUnspecialized() ||
  8497. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  8498. != S.NSDictionaryDecl->getCanonicalDecl())
  8499. return;
  8500. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  8501. if (TypeArgs.size() != 2)
  8502. return;
  8503. QualType TargetKeyType = TypeArgs[0];
  8504. QualType TargetObjectType = TypeArgs[1];
  8505. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  8506. auto Element = DictionaryLiteral->getKeyValueElement(I);
  8507. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  8508. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  8509. }
  8510. }
  8511. // Helper function to filter out cases for constant width constant conversion.
  8512. // Don't warn on char array initialization or for non-decimal values.
  8513. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  8514. SourceLocation CC) {
  8515. // If initializing from a constant, and the constant starts with '0',
  8516. // then it is a binary, octal, or hexadecimal. Allow these constants
  8517. // to fill all the bits, even if there is a sign change.
  8518. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  8519. const char FirstLiteralCharacter =
  8520. S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
  8521. if (FirstLiteralCharacter == '0')
  8522. return false;
  8523. }
  8524. // If the CC location points to a '{', and the type is char, then assume
  8525. // assume it is an array initialization.
  8526. if (CC.isValid() && T->isCharType()) {
  8527. const char FirstContextCharacter =
  8528. S.getSourceManager().getCharacterData(CC)[0];
  8529. if (FirstContextCharacter == '{')
  8530. return false;
  8531. }
  8532. return true;
  8533. }
  8534. static void
  8535. CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
  8536. bool *ICContext = nullptr) {
  8537. if (E->isTypeDependent() || E->isValueDependent()) return;
  8538. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  8539. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  8540. if (Source == Target) return;
  8541. if (Target->isDependentType()) return;
  8542. // If the conversion context location is invalid don't complain. We also
  8543. // don't want to emit a warning if the issue occurs from the expansion of
  8544. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  8545. // delay this check as long as possible. Once we detect we are in that
  8546. // scenario, we just return.
  8547. if (CC.isInvalid())
  8548. return;
  8549. // Diagnose implicit casts to bool.
  8550. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  8551. if (isa<StringLiteral>(E))
  8552. // Warn on string literal to bool. Checks for string literals in logical
  8553. // and expressions, for instance, assert(0 && "error here"), are
  8554. // prevented by a check in AnalyzeImplicitConversions().
  8555. return DiagnoseImpCast(S, E, T, CC,
  8556. diag::warn_impcast_string_literal_to_bool);
  8557. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  8558. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  8559. // This covers the literal expressions that evaluate to Objective-C
  8560. // objects.
  8561. return DiagnoseImpCast(S, E, T, CC,
  8562. diag::warn_impcast_objective_c_literal_to_bool);
  8563. }
  8564. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  8565. // Warn on pointer to bool conversion that is always true.
  8566. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  8567. SourceRange(CC));
  8568. }
  8569. }
  8570. // Check implicit casts from Objective-C collection literals to specialized
  8571. // collection types, e.g., NSArray<NSString *> *.
  8572. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  8573. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  8574. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  8575. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  8576. // Strip vector types.
  8577. if (isa<VectorType>(Source)) {
  8578. if (!isa<VectorType>(Target)) {
  8579. if (S.SourceMgr.isInSystemMacro(CC))
  8580. return;
  8581. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  8582. }
  8583. // If the vector cast is cast between two vectors of the same size, it is
  8584. // a bitcast, not a conversion.
  8585. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  8586. return;
  8587. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  8588. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  8589. }
  8590. if (auto VecTy = dyn_cast<VectorType>(Target))
  8591. Target = VecTy->getElementType().getTypePtr();
  8592. // Strip complex types.
  8593. if (isa<ComplexType>(Source)) {
  8594. if (!isa<ComplexType>(Target)) {
  8595. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  8596. return;
  8597. return DiagnoseImpCast(S, E, T, CC,
  8598. S.getLangOpts().CPlusPlus
  8599. ? diag::err_impcast_complex_scalar
  8600. : diag::warn_impcast_complex_scalar);
  8601. }
  8602. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  8603. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  8604. }
  8605. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  8606. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  8607. // If the source is floating point...
  8608. if (SourceBT && SourceBT->isFloatingPoint()) {
  8609. // ...and the target is floating point...
  8610. if (TargetBT && TargetBT->isFloatingPoint()) {
  8611. // ...then warn if we're dropping FP rank.
  8612. // Builtin FP kinds are ordered by increasing FP rank.
  8613. if (SourceBT->getKind() > TargetBT->getKind()) {
  8614. // Don't warn about float constants that are precisely
  8615. // representable in the target type.
  8616. Expr::EvalResult result;
  8617. if (E->EvaluateAsRValue(result, S.Context)) {
  8618. // Value might be a float, a float vector, or a float complex.
  8619. if (IsSameFloatAfterCast(result.Val,
  8620. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  8621. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  8622. return;
  8623. }
  8624. if (S.SourceMgr.isInSystemMacro(CC))
  8625. return;
  8626. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  8627. }
  8628. // ... or possibly if we're increasing rank, too
  8629. else if (TargetBT->getKind() > SourceBT->getKind()) {
  8630. if (S.SourceMgr.isInSystemMacro(CC))
  8631. return;
  8632. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  8633. }
  8634. return;
  8635. }
  8636. // If the target is integral, always warn.
  8637. if (TargetBT && TargetBT->isInteger()) {
  8638. if (S.SourceMgr.isInSystemMacro(CC))
  8639. return;
  8640. DiagnoseFloatingImpCast(S, E, T, CC);
  8641. }
  8642. // Detect the case where a call result is converted from floating-point to
  8643. // to bool, and the final argument to the call is converted from bool, to
  8644. // discover this typo:
  8645. //
  8646. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  8647. //
  8648. // FIXME: This is an incredibly special case; is there some more general
  8649. // way to detect this class of misplaced-parentheses bug?
  8650. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  8651. // Check last argument of function call to see if it is an
  8652. // implicit cast from a type matching the type the result
  8653. // is being cast to.
  8654. CallExpr *CEx = cast<CallExpr>(E);
  8655. if (unsigned NumArgs = CEx->getNumArgs()) {
  8656. Expr *LastA = CEx->getArg(NumArgs - 1);
  8657. Expr *InnerE = LastA->IgnoreParenImpCasts();
  8658. if (isa<ImplicitCastExpr>(LastA) &&
  8659. InnerE->getType()->isBooleanType()) {
  8660. // Warn on this floating-point to bool conversion
  8661. DiagnoseImpCast(S, E, T, CC,
  8662. diag::warn_impcast_floating_point_to_bool);
  8663. }
  8664. }
  8665. }
  8666. return;
  8667. }
  8668. DiagnoseNullConversion(S, E, T, CC);
  8669. S.DiscardMisalignedMemberAddress(Target, E);
  8670. if (!Source->isIntegerType() || !Target->isIntegerType())
  8671. return;
  8672. // TODO: remove this early return once the false positives for constant->bool
  8673. // in templates, macros, etc, are reduced or removed.
  8674. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  8675. return;
  8676. IntRange SourceRange = GetExprRange(S.Context, E);
  8677. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  8678. if (SourceRange.Width > TargetRange.Width) {
  8679. // If the source is a constant, use a default-on diagnostic.
  8680. // TODO: this should happen for bitfield stores, too.
  8681. llvm::APSInt Value(32);
  8682. if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
  8683. if (S.SourceMgr.isInSystemMacro(CC))
  8684. return;
  8685. std::string PrettySourceValue = Value.toString(10);
  8686. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  8687. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  8688. S.PDiag(diag::warn_impcast_integer_precision_constant)
  8689. << PrettySourceValue << PrettyTargetValue
  8690. << E->getType() << T << E->getSourceRange()
  8691. << clang::SourceRange(CC));
  8692. return;
  8693. }
  8694. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  8695. if (S.SourceMgr.isInSystemMacro(CC))
  8696. return;
  8697. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  8698. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  8699. /* pruneControlFlow */ true);
  8700. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  8701. }
  8702. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  8703. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  8704. // Warn when doing a signed to signed conversion, warn if the positive
  8705. // source value is exactly the width of the target type, which will
  8706. // cause a negative value to be stored.
  8707. llvm::APSInt Value;
  8708. if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
  8709. !S.SourceMgr.isInSystemMacro(CC)) {
  8710. if (isSameWidthConstantConversion(S, E, T, CC)) {
  8711. std::string PrettySourceValue = Value.toString(10);
  8712. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  8713. S.DiagRuntimeBehavior(
  8714. E->getExprLoc(), E,
  8715. S.PDiag(diag::warn_impcast_integer_precision_constant)
  8716. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  8717. << E->getSourceRange() << clang::SourceRange(CC));
  8718. return;
  8719. }
  8720. }
  8721. // Fall through for non-constants to give a sign conversion warning.
  8722. }
  8723. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  8724. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  8725. SourceRange.Width == TargetRange.Width)) {
  8726. if (S.SourceMgr.isInSystemMacro(CC))
  8727. return;
  8728. unsigned DiagID = diag::warn_impcast_integer_sign;
  8729. // Traditionally, gcc has warned about this under -Wsign-compare.
  8730. // We also want to warn about it in -Wconversion.
  8731. // So if -Wconversion is off, use a completely identical diagnostic
  8732. // in the sign-compare group.
  8733. // The conditional-checking code will
  8734. if (ICContext) {
  8735. DiagID = diag::warn_impcast_integer_sign_conditional;
  8736. *ICContext = true;
  8737. }
  8738. return DiagnoseImpCast(S, E, T, CC, DiagID);
  8739. }
  8740. // Diagnose conversions between different enumeration types.
  8741. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  8742. // type, to give us better diagnostics.
  8743. QualType SourceType = E->getType();
  8744. if (!S.getLangOpts().CPlusPlus) {
  8745. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  8746. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  8747. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  8748. SourceType = S.Context.getTypeDeclType(Enum);
  8749. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  8750. }
  8751. }
  8752. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  8753. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  8754. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  8755. TargetEnum->getDecl()->hasNameForLinkage() &&
  8756. SourceEnum != TargetEnum) {
  8757. if (S.SourceMgr.isInSystemMacro(CC))
  8758. return;
  8759. return DiagnoseImpCast(S, E, SourceType, T, CC,
  8760. diag::warn_impcast_different_enum_types);
  8761. }
  8762. }
  8763. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  8764. SourceLocation CC, QualType T);
  8765. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  8766. SourceLocation CC, bool &ICContext) {
  8767. E = E->IgnoreParenImpCasts();
  8768. if (isa<ConditionalOperator>(E))
  8769. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  8770. AnalyzeImplicitConversions(S, E, CC);
  8771. if (E->getType() != T)
  8772. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  8773. }
  8774. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  8775. SourceLocation CC, QualType T) {
  8776. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  8777. bool Suspicious = false;
  8778. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  8779. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  8780. // If -Wconversion would have warned about either of the candidates
  8781. // for a signedness conversion to the context type...
  8782. if (!Suspicious) return;
  8783. // ...but it's currently ignored...
  8784. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  8785. return;
  8786. // ...then check whether it would have warned about either of the
  8787. // candidates for a signedness conversion to the condition type.
  8788. if (E->getType() == T) return;
  8789. Suspicious = false;
  8790. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  8791. E->getType(), CC, &Suspicious);
  8792. if (!Suspicious)
  8793. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  8794. E->getType(), CC, &Suspicious);
  8795. }
  8796. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  8797. /// Input argument E is a logical expression.
  8798. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  8799. if (S.getLangOpts().Bool)
  8800. return;
  8801. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  8802. }
  8803. /// AnalyzeImplicitConversions - Find and report any interesting
  8804. /// implicit conversions in the given expression. There are a couple
  8805. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  8806. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
  8807. SourceLocation CC) {
  8808. QualType T = OrigE->getType();
  8809. Expr *E = OrigE->IgnoreParenImpCasts();
  8810. if (E->isTypeDependent() || E->isValueDependent())
  8811. return;
  8812. // For conditional operators, we analyze the arguments as if they
  8813. // were being fed directly into the output.
  8814. if (isa<ConditionalOperator>(E)) {
  8815. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  8816. CheckConditionalOperator(S, CO, CC, T);
  8817. return;
  8818. }
  8819. // Check implicit argument conversions for function calls.
  8820. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  8821. CheckImplicitArgumentConversions(S, Call, CC);
  8822. // Go ahead and check any implicit conversions we might have skipped.
  8823. // The non-canonical typecheck is just an optimization;
  8824. // CheckImplicitConversion will filter out dead implicit conversions.
  8825. if (E->getType() != T)
  8826. CheckImplicitConversion(S, E, T, CC);
  8827. // Now continue drilling into this expression.
  8828. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  8829. // The bound subexpressions in a PseudoObjectExpr are not reachable
  8830. // as transitive children.
  8831. // FIXME: Use a more uniform representation for this.
  8832. for (auto *SE : POE->semantics())
  8833. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  8834. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  8835. }
  8836. // Skip past explicit casts.
  8837. if (isa<ExplicitCastExpr>(E)) {
  8838. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  8839. return AnalyzeImplicitConversions(S, E, CC);
  8840. }
  8841. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  8842. // Do a somewhat different check with comparison operators.
  8843. if (BO->isComparisonOp())
  8844. return AnalyzeComparison(S, BO);
  8845. // And with simple assignments.
  8846. if (BO->getOpcode() == BO_Assign)
  8847. return AnalyzeAssignment(S, BO);
  8848. // And with compound assignments.
  8849. if (BO->isAssignmentOp())
  8850. return AnalyzeCompoundAssignment(S, BO);
  8851. }
  8852. // These break the otherwise-useful invariant below. Fortunately,
  8853. // we don't really need to recurse into them, because any internal
  8854. // expressions should have been analyzed already when they were
  8855. // built into statements.
  8856. if (isa<StmtExpr>(E)) return;
  8857. // Don't descend into unevaluated contexts.
  8858. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  8859. // Now just recurse over the expression's children.
  8860. CC = E->getExprLoc();
  8861. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  8862. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  8863. for (Stmt *SubStmt : E->children()) {
  8864. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  8865. if (!ChildExpr)
  8866. continue;
  8867. if (IsLogicalAndOperator &&
  8868. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  8869. // Ignore checking string literals that are in logical and operators.
  8870. // This is a common pattern for asserts.
  8871. continue;
  8872. AnalyzeImplicitConversions(S, ChildExpr, CC);
  8873. }
  8874. if (BO && BO->isLogicalOp()) {
  8875. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  8876. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  8877. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  8878. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  8879. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  8880. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  8881. }
  8882. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
  8883. if (U->getOpcode() == UO_LNot)
  8884. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  8885. }
  8886. /// Diagnose integer type and any valid implicit conversion to it.
  8887. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  8888. // Taking into account implicit conversions,
  8889. // allow any integer.
  8890. if (!E->getType()->isIntegerType()) {
  8891. S.Diag(E->getLocStart(),
  8892. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  8893. return true;
  8894. }
  8895. // Potentially emit standard warnings for implicit conversions if enabled
  8896. // using -Wconversion.
  8897. CheckImplicitConversion(S, E, IntT, E->getLocStart());
  8898. return false;
  8899. }
  8900. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  8901. // Returns true when emitting a warning about taking the address of a reference.
  8902. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  8903. const PartialDiagnostic &PD) {
  8904. E = E->IgnoreParenImpCasts();
  8905. const FunctionDecl *FD = nullptr;
  8906. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  8907. if (!DRE->getDecl()->getType()->isReferenceType())
  8908. return false;
  8909. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  8910. if (!M->getMemberDecl()->getType()->isReferenceType())
  8911. return false;
  8912. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  8913. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  8914. return false;
  8915. FD = Call->getDirectCallee();
  8916. } else {
  8917. return false;
  8918. }
  8919. SemaRef.Diag(E->getExprLoc(), PD);
  8920. // If possible, point to location of function.
  8921. if (FD) {
  8922. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  8923. }
  8924. return true;
  8925. }
  8926. // Returns true if the SourceLocation is expanded from any macro body.
  8927. // Returns false if the SourceLocation is invalid, is from not in a macro
  8928. // expansion, or is from expanded from a top-level macro argument.
  8929. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  8930. if (Loc.isInvalid())
  8931. return false;
  8932. while (Loc.isMacroID()) {
  8933. if (SM.isMacroBodyExpansion(Loc))
  8934. return true;
  8935. Loc = SM.getImmediateMacroCallerLoc(Loc);
  8936. }
  8937. return false;
  8938. }
  8939. /// \brief Diagnose pointers that are always non-null.
  8940. /// \param E the expression containing the pointer
  8941. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  8942. /// compared to a null pointer
  8943. /// \param IsEqual True when the comparison is equal to a null pointer
  8944. /// \param Range Extra SourceRange to highlight in the diagnostic
  8945. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  8946. Expr::NullPointerConstantKind NullKind,
  8947. bool IsEqual, SourceRange Range) {
  8948. if (!E)
  8949. return;
  8950. // Don't warn inside macros.
  8951. if (E->getExprLoc().isMacroID()) {
  8952. const SourceManager &SM = getSourceManager();
  8953. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  8954. IsInAnyMacroBody(SM, Range.getBegin()))
  8955. return;
  8956. }
  8957. E = E->IgnoreImpCasts();
  8958. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  8959. if (isa<CXXThisExpr>(E)) {
  8960. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  8961. : diag::warn_this_bool_conversion;
  8962. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  8963. return;
  8964. }
  8965. bool IsAddressOf = false;
  8966. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  8967. if (UO->getOpcode() != UO_AddrOf)
  8968. return;
  8969. IsAddressOf = true;
  8970. E = UO->getSubExpr();
  8971. }
  8972. if (IsAddressOf) {
  8973. unsigned DiagID = IsCompare
  8974. ? diag::warn_address_of_reference_null_compare
  8975. : diag::warn_address_of_reference_bool_conversion;
  8976. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  8977. << IsEqual;
  8978. if (CheckForReference(*this, E, PD)) {
  8979. return;
  8980. }
  8981. }
  8982. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  8983. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  8984. std::string Str;
  8985. llvm::raw_string_ostream S(Str);
  8986. E->printPretty(S, nullptr, getPrintingPolicy());
  8987. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  8988. : diag::warn_cast_nonnull_to_bool;
  8989. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  8990. << E->getSourceRange() << Range << IsEqual;
  8991. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  8992. };
  8993. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  8994. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  8995. if (auto *Callee = Call->getDirectCallee()) {
  8996. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  8997. ComplainAboutNonnullParamOrCall(A);
  8998. return;
  8999. }
  9000. }
  9001. }
  9002. // Expect to find a single Decl. Skip anything more complicated.
  9003. ValueDecl *D = nullptr;
  9004. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  9005. D = R->getDecl();
  9006. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  9007. D = M->getMemberDecl();
  9008. }
  9009. // Weak Decls can be null.
  9010. if (!D || D->isWeak())
  9011. return;
  9012. // Check for parameter decl with nonnull attribute
  9013. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  9014. if (getCurFunction() &&
  9015. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  9016. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  9017. ComplainAboutNonnullParamOrCall(A);
  9018. return;
  9019. }
  9020. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  9021. auto ParamIter = llvm::find(FD->parameters(), PV);
  9022. assert(ParamIter != FD->param_end());
  9023. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  9024. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  9025. if (!NonNull->args_size()) {
  9026. ComplainAboutNonnullParamOrCall(NonNull);
  9027. return;
  9028. }
  9029. for (const ParamIdx &ArgNo : NonNull->args()) {
  9030. if (ArgNo.getASTIndex() == ParamNo) {
  9031. ComplainAboutNonnullParamOrCall(NonNull);
  9032. return;
  9033. }
  9034. }
  9035. }
  9036. }
  9037. }
  9038. }
  9039. QualType T = D->getType();
  9040. const bool IsArray = T->isArrayType();
  9041. const bool IsFunction = T->isFunctionType();
  9042. // Address of function is used to silence the function warning.
  9043. if (IsAddressOf && IsFunction) {
  9044. return;
  9045. }
  9046. // Found nothing.
  9047. if (!IsAddressOf && !IsFunction && !IsArray)
  9048. return;
  9049. // Pretty print the expression for the diagnostic.
  9050. std::string Str;
  9051. llvm::raw_string_ostream S(Str);
  9052. E->printPretty(S, nullptr, getPrintingPolicy());
  9053. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  9054. : diag::warn_impcast_pointer_to_bool;
  9055. enum {
  9056. AddressOf,
  9057. FunctionPointer,
  9058. ArrayPointer
  9059. } DiagType;
  9060. if (IsAddressOf)
  9061. DiagType = AddressOf;
  9062. else if (IsFunction)
  9063. DiagType = FunctionPointer;
  9064. else if (IsArray)
  9065. DiagType = ArrayPointer;
  9066. else
  9067. llvm_unreachable("Could not determine diagnostic.");
  9068. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  9069. << Range << IsEqual;
  9070. if (!IsFunction)
  9071. return;
  9072. // Suggest '&' to silence the function warning.
  9073. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  9074. << FixItHint::CreateInsertion(E->getLocStart(), "&");
  9075. // Check to see if '()' fixit should be emitted.
  9076. QualType ReturnType;
  9077. UnresolvedSet<4> NonTemplateOverloads;
  9078. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  9079. if (ReturnType.isNull())
  9080. return;
  9081. if (IsCompare) {
  9082. // There are two cases here. If there is null constant, the only suggest
  9083. // for a pointer return type. If the null is 0, then suggest if the return
  9084. // type is a pointer or an integer type.
  9085. if (!ReturnType->isPointerType()) {
  9086. if (NullKind == Expr::NPCK_ZeroExpression ||
  9087. NullKind == Expr::NPCK_ZeroLiteral) {
  9088. if (!ReturnType->isIntegerType())
  9089. return;
  9090. } else {
  9091. return;
  9092. }
  9093. }
  9094. } else { // !IsCompare
  9095. // For function to bool, only suggest if the function pointer has bool
  9096. // return type.
  9097. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  9098. return;
  9099. }
  9100. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  9101. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
  9102. }
  9103. /// Diagnoses "dangerous" implicit conversions within the given
  9104. /// expression (which is a full expression). Implements -Wconversion
  9105. /// and -Wsign-compare.
  9106. ///
  9107. /// \param CC the "context" location of the implicit conversion, i.e.
  9108. /// the most location of the syntactic entity requiring the implicit
  9109. /// conversion
  9110. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  9111. // Don't diagnose in unevaluated contexts.
  9112. if (isUnevaluatedContext())
  9113. return;
  9114. // Don't diagnose for value- or type-dependent expressions.
  9115. if (E->isTypeDependent() || E->isValueDependent())
  9116. return;
  9117. // Check for array bounds violations in cases where the check isn't triggered
  9118. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  9119. // ArraySubscriptExpr is on the RHS of a variable initialization.
  9120. CheckArrayAccess(E);
  9121. // This is not the right CC for (e.g.) a variable initialization.
  9122. AnalyzeImplicitConversions(*this, E, CC);
  9123. }
  9124. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  9125. /// Input argument E is a logical expression.
  9126. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  9127. ::CheckBoolLikeConversion(*this, E, CC);
  9128. }
  9129. /// Diagnose when expression is an integer constant expression and its evaluation
  9130. /// results in integer overflow
  9131. void Sema::CheckForIntOverflow (Expr *E) {
  9132. // Use a work list to deal with nested struct initializers.
  9133. SmallVector<Expr *, 2> Exprs(1, E);
  9134. do {
  9135. Expr *OriginalE = Exprs.pop_back_val();
  9136. Expr *E = OriginalE->IgnoreParenCasts();
  9137. if (isa<BinaryOperator>(E)) {
  9138. E->EvaluateForOverflow(Context);
  9139. continue;
  9140. }
  9141. if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
  9142. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  9143. else if (isa<ObjCBoxedExpr>(OriginalE))
  9144. E->EvaluateForOverflow(Context);
  9145. else if (auto Call = dyn_cast<CallExpr>(E))
  9146. Exprs.append(Call->arg_begin(), Call->arg_end());
  9147. else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
  9148. Exprs.append(Message->arg_begin(), Message->arg_end());
  9149. } while (!Exprs.empty());
  9150. }
  9151. namespace {
  9152. /// \brief Visitor for expressions which looks for unsequenced operations on the
  9153. /// same object.
  9154. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  9155. using Base = EvaluatedExprVisitor<SequenceChecker>;
  9156. /// \brief A tree of sequenced regions within an expression. Two regions are
  9157. /// unsequenced if one is an ancestor or a descendent of the other. When we
  9158. /// finish processing an expression with sequencing, such as a comma
  9159. /// expression, we fold its tree nodes into its parent, since they are
  9160. /// unsequenced with respect to nodes we will visit later.
  9161. class SequenceTree {
  9162. struct Value {
  9163. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  9164. unsigned Parent : 31;
  9165. unsigned Merged : 1;
  9166. };
  9167. SmallVector<Value, 8> Values;
  9168. public:
  9169. /// \brief A region within an expression which may be sequenced with respect
  9170. /// to some other region.
  9171. class Seq {
  9172. friend class SequenceTree;
  9173. unsigned Index = 0;
  9174. explicit Seq(unsigned N) : Index(N) {}
  9175. public:
  9176. Seq() = default;
  9177. };
  9178. SequenceTree() { Values.push_back(Value(0)); }
  9179. Seq root() const { return Seq(0); }
  9180. /// \brief Create a new sequence of operations, which is an unsequenced
  9181. /// subset of \p Parent. This sequence of operations is sequenced with
  9182. /// respect to other children of \p Parent.
  9183. Seq allocate(Seq Parent) {
  9184. Values.push_back(Value(Parent.Index));
  9185. return Seq(Values.size() - 1);
  9186. }
  9187. /// \brief Merge a sequence of operations into its parent.
  9188. void merge(Seq S) {
  9189. Values[S.Index].Merged = true;
  9190. }
  9191. /// \brief Determine whether two operations are unsequenced. This operation
  9192. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  9193. /// should have been merged into its parent as appropriate.
  9194. bool isUnsequenced(Seq Cur, Seq Old) {
  9195. unsigned C = representative(Cur.Index);
  9196. unsigned Target = representative(Old.Index);
  9197. while (C >= Target) {
  9198. if (C == Target)
  9199. return true;
  9200. C = Values[C].Parent;
  9201. }
  9202. return false;
  9203. }
  9204. private:
  9205. /// \brief Pick a representative for a sequence.
  9206. unsigned representative(unsigned K) {
  9207. if (Values[K].Merged)
  9208. // Perform path compression as we go.
  9209. return Values[K].Parent = representative(Values[K].Parent);
  9210. return K;
  9211. }
  9212. };
  9213. /// An object for which we can track unsequenced uses.
  9214. using Object = NamedDecl *;
  9215. /// Different flavors of object usage which we track. We only track the
  9216. /// least-sequenced usage of each kind.
  9217. enum UsageKind {
  9218. /// A read of an object. Multiple unsequenced reads are OK.
  9219. UK_Use,
  9220. /// A modification of an object which is sequenced before the value
  9221. /// computation of the expression, such as ++n in C++.
  9222. UK_ModAsValue,
  9223. /// A modification of an object which is not sequenced before the value
  9224. /// computation of the expression, such as n++.
  9225. UK_ModAsSideEffect,
  9226. UK_Count = UK_ModAsSideEffect + 1
  9227. };
  9228. struct Usage {
  9229. Expr *Use = nullptr;
  9230. SequenceTree::Seq Seq;
  9231. Usage() = default;
  9232. };
  9233. struct UsageInfo {
  9234. Usage Uses[UK_Count];
  9235. /// Have we issued a diagnostic for this variable already?
  9236. bool Diagnosed = false;
  9237. UsageInfo() = default;
  9238. };
  9239. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  9240. Sema &SemaRef;
  9241. /// Sequenced regions within the expression.
  9242. SequenceTree Tree;
  9243. /// Declaration modifications and references which we have seen.
  9244. UsageInfoMap UsageMap;
  9245. /// The region we are currently within.
  9246. SequenceTree::Seq Region;
  9247. /// Filled in with declarations which were modified as a side-effect
  9248. /// (that is, post-increment operations).
  9249. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  9250. /// Expressions to check later. We defer checking these to reduce
  9251. /// stack usage.
  9252. SmallVectorImpl<Expr *> &WorkList;
  9253. /// RAII object wrapping the visitation of a sequenced subexpression of an
  9254. /// expression. At the end of this process, the side-effects of the evaluation
  9255. /// become sequenced with respect to the value computation of the result, so
  9256. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  9257. /// UK_ModAsValue.
  9258. struct SequencedSubexpression {
  9259. SequencedSubexpression(SequenceChecker &Self)
  9260. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  9261. Self.ModAsSideEffect = &ModAsSideEffect;
  9262. }
  9263. ~SequencedSubexpression() {
  9264. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  9265. UsageInfo &U = Self.UsageMap[M.first];
  9266. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  9267. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  9268. SideEffectUsage = M.second;
  9269. }
  9270. Self.ModAsSideEffect = OldModAsSideEffect;
  9271. }
  9272. SequenceChecker &Self;
  9273. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  9274. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  9275. };
  9276. /// RAII object wrapping the visitation of a subexpression which we might
  9277. /// choose to evaluate as a constant. If any subexpression is evaluated and
  9278. /// found to be non-constant, this allows us to suppress the evaluation of
  9279. /// the outer expression.
  9280. class EvaluationTracker {
  9281. public:
  9282. EvaluationTracker(SequenceChecker &Self)
  9283. : Self(Self), Prev(Self.EvalTracker) {
  9284. Self.EvalTracker = this;
  9285. }
  9286. ~EvaluationTracker() {
  9287. Self.EvalTracker = Prev;
  9288. if (Prev)
  9289. Prev->EvalOK &= EvalOK;
  9290. }
  9291. bool evaluate(const Expr *E, bool &Result) {
  9292. if (!EvalOK || E->isValueDependent())
  9293. return false;
  9294. EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
  9295. return EvalOK;
  9296. }
  9297. private:
  9298. SequenceChecker &Self;
  9299. EvaluationTracker *Prev;
  9300. bool EvalOK = true;
  9301. } *EvalTracker = nullptr;
  9302. /// \brief Find the object which is produced by the specified expression,
  9303. /// if any.
  9304. Object getObject(Expr *E, bool Mod) const {
  9305. E = E->IgnoreParenCasts();
  9306. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  9307. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  9308. return getObject(UO->getSubExpr(), Mod);
  9309. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9310. if (BO->getOpcode() == BO_Comma)
  9311. return getObject(BO->getRHS(), Mod);
  9312. if (Mod && BO->isAssignmentOp())
  9313. return getObject(BO->getLHS(), Mod);
  9314. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  9315. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  9316. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  9317. return ME->getMemberDecl();
  9318. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  9319. // FIXME: If this is a reference, map through to its value.
  9320. return DRE->getDecl();
  9321. return nullptr;
  9322. }
  9323. /// \brief Note that an object was modified or used by an expression.
  9324. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  9325. Usage &U = UI.Uses[UK];
  9326. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  9327. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  9328. ModAsSideEffect->push_back(std::make_pair(O, U));
  9329. U.Use = Ref;
  9330. U.Seq = Region;
  9331. }
  9332. }
  9333. /// \brief Check whether a modification or use conflicts with a prior usage.
  9334. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  9335. bool IsModMod) {
  9336. if (UI.Diagnosed)
  9337. return;
  9338. const Usage &U = UI.Uses[OtherKind];
  9339. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  9340. return;
  9341. Expr *Mod = U.Use;
  9342. Expr *ModOrUse = Ref;
  9343. if (OtherKind == UK_Use)
  9344. std::swap(Mod, ModOrUse);
  9345. SemaRef.Diag(Mod->getExprLoc(),
  9346. IsModMod ? diag::warn_unsequenced_mod_mod
  9347. : diag::warn_unsequenced_mod_use)
  9348. << O << SourceRange(ModOrUse->getExprLoc());
  9349. UI.Diagnosed = true;
  9350. }
  9351. void notePreUse(Object O, Expr *Use) {
  9352. UsageInfo &U = UsageMap[O];
  9353. // Uses conflict with other modifications.
  9354. checkUsage(O, U, Use, UK_ModAsValue, false);
  9355. }
  9356. void notePostUse(Object O, Expr *Use) {
  9357. UsageInfo &U = UsageMap[O];
  9358. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  9359. addUsage(U, O, Use, UK_Use);
  9360. }
  9361. void notePreMod(Object O, Expr *Mod) {
  9362. UsageInfo &U = UsageMap[O];
  9363. // Modifications conflict with other modifications and with uses.
  9364. checkUsage(O, U, Mod, UK_ModAsValue, true);
  9365. checkUsage(O, U, Mod, UK_Use, false);
  9366. }
  9367. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  9368. UsageInfo &U = UsageMap[O];
  9369. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  9370. addUsage(U, O, Use, UK);
  9371. }
  9372. public:
  9373. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  9374. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  9375. Visit(E);
  9376. }
  9377. void VisitStmt(Stmt *S) {
  9378. // Skip all statements which aren't expressions for now.
  9379. }
  9380. void VisitExpr(Expr *E) {
  9381. // By default, just recurse to evaluated subexpressions.
  9382. Base::VisitStmt(E);
  9383. }
  9384. void VisitCastExpr(CastExpr *E) {
  9385. Object O = Object();
  9386. if (E->getCastKind() == CK_LValueToRValue)
  9387. O = getObject(E->getSubExpr(), false);
  9388. if (O)
  9389. notePreUse(O, E);
  9390. VisitExpr(E);
  9391. if (O)
  9392. notePostUse(O, E);
  9393. }
  9394. void VisitBinComma(BinaryOperator *BO) {
  9395. // C++11 [expr.comma]p1:
  9396. // Every value computation and side effect associated with the left
  9397. // expression is sequenced before every value computation and side
  9398. // effect associated with the right expression.
  9399. SequenceTree::Seq LHS = Tree.allocate(Region);
  9400. SequenceTree::Seq RHS = Tree.allocate(Region);
  9401. SequenceTree::Seq OldRegion = Region;
  9402. {
  9403. SequencedSubexpression SeqLHS(*this);
  9404. Region = LHS;
  9405. Visit(BO->getLHS());
  9406. }
  9407. Region = RHS;
  9408. Visit(BO->getRHS());
  9409. Region = OldRegion;
  9410. // Forget that LHS and RHS are sequenced. They are both unsequenced
  9411. // with respect to other stuff.
  9412. Tree.merge(LHS);
  9413. Tree.merge(RHS);
  9414. }
  9415. void VisitBinAssign(BinaryOperator *BO) {
  9416. // The modification is sequenced after the value computation of the LHS
  9417. // and RHS, so check it before inspecting the operands and update the
  9418. // map afterwards.
  9419. Object O = getObject(BO->getLHS(), true);
  9420. if (!O)
  9421. return VisitExpr(BO);
  9422. notePreMod(O, BO);
  9423. // C++11 [expr.ass]p7:
  9424. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  9425. // only once.
  9426. //
  9427. // Therefore, for a compound assignment operator, O is considered used
  9428. // everywhere except within the evaluation of E1 itself.
  9429. if (isa<CompoundAssignOperator>(BO))
  9430. notePreUse(O, BO);
  9431. Visit(BO->getLHS());
  9432. if (isa<CompoundAssignOperator>(BO))
  9433. notePostUse(O, BO);
  9434. Visit(BO->getRHS());
  9435. // C++11 [expr.ass]p1:
  9436. // the assignment is sequenced [...] before the value computation of the
  9437. // assignment expression.
  9438. // C11 6.5.16/3 has no such rule.
  9439. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  9440. : UK_ModAsSideEffect);
  9441. }
  9442. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  9443. VisitBinAssign(CAO);
  9444. }
  9445. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  9446. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  9447. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  9448. Object O = getObject(UO->getSubExpr(), true);
  9449. if (!O)
  9450. return VisitExpr(UO);
  9451. notePreMod(O, UO);
  9452. Visit(UO->getSubExpr());
  9453. // C++11 [expr.pre.incr]p1:
  9454. // the expression ++x is equivalent to x+=1
  9455. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  9456. : UK_ModAsSideEffect);
  9457. }
  9458. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  9459. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  9460. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  9461. Object O = getObject(UO->getSubExpr(), true);
  9462. if (!O)
  9463. return VisitExpr(UO);
  9464. notePreMod(O, UO);
  9465. Visit(UO->getSubExpr());
  9466. notePostMod(O, UO, UK_ModAsSideEffect);
  9467. }
  9468. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  9469. void VisitBinLOr(BinaryOperator *BO) {
  9470. // The side-effects of the LHS of an '&&' are sequenced before the
  9471. // value computation of the RHS, and hence before the value computation
  9472. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  9473. // as if they were unconditionally sequenced.
  9474. EvaluationTracker Eval(*this);
  9475. {
  9476. SequencedSubexpression Sequenced(*this);
  9477. Visit(BO->getLHS());
  9478. }
  9479. bool Result;
  9480. if (Eval.evaluate(BO->getLHS(), Result)) {
  9481. if (!Result)
  9482. Visit(BO->getRHS());
  9483. } else {
  9484. // Check for unsequenced operations in the RHS, treating it as an
  9485. // entirely separate evaluation.
  9486. //
  9487. // FIXME: If there are operations in the RHS which are unsequenced
  9488. // with respect to operations outside the RHS, and those operations
  9489. // are unconditionally evaluated, diagnose them.
  9490. WorkList.push_back(BO->getRHS());
  9491. }
  9492. }
  9493. void VisitBinLAnd(BinaryOperator *BO) {
  9494. EvaluationTracker Eval(*this);
  9495. {
  9496. SequencedSubexpression Sequenced(*this);
  9497. Visit(BO->getLHS());
  9498. }
  9499. bool Result;
  9500. if (Eval.evaluate(BO->getLHS(), Result)) {
  9501. if (Result)
  9502. Visit(BO->getRHS());
  9503. } else {
  9504. WorkList.push_back(BO->getRHS());
  9505. }
  9506. }
  9507. // Only visit the condition, unless we can be sure which subexpression will
  9508. // be chosen.
  9509. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  9510. EvaluationTracker Eval(*this);
  9511. {
  9512. SequencedSubexpression Sequenced(*this);
  9513. Visit(CO->getCond());
  9514. }
  9515. bool Result;
  9516. if (Eval.evaluate(CO->getCond(), Result))
  9517. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  9518. else {
  9519. WorkList.push_back(CO->getTrueExpr());
  9520. WorkList.push_back(CO->getFalseExpr());
  9521. }
  9522. }
  9523. void VisitCallExpr(CallExpr *CE) {
  9524. // C++11 [intro.execution]p15:
  9525. // When calling a function [...], every value computation and side effect
  9526. // associated with any argument expression, or with the postfix expression
  9527. // designating the called function, is sequenced before execution of every
  9528. // expression or statement in the body of the function [and thus before
  9529. // the value computation of its result].
  9530. SequencedSubexpression Sequenced(*this);
  9531. Base::VisitCallExpr(CE);
  9532. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  9533. }
  9534. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  9535. // This is a call, so all subexpressions are sequenced before the result.
  9536. SequencedSubexpression Sequenced(*this);
  9537. if (!CCE->isListInitialization())
  9538. return VisitExpr(CCE);
  9539. // In C++11, list initializations are sequenced.
  9540. SmallVector<SequenceTree::Seq, 32> Elts;
  9541. SequenceTree::Seq Parent = Region;
  9542. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  9543. E = CCE->arg_end();
  9544. I != E; ++I) {
  9545. Region = Tree.allocate(Parent);
  9546. Elts.push_back(Region);
  9547. Visit(*I);
  9548. }
  9549. // Forget that the initializers are sequenced.
  9550. Region = Parent;
  9551. for (unsigned I = 0; I < Elts.size(); ++I)
  9552. Tree.merge(Elts[I]);
  9553. }
  9554. void VisitInitListExpr(InitListExpr *ILE) {
  9555. if (!SemaRef.getLangOpts().CPlusPlus11)
  9556. return VisitExpr(ILE);
  9557. // In C++11, list initializations are sequenced.
  9558. SmallVector<SequenceTree::Seq, 32> Elts;
  9559. SequenceTree::Seq Parent = Region;
  9560. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  9561. Expr *E = ILE->getInit(I);
  9562. if (!E) continue;
  9563. Region = Tree.allocate(Parent);
  9564. Elts.push_back(Region);
  9565. Visit(E);
  9566. }
  9567. // Forget that the initializers are sequenced.
  9568. Region = Parent;
  9569. for (unsigned I = 0; I < Elts.size(); ++I)
  9570. Tree.merge(Elts[I]);
  9571. }
  9572. };
  9573. } // namespace
  9574. void Sema::CheckUnsequencedOperations(Expr *E) {
  9575. SmallVector<Expr *, 8> WorkList;
  9576. WorkList.push_back(E);
  9577. while (!WorkList.empty()) {
  9578. Expr *Item = WorkList.pop_back_val();
  9579. SequenceChecker(*this, Item, WorkList);
  9580. }
  9581. }
  9582. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  9583. bool IsConstexpr) {
  9584. CheckImplicitConversions(E, CheckLoc);
  9585. if (!E->isInstantiationDependent())
  9586. CheckUnsequencedOperations(E);
  9587. if (!IsConstexpr && !E->isValueDependent())
  9588. CheckForIntOverflow(E);
  9589. DiagnoseMisalignedMembers();
  9590. }
  9591. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  9592. FieldDecl *BitField,
  9593. Expr *Init) {
  9594. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  9595. }
  9596. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  9597. SourceLocation Loc) {
  9598. if (!PType->isVariablyModifiedType())
  9599. return;
  9600. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  9601. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  9602. return;
  9603. }
  9604. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  9605. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  9606. return;
  9607. }
  9608. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  9609. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  9610. return;
  9611. }
  9612. const ArrayType *AT = S.Context.getAsArrayType(PType);
  9613. if (!AT)
  9614. return;
  9615. if (AT->getSizeModifier() != ArrayType::Star) {
  9616. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  9617. return;
  9618. }
  9619. S.Diag(Loc, diag::err_array_star_in_function_definition);
  9620. }
  9621. /// CheckParmsForFunctionDef - Check that the parameters of the given
  9622. /// function are appropriate for the definition of a function. This
  9623. /// takes care of any checks that cannot be performed on the
  9624. /// declaration itself, e.g., that the types of each of the function
  9625. /// parameters are complete.
  9626. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  9627. bool CheckParameterNames) {
  9628. bool HasInvalidParm = false;
  9629. for (ParmVarDecl *Param : Parameters) {
  9630. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  9631. // function declarator that is part of a function definition of
  9632. // that function shall not have incomplete type.
  9633. //
  9634. // This is also C++ [dcl.fct]p6.
  9635. if (!Param->isInvalidDecl() &&
  9636. RequireCompleteType(Param->getLocation(), Param->getType(),
  9637. diag::err_typecheck_decl_incomplete_type)) {
  9638. Param->setInvalidDecl();
  9639. HasInvalidParm = true;
  9640. }
  9641. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  9642. // declaration of each parameter shall include an identifier.
  9643. if (CheckParameterNames &&
  9644. Param->getIdentifier() == nullptr &&
  9645. !Param->isImplicit() &&
  9646. !getLangOpts().CPlusPlus)
  9647. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  9648. // C99 6.7.5.3p12:
  9649. // If the function declarator is not part of a definition of that
  9650. // function, parameters may have incomplete type and may use the [*]
  9651. // notation in their sequences of declarator specifiers to specify
  9652. // variable length array types.
  9653. QualType PType = Param->getOriginalType();
  9654. // FIXME: This diagnostic should point the '[*]' if source-location
  9655. // information is added for it.
  9656. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  9657. // If the parameter is a c++ class type and it has to be destructed in the
  9658. // callee function, declare the destructor so that it can be called by the
  9659. // callee function. Do not perform any direct access check on the dtor here.
  9660. if (!Param->isInvalidDecl()) {
  9661. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  9662. if (!ClassDecl->isInvalidDecl() &&
  9663. !ClassDecl->hasIrrelevantDestructor() &&
  9664. !ClassDecl->isDependentContext() &&
  9665. Context.isParamDestroyedInCallee(Param->getType())) {
  9666. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  9667. MarkFunctionReferenced(Param->getLocation(), Destructor);
  9668. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  9669. }
  9670. }
  9671. }
  9672. // Parameters with the pass_object_size attribute only need to be marked
  9673. // constant at function definitions. Because we lack information about
  9674. // whether we're on a declaration or definition when we're instantiating the
  9675. // attribute, we need to check for constness here.
  9676. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  9677. if (!Param->getType().isConstQualified())
  9678. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  9679. << Attr->getSpelling() << 1;
  9680. }
  9681. return HasInvalidParm;
  9682. }
  9683. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  9684. /// or MemberExpr.
  9685. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  9686. ASTContext &Context) {
  9687. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  9688. return Context.getDeclAlign(DRE->getDecl());
  9689. if (const auto *ME = dyn_cast<MemberExpr>(E))
  9690. return Context.getDeclAlign(ME->getMemberDecl());
  9691. return TypeAlign;
  9692. }
  9693. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  9694. /// pointer cast increases the alignment requirements.
  9695. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  9696. // This is actually a lot of work to potentially be doing on every
  9697. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  9698. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  9699. return;
  9700. // Ignore dependent types.
  9701. if (T->isDependentType() || Op->getType()->isDependentType())
  9702. return;
  9703. // Require that the destination be a pointer type.
  9704. const PointerType *DestPtr = T->getAs<PointerType>();
  9705. if (!DestPtr) return;
  9706. // If the destination has alignment 1, we're done.
  9707. QualType DestPointee = DestPtr->getPointeeType();
  9708. if (DestPointee->isIncompleteType()) return;
  9709. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  9710. if (DestAlign.isOne()) return;
  9711. // Require that the source be a pointer type.
  9712. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  9713. if (!SrcPtr) return;
  9714. QualType SrcPointee = SrcPtr->getPointeeType();
  9715. // Whitelist casts from cv void*. We already implicitly
  9716. // whitelisted casts to cv void*, since they have alignment 1.
  9717. // Also whitelist casts involving incomplete types, which implicitly
  9718. // includes 'void'.
  9719. if (SrcPointee->isIncompleteType()) return;
  9720. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  9721. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  9722. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  9723. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  9724. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  9725. if (UO->getOpcode() == UO_AddrOf)
  9726. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  9727. }
  9728. if (SrcAlign >= DestAlign) return;
  9729. Diag(TRange.getBegin(), diag::warn_cast_align)
  9730. << Op->getType() << T
  9731. << static_cast<unsigned>(SrcAlign.getQuantity())
  9732. << static_cast<unsigned>(DestAlign.getQuantity())
  9733. << TRange << Op->getSourceRange();
  9734. }
  9735. /// \brief Check whether this array fits the idiom of a size-one tail padded
  9736. /// array member of a struct.
  9737. ///
  9738. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  9739. /// commonly used to emulate flexible arrays in C89 code.
  9740. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  9741. const NamedDecl *ND) {
  9742. if (Size != 1 || !ND) return false;
  9743. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  9744. if (!FD) return false;
  9745. // Don't consider sizes resulting from macro expansions or template argument
  9746. // substitution to form C89 tail-padded arrays.
  9747. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  9748. while (TInfo) {
  9749. TypeLoc TL = TInfo->getTypeLoc();
  9750. // Look through typedefs.
  9751. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  9752. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  9753. TInfo = TDL->getTypeSourceInfo();
  9754. continue;
  9755. }
  9756. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  9757. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  9758. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  9759. return false;
  9760. }
  9761. break;
  9762. }
  9763. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  9764. if (!RD) return false;
  9765. if (RD->isUnion()) return false;
  9766. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  9767. if (!CRD->isStandardLayout()) return false;
  9768. }
  9769. // See if this is the last field decl in the record.
  9770. const Decl *D = FD;
  9771. while ((D = D->getNextDeclInContext()))
  9772. if (isa<FieldDecl>(D))
  9773. return false;
  9774. return true;
  9775. }
  9776. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  9777. const ArraySubscriptExpr *ASE,
  9778. bool AllowOnePastEnd, bool IndexNegated) {
  9779. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  9780. if (IndexExpr->isValueDependent())
  9781. return;
  9782. const Type *EffectiveType =
  9783. BaseExpr->getType()->getPointeeOrArrayElementType();
  9784. BaseExpr = BaseExpr->IgnoreParenCasts();
  9785. const ConstantArrayType *ArrayTy =
  9786. Context.getAsConstantArrayType(BaseExpr->getType());
  9787. if (!ArrayTy)
  9788. return;
  9789. llvm::APSInt index;
  9790. if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
  9791. return;
  9792. if (IndexNegated)
  9793. index = -index;
  9794. const NamedDecl *ND = nullptr;
  9795. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  9796. ND = DRE->getDecl();
  9797. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  9798. ND = ME->getMemberDecl();
  9799. if (index.isUnsigned() || !index.isNegative()) {
  9800. llvm::APInt size = ArrayTy->getSize();
  9801. if (!size.isStrictlyPositive())
  9802. return;
  9803. const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
  9804. if (BaseType != EffectiveType) {
  9805. // Make sure we're comparing apples to apples when comparing index to size
  9806. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  9807. uint64_t array_typesize = Context.getTypeSize(BaseType);
  9808. // Handle ptrarith_typesize being zero, such as when casting to void*
  9809. if (!ptrarith_typesize) ptrarith_typesize = 1;
  9810. if (ptrarith_typesize != array_typesize) {
  9811. // There's a cast to a different size type involved
  9812. uint64_t ratio = array_typesize / ptrarith_typesize;
  9813. // TODO: Be smarter about handling cases where array_typesize is not a
  9814. // multiple of ptrarith_typesize
  9815. if (ptrarith_typesize * ratio == array_typesize)
  9816. size *= llvm::APInt(size.getBitWidth(), ratio);
  9817. }
  9818. }
  9819. if (size.getBitWidth() > index.getBitWidth())
  9820. index = index.zext(size.getBitWidth());
  9821. else if (size.getBitWidth() < index.getBitWidth())
  9822. size = size.zext(index.getBitWidth());
  9823. // For array subscripting the index must be less than size, but for pointer
  9824. // arithmetic also allow the index (offset) to be equal to size since
  9825. // computing the next address after the end of the array is legal and
  9826. // commonly done e.g. in C++ iterators and range-based for loops.
  9827. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  9828. return;
  9829. // Also don't warn for arrays of size 1 which are members of some
  9830. // structure. These are often used to approximate flexible arrays in C89
  9831. // code.
  9832. if (IsTailPaddedMemberArray(*this, size, ND))
  9833. return;
  9834. // Suppress the warning if the subscript expression (as identified by the
  9835. // ']' location) and the index expression are both from macro expansions
  9836. // within a system header.
  9837. if (ASE) {
  9838. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  9839. ASE->getRBracketLoc());
  9840. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  9841. SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
  9842. IndexExpr->getLocStart());
  9843. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  9844. return;
  9845. }
  9846. }
  9847. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  9848. if (ASE)
  9849. DiagID = diag::warn_array_index_exceeds_bounds;
  9850. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  9851. PDiag(DiagID) << index.toString(10, true)
  9852. << size.toString(10, true)
  9853. << (unsigned)size.getLimitedValue(~0U)
  9854. << IndexExpr->getSourceRange());
  9855. } else {
  9856. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  9857. if (!ASE) {
  9858. DiagID = diag::warn_ptr_arith_precedes_bounds;
  9859. if (index.isNegative()) index = -index;
  9860. }
  9861. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  9862. PDiag(DiagID) << index.toString(10, true)
  9863. << IndexExpr->getSourceRange());
  9864. }
  9865. if (!ND) {
  9866. // Try harder to find a NamedDecl to point at in the note.
  9867. while (const ArraySubscriptExpr *ASE =
  9868. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  9869. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  9870. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  9871. ND = DRE->getDecl();
  9872. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  9873. ND = ME->getMemberDecl();
  9874. }
  9875. if (ND)
  9876. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  9877. PDiag(diag::note_array_index_out_of_bounds)
  9878. << ND->getDeclName());
  9879. }
  9880. void Sema::CheckArrayAccess(const Expr *expr) {
  9881. int AllowOnePastEnd = 0;
  9882. while (expr) {
  9883. expr = expr->IgnoreParenImpCasts();
  9884. switch (expr->getStmtClass()) {
  9885. case Stmt::ArraySubscriptExprClass: {
  9886. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  9887. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  9888. AllowOnePastEnd > 0);
  9889. expr = ASE->getBase();
  9890. break;
  9891. }
  9892. case Stmt::MemberExprClass: {
  9893. expr = cast<MemberExpr>(expr)->getBase();
  9894. break;
  9895. }
  9896. case Stmt::OMPArraySectionExprClass: {
  9897. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  9898. if (ASE->getLowerBound())
  9899. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  9900. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  9901. return;
  9902. }
  9903. case Stmt::UnaryOperatorClass: {
  9904. // Only unwrap the * and & unary operators
  9905. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  9906. expr = UO->getSubExpr();
  9907. switch (UO->getOpcode()) {
  9908. case UO_AddrOf:
  9909. AllowOnePastEnd++;
  9910. break;
  9911. case UO_Deref:
  9912. AllowOnePastEnd--;
  9913. break;
  9914. default:
  9915. return;
  9916. }
  9917. break;
  9918. }
  9919. case Stmt::ConditionalOperatorClass: {
  9920. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  9921. if (const Expr *lhs = cond->getLHS())
  9922. CheckArrayAccess(lhs);
  9923. if (const Expr *rhs = cond->getRHS())
  9924. CheckArrayAccess(rhs);
  9925. return;
  9926. }
  9927. case Stmt::CXXOperatorCallExprClass: {
  9928. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  9929. for (const auto *Arg : OCE->arguments())
  9930. CheckArrayAccess(Arg);
  9931. return;
  9932. }
  9933. default:
  9934. return;
  9935. }
  9936. }
  9937. }
  9938. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  9939. namespace {
  9940. struct RetainCycleOwner {
  9941. VarDecl *Variable = nullptr;
  9942. SourceRange Range;
  9943. SourceLocation Loc;
  9944. bool Indirect = false;
  9945. RetainCycleOwner() = default;
  9946. void setLocsFrom(Expr *e) {
  9947. Loc = e->getExprLoc();
  9948. Range = e->getSourceRange();
  9949. }
  9950. };
  9951. } // namespace
  9952. /// Consider whether capturing the given variable can possibly lead to
  9953. /// a retain cycle.
  9954. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  9955. // In ARC, it's captured strongly iff the variable has __strong
  9956. // lifetime. In MRR, it's captured strongly if the variable is
  9957. // __block and has an appropriate type.
  9958. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  9959. return false;
  9960. owner.Variable = var;
  9961. if (ref)
  9962. owner.setLocsFrom(ref);
  9963. return true;
  9964. }
  9965. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  9966. while (true) {
  9967. e = e->IgnoreParens();
  9968. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  9969. switch (cast->getCastKind()) {
  9970. case CK_BitCast:
  9971. case CK_LValueBitCast:
  9972. case CK_LValueToRValue:
  9973. case CK_ARCReclaimReturnedObject:
  9974. e = cast->getSubExpr();
  9975. continue;
  9976. default:
  9977. return false;
  9978. }
  9979. }
  9980. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  9981. ObjCIvarDecl *ivar = ref->getDecl();
  9982. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  9983. return false;
  9984. // Try to find a retain cycle in the base.
  9985. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  9986. return false;
  9987. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  9988. owner.Indirect = true;
  9989. return true;
  9990. }
  9991. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  9992. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  9993. if (!var) return false;
  9994. return considerVariable(var, ref, owner);
  9995. }
  9996. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  9997. if (member->isArrow()) return false;
  9998. // Don't count this as an indirect ownership.
  9999. e = member->getBase();
  10000. continue;
  10001. }
  10002. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  10003. // Only pay attention to pseudo-objects on property references.
  10004. ObjCPropertyRefExpr *pre
  10005. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  10006. ->IgnoreParens());
  10007. if (!pre) return false;
  10008. if (pre->isImplicitProperty()) return false;
  10009. ObjCPropertyDecl *property = pre->getExplicitProperty();
  10010. if (!property->isRetaining() &&
  10011. !(property->getPropertyIvarDecl() &&
  10012. property->getPropertyIvarDecl()->getType()
  10013. .getObjCLifetime() == Qualifiers::OCL_Strong))
  10014. return false;
  10015. owner.Indirect = true;
  10016. if (pre->isSuperReceiver()) {
  10017. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  10018. if (!owner.Variable)
  10019. return false;
  10020. owner.Loc = pre->getLocation();
  10021. owner.Range = pre->getSourceRange();
  10022. return true;
  10023. }
  10024. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  10025. ->getSourceExpr());
  10026. continue;
  10027. }
  10028. // Array ivars?
  10029. return false;
  10030. }
  10031. }
  10032. namespace {
  10033. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  10034. ASTContext &Context;
  10035. VarDecl *Variable;
  10036. Expr *Capturer = nullptr;
  10037. bool VarWillBeReased = false;
  10038. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  10039. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  10040. Context(Context), Variable(variable) {}
  10041. void VisitDeclRefExpr(DeclRefExpr *ref) {
  10042. if (ref->getDecl() == Variable && !Capturer)
  10043. Capturer = ref;
  10044. }
  10045. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  10046. if (Capturer) return;
  10047. Visit(ref->getBase());
  10048. if (Capturer && ref->isFreeIvar())
  10049. Capturer = ref;
  10050. }
  10051. void VisitBlockExpr(BlockExpr *block) {
  10052. // Look inside nested blocks
  10053. if (block->getBlockDecl()->capturesVariable(Variable))
  10054. Visit(block->getBlockDecl()->getBody());
  10055. }
  10056. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  10057. if (Capturer) return;
  10058. if (OVE->getSourceExpr())
  10059. Visit(OVE->getSourceExpr());
  10060. }
  10061. void VisitBinaryOperator(BinaryOperator *BinOp) {
  10062. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  10063. return;
  10064. Expr *LHS = BinOp->getLHS();
  10065. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  10066. if (DRE->getDecl() != Variable)
  10067. return;
  10068. if (Expr *RHS = BinOp->getRHS()) {
  10069. RHS = RHS->IgnoreParenCasts();
  10070. llvm::APSInt Value;
  10071. VarWillBeReased =
  10072. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  10073. }
  10074. }
  10075. }
  10076. };
  10077. } // namespace
  10078. /// Check whether the given argument is a block which captures a
  10079. /// variable.
  10080. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  10081. assert(owner.Variable && owner.Loc.isValid());
  10082. e = e->IgnoreParenCasts();
  10083. // Look through [^{...} copy] and Block_copy(^{...}).
  10084. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  10085. Selector Cmd = ME->getSelector();
  10086. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  10087. e = ME->getInstanceReceiver();
  10088. if (!e)
  10089. return nullptr;
  10090. e = e->IgnoreParenCasts();
  10091. }
  10092. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  10093. if (CE->getNumArgs() == 1) {
  10094. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  10095. if (Fn) {
  10096. const IdentifierInfo *FnI = Fn->getIdentifier();
  10097. if (FnI && FnI->isStr("_Block_copy")) {
  10098. e = CE->getArg(0)->IgnoreParenCasts();
  10099. }
  10100. }
  10101. }
  10102. }
  10103. BlockExpr *block = dyn_cast<BlockExpr>(e);
  10104. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  10105. return nullptr;
  10106. FindCaptureVisitor visitor(S.Context, owner.Variable);
  10107. visitor.Visit(block->getBlockDecl()->getBody());
  10108. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  10109. }
  10110. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  10111. RetainCycleOwner &owner) {
  10112. assert(capturer);
  10113. assert(owner.Variable && owner.Loc.isValid());
  10114. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  10115. << owner.Variable << capturer->getSourceRange();
  10116. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  10117. << owner.Indirect << owner.Range;
  10118. }
  10119. /// Check for a keyword selector that starts with the word 'add' or
  10120. /// 'set'.
  10121. static bool isSetterLikeSelector(Selector sel) {
  10122. if (sel.isUnarySelector()) return false;
  10123. StringRef str = sel.getNameForSlot(0);
  10124. while (!str.empty() && str.front() == '_') str = str.substr(1);
  10125. if (str.startswith("set"))
  10126. str = str.substr(3);
  10127. else if (str.startswith("add")) {
  10128. // Specially whitelist 'addOperationWithBlock:'.
  10129. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  10130. return false;
  10131. str = str.substr(3);
  10132. }
  10133. else
  10134. return false;
  10135. if (str.empty()) return true;
  10136. return !isLowercase(str.front());
  10137. }
  10138. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  10139. ObjCMessageExpr *Message) {
  10140. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  10141. Message->getReceiverInterface(),
  10142. NSAPI::ClassId_NSMutableArray);
  10143. if (!IsMutableArray) {
  10144. return None;
  10145. }
  10146. Selector Sel = Message->getSelector();
  10147. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  10148. S.NSAPIObj->getNSArrayMethodKind(Sel);
  10149. if (!MKOpt) {
  10150. return None;
  10151. }
  10152. NSAPI::NSArrayMethodKind MK = *MKOpt;
  10153. switch (MK) {
  10154. case NSAPI::NSMutableArr_addObject:
  10155. case NSAPI::NSMutableArr_insertObjectAtIndex:
  10156. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  10157. return 0;
  10158. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  10159. return 1;
  10160. default:
  10161. return None;
  10162. }
  10163. return None;
  10164. }
  10165. static
  10166. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  10167. ObjCMessageExpr *Message) {
  10168. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  10169. Message->getReceiverInterface(),
  10170. NSAPI::ClassId_NSMutableDictionary);
  10171. if (!IsMutableDictionary) {
  10172. return None;
  10173. }
  10174. Selector Sel = Message->getSelector();
  10175. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  10176. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  10177. if (!MKOpt) {
  10178. return None;
  10179. }
  10180. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  10181. switch (MK) {
  10182. case NSAPI::NSMutableDict_setObjectForKey:
  10183. case NSAPI::NSMutableDict_setValueForKey:
  10184. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  10185. return 0;
  10186. default:
  10187. return None;
  10188. }
  10189. return None;
  10190. }
  10191. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  10192. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  10193. Message->getReceiverInterface(),
  10194. NSAPI::ClassId_NSMutableSet);
  10195. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  10196. Message->getReceiverInterface(),
  10197. NSAPI::ClassId_NSMutableOrderedSet);
  10198. if (!IsMutableSet && !IsMutableOrderedSet) {
  10199. return None;
  10200. }
  10201. Selector Sel = Message->getSelector();
  10202. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  10203. if (!MKOpt) {
  10204. return None;
  10205. }
  10206. NSAPI::NSSetMethodKind MK = *MKOpt;
  10207. switch (MK) {
  10208. case NSAPI::NSMutableSet_addObject:
  10209. case NSAPI::NSOrderedSet_setObjectAtIndex:
  10210. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  10211. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  10212. return 0;
  10213. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  10214. return 1;
  10215. }
  10216. return None;
  10217. }
  10218. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  10219. if (!Message->isInstanceMessage()) {
  10220. return;
  10221. }
  10222. Optional<int> ArgOpt;
  10223. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  10224. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  10225. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  10226. return;
  10227. }
  10228. int ArgIndex = *ArgOpt;
  10229. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  10230. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  10231. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  10232. }
  10233. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  10234. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  10235. if (ArgRE->isObjCSelfExpr()) {
  10236. Diag(Message->getSourceRange().getBegin(),
  10237. diag::warn_objc_circular_container)
  10238. << ArgRE->getDecl() << StringRef("'super'");
  10239. }
  10240. }
  10241. } else {
  10242. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  10243. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  10244. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  10245. }
  10246. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  10247. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  10248. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  10249. ValueDecl *Decl = ReceiverRE->getDecl();
  10250. Diag(Message->getSourceRange().getBegin(),
  10251. diag::warn_objc_circular_container)
  10252. << Decl << Decl;
  10253. if (!ArgRE->isObjCSelfExpr()) {
  10254. Diag(Decl->getLocation(),
  10255. diag::note_objc_circular_container_declared_here)
  10256. << Decl;
  10257. }
  10258. }
  10259. }
  10260. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  10261. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  10262. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  10263. ObjCIvarDecl *Decl = IvarRE->getDecl();
  10264. Diag(Message->getSourceRange().getBegin(),
  10265. diag::warn_objc_circular_container)
  10266. << Decl << Decl;
  10267. Diag(Decl->getLocation(),
  10268. diag::note_objc_circular_container_declared_here)
  10269. << Decl;
  10270. }
  10271. }
  10272. }
  10273. }
  10274. }
  10275. /// Check a message send to see if it's likely to cause a retain cycle.
  10276. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  10277. // Only check instance methods whose selector looks like a setter.
  10278. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  10279. return;
  10280. // Try to find a variable that the receiver is strongly owned by.
  10281. RetainCycleOwner owner;
  10282. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  10283. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  10284. return;
  10285. } else {
  10286. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  10287. owner.Variable = getCurMethodDecl()->getSelfDecl();
  10288. owner.Loc = msg->getSuperLoc();
  10289. owner.Range = msg->getSuperLoc();
  10290. }
  10291. // Check whether the receiver is captured by any of the arguments.
  10292. const ObjCMethodDecl *MD = msg->getMethodDecl();
  10293. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  10294. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  10295. // noescape blocks should not be retained by the method.
  10296. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  10297. continue;
  10298. return diagnoseRetainCycle(*this, capturer, owner);
  10299. }
  10300. }
  10301. }
  10302. /// Check a property assign to see if it's likely to cause a retain cycle.
  10303. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  10304. RetainCycleOwner owner;
  10305. if (!findRetainCycleOwner(*this, receiver, owner))
  10306. return;
  10307. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  10308. diagnoseRetainCycle(*this, capturer, owner);
  10309. }
  10310. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  10311. RetainCycleOwner Owner;
  10312. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  10313. return;
  10314. // Because we don't have an expression for the variable, we have to set the
  10315. // location explicitly here.
  10316. Owner.Loc = Var->getLocation();
  10317. Owner.Range = Var->getSourceRange();
  10318. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  10319. diagnoseRetainCycle(*this, Capturer, Owner);
  10320. }
  10321. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  10322. Expr *RHS, bool isProperty) {
  10323. // Check if RHS is an Objective-C object literal, which also can get
  10324. // immediately zapped in a weak reference. Note that we explicitly
  10325. // allow ObjCStringLiterals, since those are designed to never really die.
  10326. RHS = RHS->IgnoreParenImpCasts();
  10327. // This enum needs to match with the 'select' in
  10328. // warn_objc_arc_literal_assign (off-by-1).
  10329. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  10330. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  10331. return false;
  10332. S.Diag(Loc, diag::warn_arc_literal_assign)
  10333. << (unsigned) Kind
  10334. << (isProperty ? 0 : 1)
  10335. << RHS->getSourceRange();
  10336. return true;
  10337. }
  10338. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  10339. Qualifiers::ObjCLifetime LT,
  10340. Expr *RHS, bool isProperty) {
  10341. // Strip off any implicit cast added to get to the one ARC-specific.
  10342. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  10343. if (cast->getCastKind() == CK_ARCConsumeObject) {
  10344. S.Diag(Loc, diag::warn_arc_retained_assign)
  10345. << (LT == Qualifiers::OCL_ExplicitNone)
  10346. << (isProperty ? 0 : 1)
  10347. << RHS->getSourceRange();
  10348. return true;
  10349. }
  10350. RHS = cast->getSubExpr();
  10351. }
  10352. if (LT == Qualifiers::OCL_Weak &&
  10353. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  10354. return true;
  10355. return false;
  10356. }
  10357. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  10358. QualType LHS, Expr *RHS) {
  10359. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  10360. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  10361. return false;
  10362. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  10363. return true;
  10364. return false;
  10365. }
  10366. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  10367. Expr *LHS, Expr *RHS) {
  10368. QualType LHSType;
  10369. // PropertyRef on LHS type need be directly obtained from
  10370. // its declaration as it has a PseudoType.
  10371. ObjCPropertyRefExpr *PRE
  10372. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  10373. if (PRE && !PRE->isImplicitProperty()) {
  10374. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  10375. if (PD)
  10376. LHSType = PD->getType();
  10377. }
  10378. if (LHSType.isNull())
  10379. LHSType = LHS->getType();
  10380. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  10381. if (LT == Qualifiers::OCL_Weak) {
  10382. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  10383. getCurFunction()->markSafeWeakUse(LHS);
  10384. }
  10385. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  10386. return;
  10387. // FIXME. Check for other life times.
  10388. if (LT != Qualifiers::OCL_None)
  10389. return;
  10390. if (PRE) {
  10391. if (PRE->isImplicitProperty())
  10392. return;
  10393. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  10394. if (!PD)
  10395. return;
  10396. unsigned Attributes = PD->getPropertyAttributes();
  10397. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  10398. // when 'assign' attribute was not explicitly specified
  10399. // by user, ignore it and rely on property type itself
  10400. // for lifetime info.
  10401. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  10402. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  10403. LHSType->isObjCRetainableType())
  10404. return;
  10405. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  10406. if (cast->getCastKind() == CK_ARCConsumeObject) {
  10407. Diag(Loc, diag::warn_arc_retained_property_assign)
  10408. << RHS->getSourceRange();
  10409. return;
  10410. }
  10411. RHS = cast->getSubExpr();
  10412. }
  10413. }
  10414. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  10415. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  10416. return;
  10417. }
  10418. }
  10419. }
  10420. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  10421. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  10422. SourceLocation StmtLoc,
  10423. const NullStmt *Body) {
  10424. // Do not warn if the body is a macro that expands to nothing, e.g:
  10425. //
  10426. // #define CALL(x)
  10427. // if (condition)
  10428. // CALL(0);
  10429. if (Body->hasLeadingEmptyMacro())
  10430. return false;
  10431. // Get line numbers of statement and body.
  10432. bool StmtLineInvalid;
  10433. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  10434. &StmtLineInvalid);
  10435. if (StmtLineInvalid)
  10436. return false;
  10437. bool BodyLineInvalid;
  10438. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  10439. &BodyLineInvalid);
  10440. if (BodyLineInvalid)
  10441. return false;
  10442. // Warn if null statement and body are on the same line.
  10443. if (StmtLine != BodyLine)
  10444. return false;
  10445. return true;
  10446. }
  10447. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  10448. const Stmt *Body,
  10449. unsigned DiagID) {
  10450. // Since this is a syntactic check, don't emit diagnostic for template
  10451. // instantiations, this just adds noise.
  10452. if (CurrentInstantiationScope)
  10453. return;
  10454. // The body should be a null statement.
  10455. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  10456. if (!NBody)
  10457. return;
  10458. // Do the usual checks.
  10459. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  10460. return;
  10461. Diag(NBody->getSemiLoc(), DiagID);
  10462. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  10463. }
  10464. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  10465. const Stmt *PossibleBody) {
  10466. assert(!CurrentInstantiationScope); // Ensured by caller
  10467. SourceLocation StmtLoc;
  10468. const Stmt *Body;
  10469. unsigned DiagID;
  10470. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  10471. StmtLoc = FS->getRParenLoc();
  10472. Body = FS->getBody();
  10473. DiagID = diag::warn_empty_for_body;
  10474. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  10475. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  10476. Body = WS->getBody();
  10477. DiagID = diag::warn_empty_while_body;
  10478. } else
  10479. return; // Neither `for' nor `while'.
  10480. // The body should be a null statement.
  10481. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  10482. if (!NBody)
  10483. return;
  10484. // Skip expensive checks if diagnostic is disabled.
  10485. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  10486. return;
  10487. // Do the usual checks.
  10488. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  10489. return;
  10490. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  10491. // noise level low, emit diagnostics only if for/while is followed by a
  10492. // CompoundStmt, e.g.:
  10493. // for (int i = 0; i < n; i++);
  10494. // {
  10495. // a(i);
  10496. // }
  10497. // or if for/while is followed by a statement with more indentation
  10498. // than for/while itself:
  10499. // for (int i = 0; i < n; i++);
  10500. // a(i);
  10501. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  10502. if (!ProbableTypo) {
  10503. bool BodyColInvalid;
  10504. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  10505. PossibleBody->getLocStart(),
  10506. &BodyColInvalid);
  10507. if (BodyColInvalid)
  10508. return;
  10509. bool StmtColInvalid;
  10510. unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
  10511. S->getLocStart(),
  10512. &StmtColInvalid);
  10513. if (StmtColInvalid)
  10514. return;
  10515. if (BodyCol > StmtCol)
  10516. ProbableTypo = true;
  10517. }
  10518. if (ProbableTypo) {
  10519. Diag(NBody->getSemiLoc(), DiagID);
  10520. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  10521. }
  10522. }
  10523. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  10524. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  10525. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  10526. SourceLocation OpLoc) {
  10527. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  10528. return;
  10529. if (inTemplateInstantiation())
  10530. return;
  10531. // Strip parens and casts away.
  10532. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  10533. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  10534. // Check for a call expression
  10535. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  10536. if (!CE || CE->getNumArgs() != 1)
  10537. return;
  10538. // Check for a call to std::move
  10539. if (!CE->isCallToStdMove())
  10540. return;
  10541. // Get argument from std::move
  10542. RHSExpr = CE->getArg(0);
  10543. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  10544. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  10545. // Two DeclRefExpr's, check that the decls are the same.
  10546. if (LHSDeclRef && RHSDeclRef) {
  10547. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  10548. return;
  10549. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  10550. RHSDeclRef->getDecl()->getCanonicalDecl())
  10551. return;
  10552. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  10553. << LHSExpr->getSourceRange()
  10554. << RHSExpr->getSourceRange();
  10555. return;
  10556. }
  10557. // Member variables require a different approach to check for self moves.
  10558. // MemberExpr's are the same if every nested MemberExpr refers to the same
  10559. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  10560. // the base Expr's are CXXThisExpr's.
  10561. const Expr *LHSBase = LHSExpr;
  10562. const Expr *RHSBase = RHSExpr;
  10563. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  10564. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  10565. if (!LHSME || !RHSME)
  10566. return;
  10567. while (LHSME && RHSME) {
  10568. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  10569. RHSME->getMemberDecl()->getCanonicalDecl())
  10570. return;
  10571. LHSBase = LHSME->getBase();
  10572. RHSBase = RHSME->getBase();
  10573. LHSME = dyn_cast<MemberExpr>(LHSBase);
  10574. RHSME = dyn_cast<MemberExpr>(RHSBase);
  10575. }
  10576. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  10577. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  10578. if (LHSDeclRef && RHSDeclRef) {
  10579. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  10580. return;
  10581. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  10582. RHSDeclRef->getDecl()->getCanonicalDecl())
  10583. return;
  10584. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  10585. << LHSExpr->getSourceRange()
  10586. << RHSExpr->getSourceRange();
  10587. return;
  10588. }
  10589. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  10590. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  10591. << LHSExpr->getSourceRange()
  10592. << RHSExpr->getSourceRange();
  10593. }
  10594. //===--- Layout compatibility ----------------------------------------------//
  10595. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  10596. /// \brief Check if two enumeration types are layout-compatible.
  10597. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  10598. // C++11 [dcl.enum] p8:
  10599. // Two enumeration types are layout-compatible if they have the same
  10600. // underlying type.
  10601. return ED1->isComplete() && ED2->isComplete() &&
  10602. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  10603. }
  10604. /// \brief Check if two fields are layout-compatible.
  10605. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  10606. FieldDecl *Field2) {
  10607. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  10608. return false;
  10609. if (Field1->isBitField() != Field2->isBitField())
  10610. return false;
  10611. if (Field1->isBitField()) {
  10612. // Make sure that the bit-fields are the same length.
  10613. unsigned Bits1 = Field1->getBitWidthValue(C);
  10614. unsigned Bits2 = Field2->getBitWidthValue(C);
  10615. if (Bits1 != Bits2)
  10616. return false;
  10617. }
  10618. return true;
  10619. }
  10620. /// \brief Check if two standard-layout structs are layout-compatible.
  10621. /// (C++11 [class.mem] p17)
  10622. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  10623. RecordDecl *RD2) {
  10624. // If both records are C++ classes, check that base classes match.
  10625. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  10626. // If one of records is a CXXRecordDecl we are in C++ mode,
  10627. // thus the other one is a CXXRecordDecl, too.
  10628. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  10629. // Check number of base classes.
  10630. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  10631. return false;
  10632. // Check the base classes.
  10633. for (CXXRecordDecl::base_class_const_iterator
  10634. Base1 = D1CXX->bases_begin(),
  10635. BaseEnd1 = D1CXX->bases_end(),
  10636. Base2 = D2CXX->bases_begin();
  10637. Base1 != BaseEnd1;
  10638. ++Base1, ++Base2) {
  10639. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  10640. return false;
  10641. }
  10642. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  10643. // If only RD2 is a C++ class, it should have zero base classes.
  10644. if (D2CXX->getNumBases() > 0)
  10645. return false;
  10646. }
  10647. // Check the fields.
  10648. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  10649. Field2End = RD2->field_end(),
  10650. Field1 = RD1->field_begin(),
  10651. Field1End = RD1->field_end();
  10652. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  10653. if (!isLayoutCompatible(C, *Field1, *Field2))
  10654. return false;
  10655. }
  10656. if (Field1 != Field1End || Field2 != Field2End)
  10657. return false;
  10658. return true;
  10659. }
  10660. /// \brief Check if two standard-layout unions are layout-compatible.
  10661. /// (C++11 [class.mem] p18)
  10662. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  10663. RecordDecl *RD2) {
  10664. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  10665. for (auto *Field2 : RD2->fields())
  10666. UnmatchedFields.insert(Field2);
  10667. for (auto *Field1 : RD1->fields()) {
  10668. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  10669. I = UnmatchedFields.begin(),
  10670. E = UnmatchedFields.end();
  10671. for ( ; I != E; ++I) {
  10672. if (isLayoutCompatible(C, Field1, *I)) {
  10673. bool Result = UnmatchedFields.erase(*I);
  10674. (void) Result;
  10675. assert(Result);
  10676. break;
  10677. }
  10678. }
  10679. if (I == E)
  10680. return false;
  10681. }
  10682. return UnmatchedFields.empty();
  10683. }
  10684. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  10685. RecordDecl *RD2) {
  10686. if (RD1->isUnion() != RD2->isUnion())
  10687. return false;
  10688. if (RD1->isUnion())
  10689. return isLayoutCompatibleUnion(C, RD1, RD2);
  10690. else
  10691. return isLayoutCompatibleStruct(C, RD1, RD2);
  10692. }
  10693. /// \brief Check if two types are layout-compatible in C++11 sense.
  10694. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  10695. if (T1.isNull() || T2.isNull())
  10696. return false;
  10697. // C++11 [basic.types] p11:
  10698. // If two types T1 and T2 are the same type, then T1 and T2 are
  10699. // layout-compatible types.
  10700. if (C.hasSameType(T1, T2))
  10701. return true;
  10702. T1 = T1.getCanonicalType().getUnqualifiedType();
  10703. T2 = T2.getCanonicalType().getUnqualifiedType();
  10704. const Type::TypeClass TC1 = T1->getTypeClass();
  10705. const Type::TypeClass TC2 = T2->getTypeClass();
  10706. if (TC1 != TC2)
  10707. return false;
  10708. if (TC1 == Type::Enum) {
  10709. return isLayoutCompatible(C,
  10710. cast<EnumType>(T1)->getDecl(),
  10711. cast<EnumType>(T2)->getDecl());
  10712. } else if (TC1 == Type::Record) {
  10713. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  10714. return false;
  10715. return isLayoutCompatible(C,
  10716. cast<RecordType>(T1)->getDecl(),
  10717. cast<RecordType>(T2)->getDecl());
  10718. }
  10719. return false;
  10720. }
  10721. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  10722. /// \brief Given a type tag expression find the type tag itself.
  10723. ///
  10724. /// \param TypeExpr Type tag expression, as it appears in user's code.
  10725. ///
  10726. /// \param VD Declaration of an identifier that appears in a type tag.
  10727. ///
  10728. /// \param MagicValue Type tag magic value.
  10729. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  10730. const ValueDecl **VD, uint64_t *MagicValue) {
  10731. while(true) {
  10732. if (!TypeExpr)
  10733. return false;
  10734. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  10735. switch (TypeExpr->getStmtClass()) {
  10736. case Stmt::UnaryOperatorClass: {
  10737. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  10738. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  10739. TypeExpr = UO->getSubExpr();
  10740. continue;
  10741. }
  10742. return false;
  10743. }
  10744. case Stmt::DeclRefExprClass: {
  10745. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  10746. *VD = DRE->getDecl();
  10747. return true;
  10748. }
  10749. case Stmt::IntegerLiteralClass: {
  10750. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  10751. llvm::APInt MagicValueAPInt = IL->getValue();
  10752. if (MagicValueAPInt.getActiveBits() <= 64) {
  10753. *MagicValue = MagicValueAPInt.getZExtValue();
  10754. return true;
  10755. } else
  10756. return false;
  10757. }
  10758. case Stmt::BinaryConditionalOperatorClass:
  10759. case Stmt::ConditionalOperatorClass: {
  10760. const AbstractConditionalOperator *ACO =
  10761. cast<AbstractConditionalOperator>(TypeExpr);
  10762. bool Result;
  10763. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  10764. if (Result)
  10765. TypeExpr = ACO->getTrueExpr();
  10766. else
  10767. TypeExpr = ACO->getFalseExpr();
  10768. continue;
  10769. }
  10770. return false;
  10771. }
  10772. case Stmt::BinaryOperatorClass: {
  10773. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  10774. if (BO->getOpcode() == BO_Comma) {
  10775. TypeExpr = BO->getRHS();
  10776. continue;
  10777. }
  10778. return false;
  10779. }
  10780. default:
  10781. return false;
  10782. }
  10783. }
  10784. }
  10785. /// \brief Retrieve the C type corresponding to type tag TypeExpr.
  10786. ///
  10787. /// \param TypeExpr Expression that specifies a type tag.
  10788. ///
  10789. /// \param MagicValues Registered magic values.
  10790. ///
  10791. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  10792. /// kind.
  10793. ///
  10794. /// \param TypeInfo Information about the corresponding C type.
  10795. ///
  10796. /// \returns true if the corresponding C type was found.
  10797. static bool GetMatchingCType(
  10798. const IdentifierInfo *ArgumentKind,
  10799. const Expr *TypeExpr, const ASTContext &Ctx,
  10800. const llvm::DenseMap<Sema::TypeTagMagicValue,
  10801. Sema::TypeTagData> *MagicValues,
  10802. bool &FoundWrongKind,
  10803. Sema::TypeTagData &TypeInfo) {
  10804. FoundWrongKind = false;
  10805. // Variable declaration that has type_tag_for_datatype attribute.
  10806. const ValueDecl *VD = nullptr;
  10807. uint64_t MagicValue;
  10808. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  10809. return false;
  10810. if (VD) {
  10811. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  10812. if (I->getArgumentKind() != ArgumentKind) {
  10813. FoundWrongKind = true;
  10814. return false;
  10815. }
  10816. TypeInfo.Type = I->getMatchingCType();
  10817. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  10818. TypeInfo.MustBeNull = I->getMustBeNull();
  10819. return true;
  10820. }
  10821. return false;
  10822. }
  10823. if (!MagicValues)
  10824. return false;
  10825. llvm::DenseMap<Sema::TypeTagMagicValue,
  10826. Sema::TypeTagData>::const_iterator I =
  10827. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  10828. if (I == MagicValues->end())
  10829. return false;
  10830. TypeInfo = I->second;
  10831. return true;
  10832. }
  10833. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  10834. uint64_t MagicValue, QualType Type,
  10835. bool LayoutCompatible,
  10836. bool MustBeNull) {
  10837. if (!TypeTagForDatatypeMagicValues)
  10838. TypeTagForDatatypeMagicValues.reset(
  10839. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  10840. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  10841. (*TypeTagForDatatypeMagicValues)[Magic] =
  10842. TypeTagData(Type, LayoutCompatible, MustBeNull);
  10843. }
  10844. static bool IsSameCharType(QualType T1, QualType T2) {
  10845. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  10846. if (!BT1)
  10847. return false;
  10848. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  10849. if (!BT2)
  10850. return false;
  10851. BuiltinType::Kind T1Kind = BT1->getKind();
  10852. BuiltinType::Kind T2Kind = BT2->getKind();
  10853. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  10854. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  10855. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  10856. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  10857. }
  10858. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  10859. const ArrayRef<const Expr *> ExprArgs,
  10860. SourceLocation CallSiteLoc) {
  10861. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  10862. bool IsPointerAttr = Attr->getIsPointer();
  10863. // Retrieve the argument representing the 'type_tag'.
  10864. unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
  10865. if (TypeTagIdxAST >= ExprArgs.size()) {
  10866. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  10867. << 0 << Attr->getTypeTagIdx().getSourceIndex();
  10868. return;
  10869. }
  10870. const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
  10871. bool FoundWrongKind;
  10872. TypeTagData TypeInfo;
  10873. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  10874. TypeTagForDatatypeMagicValues.get(),
  10875. FoundWrongKind, TypeInfo)) {
  10876. if (FoundWrongKind)
  10877. Diag(TypeTagExpr->getExprLoc(),
  10878. diag::warn_type_tag_for_datatype_wrong_kind)
  10879. << TypeTagExpr->getSourceRange();
  10880. return;
  10881. }
  10882. // Retrieve the argument representing the 'arg_idx'.
  10883. unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
  10884. if (ArgumentIdxAST >= ExprArgs.size()) {
  10885. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  10886. << 1 << Attr->getArgumentIdx().getSourceIndex();
  10887. return;
  10888. }
  10889. const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
  10890. if (IsPointerAttr) {
  10891. // Skip implicit cast of pointer to `void *' (as a function argument).
  10892. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  10893. if (ICE->getType()->isVoidPointerType() &&
  10894. ICE->getCastKind() == CK_BitCast)
  10895. ArgumentExpr = ICE->getSubExpr();
  10896. }
  10897. QualType ArgumentType = ArgumentExpr->getType();
  10898. // Passing a `void*' pointer shouldn't trigger a warning.
  10899. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  10900. return;
  10901. if (TypeInfo.MustBeNull) {
  10902. // Type tag with matching void type requires a null pointer.
  10903. if (!ArgumentExpr->isNullPointerConstant(Context,
  10904. Expr::NPC_ValueDependentIsNotNull)) {
  10905. Diag(ArgumentExpr->getExprLoc(),
  10906. diag::warn_type_safety_null_pointer_required)
  10907. << ArgumentKind->getName()
  10908. << ArgumentExpr->getSourceRange()
  10909. << TypeTagExpr->getSourceRange();
  10910. }
  10911. return;
  10912. }
  10913. QualType RequiredType = TypeInfo.Type;
  10914. if (IsPointerAttr)
  10915. RequiredType = Context.getPointerType(RequiredType);
  10916. bool mismatch = false;
  10917. if (!TypeInfo.LayoutCompatible) {
  10918. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  10919. // C++11 [basic.fundamental] p1:
  10920. // Plain char, signed char, and unsigned char are three distinct types.
  10921. //
  10922. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  10923. // char' depending on the current char signedness mode.
  10924. if (mismatch)
  10925. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  10926. RequiredType->getPointeeType())) ||
  10927. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  10928. mismatch = false;
  10929. } else
  10930. if (IsPointerAttr)
  10931. mismatch = !isLayoutCompatible(Context,
  10932. ArgumentType->getPointeeType(),
  10933. RequiredType->getPointeeType());
  10934. else
  10935. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  10936. if (mismatch)
  10937. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  10938. << ArgumentType << ArgumentKind
  10939. << TypeInfo.LayoutCompatible << RequiredType
  10940. << ArgumentExpr->getSourceRange()
  10941. << TypeTagExpr->getSourceRange();
  10942. }
  10943. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  10944. CharUnits Alignment) {
  10945. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  10946. }
  10947. void Sema::DiagnoseMisalignedMembers() {
  10948. for (MisalignedMember &m : MisalignedMembers) {
  10949. const NamedDecl *ND = m.RD;
  10950. if (ND->getName().empty()) {
  10951. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  10952. ND = TD;
  10953. }
  10954. Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
  10955. << m.MD << ND << m.E->getSourceRange();
  10956. }
  10957. MisalignedMembers.clear();
  10958. }
  10959. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  10960. E = E->IgnoreParens();
  10961. if (!T->isPointerType() && !T->isIntegerType())
  10962. return;
  10963. if (isa<UnaryOperator>(E) &&
  10964. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  10965. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  10966. if (isa<MemberExpr>(Op)) {
  10967. auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
  10968. MisalignedMember(Op));
  10969. if (MA != MisalignedMembers.end() &&
  10970. (T->isIntegerType() ||
  10971. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  10972. Context.getTypeAlignInChars(
  10973. T->getPointeeType()) <= MA->Alignment))))
  10974. MisalignedMembers.erase(MA);
  10975. }
  10976. }
  10977. }
  10978. void Sema::RefersToMemberWithReducedAlignment(
  10979. Expr *E,
  10980. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  10981. Action) {
  10982. const auto *ME = dyn_cast<MemberExpr>(E);
  10983. if (!ME)
  10984. return;
  10985. // No need to check expressions with an __unaligned-qualified type.
  10986. if (E->getType().getQualifiers().hasUnaligned())
  10987. return;
  10988. // For a chain of MemberExpr like "a.b.c.d" this list
  10989. // will keep FieldDecl's like [d, c, b].
  10990. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  10991. const MemberExpr *TopME = nullptr;
  10992. bool AnyIsPacked = false;
  10993. do {
  10994. QualType BaseType = ME->getBase()->getType();
  10995. if (ME->isArrow())
  10996. BaseType = BaseType->getPointeeType();
  10997. RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
  10998. if (RD->isInvalidDecl())
  10999. return;
  11000. ValueDecl *MD = ME->getMemberDecl();
  11001. auto *FD = dyn_cast<FieldDecl>(MD);
  11002. // We do not care about non-data members.
  11003. if (!FD || FD->isInvalidDecl())
  11004. return;
  11005. AnyIsPacked =
  11006. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  11007. ReverseMemberChain.push_back(FD);
  11008. TopME = ME;
  11009. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  11010. } while (ME);
  11011. assert(TopME && "We did not compute a topmost MemberExpr!");
  11012. // Not the scope of this diagnostic.
  11013. if (!AnyIsPacked)
  11014. return;
  11015. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  11016. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  11017. // TODO: The innermost base of the member expression may be too complicated.
  11018. // For now, just disregard these cases. This is left for future
  11019. // improvement.
  11020. if (!DRE && !isa<CXXThisExpr>(TopBase))
  11021. return;
  11022. // Alignment expected by the whole expression.
  11023. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  11024. // No need to do anything else with this case.
  11025. if (ExpectedAlignment.isOne())
  11026. return;
  11027. // Synthesize offset of the whole access.
  11028. CharUnits Offset;
  11029. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  11030. I++) {
  11031. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  11032. }
  11033. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  11034. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  11035. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  11036. // The base expression of the innermost MemberExpr may give
  11037. // stronger guarantees than the class containing the member.
  11038. if (DRE && !TopME->isArrow()) {
  11039. const ValueDecl *VD = DRE->getDecl();
  11040. if (!VD->getType()->isReferenceType())
  11041. CompleteObjectAlignment =
  11042. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  11043. }
  11044. // Check if the synthesized offset fulfills the alignment.
  11045. if (Offset % ExpectedAlignment != 0 ||
  11046. // It may fulfill the offset it but the effective alignment may still be
  11047. // lower than the expected expression alignment.
  11048. CompleteObjectAlignment < ExpectedAlignment) {
  11049. // If this happens, we want to determine a sensible culprit of this.
  11050. // Intuitively, watching the chain of member expressions from right to
  11051. // left, we start with the required alignment (as required by the field
  11052. // type) but some packed attribute in that chain has reduced the alignment.
  11053. // It may happen that another packed structure increases it again. But if
  11054. // we are here such increase has not been enough. So pointing the first
  11055. // FieldDecl that either is packed or else its RecordDecl is,
  11056. // seems reasonable.
  11057. FieldDecl *FD = nullptr;
  11058. CharUnits Alignment;
  11059. for (FieldDecl *FDI : ReverseMemberChain) {
  11060. if (FDI->hasAttr<PackedAttr>() ||
  11061. FDI->getParent()->hasAttr<PackedAttr>()) {
  11062. FD = FDI;
  11063. Alignment = std::min(
  11064. Context.getTypeAlignInChars(FD->getType()),
  11065. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  11066. break;
  11067. }
  11068. }
  11069. assert(FD && "We did not find a packed FieldDecl!");
  11070. Action(E, FD->getParent(), FD, Alignment);
  11071. }
  11072. }
  11073. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  11074. using namespace std::placeholders;
  11075. RefersToMemberWithReducedAlignment(
  11076. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  11077. _2, _3, _4));
  11078. }