SemaChecking.cpp 457 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455
  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/ASTContext.h"
  15. #include "clang/AST/CharUnits.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclObjC.h"
  18. #include "clang/AST/EvaluatedExprVisitor.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/ExprObjC.h"
  22. #include "clang/AST/ExprOpenMP.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/AST/StmtObjC.h"
  25. #include "clang/Analysis/Analyses/FormatString.h"
  26. #include "clang/Basic/CharInfo.h"
  27. #include "clang/Basic/SyncScope.h"
  28. #include "clang/Basic/TargetBuiltins.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  31. #include "clang/Sema/Initialization.h"
  32. #include "clang/Sema/Lookup.h"
  33. #include "clang/Sema/ScopeInfo.h"
  34. #include "clang/Sema/Sema.h"
  35. #include "clang/Sema/SemaInternal.h"
  36. #include "llvm/ADT/STLExtras.h"
  37. #include "llvm/ADT/SmallBitVector.h"
  38. #include "llvm/ADT/SmallString.h"
  39. #include "llvm/Support/ConvertUTF.h"
  40. #include "llvm/Support/Format.h"
  41. #include "llvm/Support/Locale.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. using namespace clang;
  44. using namespace sema;
  45. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  46. unsigned ByteNo) const {
  47. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  48. Context.getTargetInfo());
  49. }
  50. /// Checks that a call expression's argument count is the desired number.
  51. /// This is useful when doing custom type-checking. Returns true on error.
  52. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  53. unsigned argCount = call->getNumArgs();
  54. if (argCount == desiredArgCount) return false;
  55. if (argCount < desiredArgCount)
  56. return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
  57. << 0 /*function call*/ << desiredArgCount << argCount
  58. << call->getSourceRange();
  59. // Highlight all the excess arguments.
  60. SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
  61. call->getArg(argCount - 1)->getLocEnd());
  62. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  63. << 0 /*function call*/ << desiredArgCount << argCount
  64. << call->getArg(1)->getSourceRange();
  65. }
  66. /// Check that the first argument to __builtin_annotation is an integer
  67. /// and the second argument is a non-wide string literal.
  68. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  69. if (checkArgCount(S, TheCall, 2))
  70. return true;
  71. // First argument should be an integer.
  72. Expr *ValArg = TheCall->getArg(0);
  73. QualType Ty = ValArg->getType();
  74. if (!Ty->isIntegerType()) {
  75. S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
  76. << ValArg->getSourceRange();
  77. return true;
  78. }
  79. // Second argument should be a constant string.
  80. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  81. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  82. if (!Literal || !Literal->isAscii()) {
  83. S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
  84. << StrArg->getSourceRange();
  85. return true;
  86. }
  87. TheCall->setType(Ty);
  88. return false;
  89. }
  90. static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
  91. // We need at least one argument.
  92. if (TheCall->getNumArgs() < 1) {
  93. S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  94. << 0 << 1 << TheCall->getNumArgs()
  95. << TheCall->getCallee()->getSourceRange();
  96. return true;
  97. }
  98. // All arguments should be wide string literals.
  99. for (Expr *Arg : TheCall->arguments()) {
  100. auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  101. if (!Literal || !Literal->isWide()) {
  102. S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
  103. << Arg->getSourceRange();
  104. return true;
  105. }
  106. }
  107. return false;
  108. }
  109. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  110. /// result type to the corresponding pointer type.
  111. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  112. if (checkArgCount(S, TheCall, 1))
  113. return true;
  114. ExprResult Arg(TheCall->getArg(0));
  115. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
  116. if (ResultType.isNull())
  117. return true;
  118. TheCall->setArg(0, Arg.get());
  119. TheCall->setType(ResultType);
  120. return false;
  121. }
  122. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
  123. if (checkArgCount(S, TheCall, 3))
  124. return true;
  125. // First two arguments should be integers.
  126. for (unsigned I = 0; I < 2; ++I) {
  127. Expr *Arg = TheCall->getArg(I);
  128. QualType Ty = Arg->getType();
  129. if (!Ty->isIntegerType()) {
  130. S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
  131. << Ty << Arg->getSourceRange();
  132. return true;
  133. }
  134. }
  135. // Third argument should be a pointer to a non-const integer.
  136. // IRGen correctly handles volatile, restrict, and address spaces, and
  137. // the other qualifiers aren't possible.
  138. {
  139. Expr *Arg = TheCall->getArg(2);
  140. QualType Ty = Arg->getType();
  141. const auto *PtrTy = Ty->getAs<PointerType>();
  142. if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
  143. !PtrTy->getPointeeType().isConstQualified())) {
  144. S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
  145. << Ty << Arg->getSourceRange();
  146. return true;
  147. }
  148. }
  149. return false;
  150. }
  151. static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
  152. CallExpr *TheCall, unsigned SizeIdx,
  153. unsigned DstSizeIdx) {
  154. if (TheCall->getNumArgs() <= SizeIdx ||
  155. TheCall->getNumArgs() <= DstSizeIdx)
  156. return;
  157. const Expr *SizeArg = TheCall->getArg(SizeIdx);
  158. const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
  159. llvm::APSInt Size, DstSize;
  160. // find out if both sizes are known at compile time
  161. if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
  162. !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
  163. return;
  164. if (Size.ule(DstSize))
  165. return;
  166. // confirmed overflow so generate the diagnostic.
  167. IdentifierInfo *FnName = FDecl->getIdentifier();
  168. SourceLocation SL = TheCall->getLocStart();
  169. SourceRange SR = TheCall->getSourceRange();
  170. S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
  171. }
  172. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  173. if (checkArgCount(S, BuiltinCall, 2))
  174. return true;
  175. SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
  176. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  177. Expr *Call = BuiltinCall->getArg(0);
  178. Expr *Chain = BuiltinCall->getArg(1);
  179. if (Call->getStmtClass() != Stmt::CallExprClass) {
  180. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  181. << Call->getSourceRange();
  182. return true;
  183. }
  184. auto CE = cast<CallExpr>(Call);
  185. if (CE->getCallee()->getType()->isBlockPointerType()) {
  186. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  187. << Call->getSourceRange();
  188. return true;
  189. }
  190. const Decl *TargetDecl = CE->getCalleeDecl();
  191. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  192. if (FD->getBuiltinID()) {
  193. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  194. << Call->getSourceRange();
  195. return true;
  196. }
  197. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  198. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  199. << Call->getSourceRange();
  200. return true;
  201. }
  202. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  203. if (ChainResult.isInvalid())
  204. return true;
  205. if (!ChainResult.get()->getType()->isPointerType()) {
  206. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  207. << Chain->getSourceRange();
  208. return true;
  209. }
  210. QualType ReturnTy = CE->getCallReturnType(S.Context);
  211. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  212. QualType BuiltinTy = S.Context.getFunctionType(
  213. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  214. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  215. Builtin =
  216. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  217. BuiltinCall->setType(CE->getType());
  218. BuiltinCall->setValueKind(CE->getValueKind());
  219. BuiltinCall->setObjectKind(CE->getObjectKind());
  220. BuiltinCall->setCallee(Builtin);
  221. BuiltinCall->setArg(1, ChainResult.get());
  222. return false;
  223. }
  224. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  225. Scope::ScopeFlags NeededScopeFlags,
  226. unsigned DiagID) {
  227. // Scopes aren't available during instantiation. Fortunately, builtin
  228. // functions cannot be template args so they cannot be formed through template
  229. // instantiation. Therefore checking once during the parse is sufficient.
  230. if (SemaRef.inTemplateInstantiation())
  231. return false;
  232. Scope *S = SemaRef.getCurScope();
  233. while (S && !S->isSEHExceptScope())
  234. S = S->getParent();
  235. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  236. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  237. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  238. << DRE->getDecl()->getIdentifier();
  239. return true;
  240. }
  241. return false;
  242. }
  243. static inline bool isBlockPointer(Expr *Arg) {
  244. return Arg->getType()->isBlockPointerType();
  245. }
  246. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  247. /// void*, which is a requirement of device side enqueue.
  248. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  249. const BlockPointerType *BPT =
  250. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  251. ArrayRef<QualType> Params =
  252. BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
  253. unsigned ArgCounter = 0;
  254. bool IllegalParams = false;
  255. // Iterate through the block parameters until either one is found that is not
  256. // a local void*, or the block is valid.
  257. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  258. I != E; ++I, ++ArgCounter) {
  259. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  260. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  261. LangAS::opencl_local) {
  262. // Get the location of the error. If a block literal has been passed
  263. // (BlockExpr) then we can point straight to the offending argument,
  264. // else we just point to the variable reference.
  265. SourceLocation ErrorLoc;
  266. if (isa<BlockExpr>(BlockArg)) {
  267. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  268. ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
  269. } else if (isa<DeclRefExpr>(BlockArg)) {
  270. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
  271. }
  272. S.Diag(ErrorLoc,
  273. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  274. IllegalParams = true;
  275. }
  276. }
  277. return IllegalParams;
  278. }
  279. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  280. if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
  281. S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
  282. << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
  283. return true;
  284. }
  285. return false;
  286. }
  287. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  288. if (checkArgCount(S, TheCall, 2))
  289. return true;
  290. if (checkOpenCLSubgroupExt(S, TheCall))
  291. return true;
  292. // First argument is an ndrange_t type.
  293. Expr *NDRangeArg = TheCall->getArg(0);
  294. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  295. S.Diag(NDRangeArg->getLocStart(),
  296. diag::err_opencl_builtin_expected_type)
  297. << TheCall->getDirectCallee() << "'ndrange_t'";
  298. return true;
  299. }
  300. Expr *BlockArg = TheCall->getArg(1);
  301. if (!isBlockPointer(BlockArg)) {
  302. S.Diag(BlockArg->getLocStart(),
  303. diag::err_opencl_builtin_expected_type)
  304. << TheCall->getDirectCallee() << "block";
  305. return true;
  306. }
  307. return checkOpenCLBlockArgs(S, BlockArg);
  308. }
  309. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  310. /// get_kernel_work_group_size
  311. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  312. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  313. if (checkArgCount(S, TheCall, 1))
  314. return true;
  315. Expr *BlockArg = TheCall->getArg(0);
  316. if (!isBlockPointer(BlockArg)) {
  317. S.Diag(BlockArg->getLocStart(),
  318. diag::err_opencl_builtin_expected_type)
  319. << TheCall->getDirectCallee() << "block";
  320. return true;
  321. }
  322. return checkOpenCLBlockArgs(S, BlockArg);
  323. }
  324. /// Diagnose integer type and any valid implicit conversion to it.
  325. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  326. const QualType &IntType);
  327. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  328. unsigned Start, unsigned End) {
  329. bool IllegalParams = false;
  330. for (unsigned I = Start; I <= End; ++I)
  331. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  332. S.Context.getSizeType());
  333. return IllegalParams;
  334. }
  335. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  336. /// 'local void*' parameter of passed block.
  337. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  338. Expr *BlockArg,
  339. unsigned NumNonVarArgs) {
  340. const BlockPointerType *BPT =
  341. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  342. unsigned NumBlockParams =
  343. BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
  344. unsigned TotalNumArgs = TheCall->getNumArgs();
  345. // For each argument passed to the block, a corresponding uint needs to
  346. // be passed to describe the size of the local memory.
  347. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  348. S.Diag(TheCall->getLocStart(),
  349. diag::err_opencl_enqueue_kernel_local_size_args);
  350. return true;
  351. }
  352. // Check that the sizes of the local memory are specified by integers.
  353. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  354. TotalNumArgs - 1);
  355. }
  356. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  357. /// overload formats specified in Table 6.13.17.1.
  358. /// int enqueue_kernel(queue_t queue,
  359. /// kernel_enqueue_flags_t flags,
  360. /// const ndrange_t ndrange,
  361. /// void (^block)(void))
  362. /// int enqueue_kernel(queue_t queue,
  363. /// kernel_enqueue_flags_t flags,
  364. /// const ndrange_t ndrange,
  365. /// uint num_events_in_wait_list,
  366. /// clk_event_t *event_wait_list,
  367. /// clk_event_t *event_ret,
  368. /// void (^block)(void))
  369. /// int enqueue_kernel(queue_t queue,
  370. /// kernel_enqueue_flags_t flags,
  371. /// const ndrange_t ndrange,
  372. /// void (^block)(local void*, ...),
  373. /// uint size0, ...)
  374. /// int enqueue_kernel(queue_t queue,
  375. /// kernel_enqueue_flags_t flags,
  376. /// const ndrange_t ndrange,
  377. /// uint num_events_in_wait_list,
  378. /// clk_event_t *event_wait_list,
  379. /// clk_event_t *event_ret,
  380. /// void (^block)(local void*, ...),
  381. /// uint size0, ...)
  382. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  383. unsigned NumArgs = TheCall->getNumArgs();
  384. if (NumArgs < 4) {
  385. S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
  386. return true;
  387. }
  388. Expr *Arg0 = TheCall->getArg(0);
  389. Expr *Arg1 = TheCall->getArg(1);
  390. Expr *Arg2 = TheCall->getArg(2);
  391. Expr *Arg3 = TheCall->getArg(3);
  392. // First argument always needs to be a queue_t type.
  393. if (!Arg0->getType()->isQueueT()) {
  394. S.Diag(TheCall->getArg(0)->getLocStart(),
  395. diag::err_opencl_builtin_expected_type)
  396. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  397. return true;
  398. }
  399. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  400. if (!Arg1->getType()->isIntegerType()) {
  401. S.Diag(TheCall->getArg(1)->getLocStart(),
  402. diag::err_opencl_builtin_expected_type)
  403. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  404. return true;
  405. }
  406. // Third argument is always an ndrange_t type.
  407. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  408. S.Diag(TheCall->getArg(2)->getLocStart(),
  409. diag::err_opencl_builtin_expected_type)
  410. << TheCall->getDirectCallee() << "'ndrange_t'";
  411. return true;
  412. }
  413. // With four arguments, there is only one form that the function could be
  414. // called in: no events and no variable arguments.
  415. if (NumArgs == 4) {
  416. // check that the last argument is the right block type.
  417. if (!isBlockPointer(Arg3)) {
  418. S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
  419. << TheCall->getDirectCallee() << "block";
  420. return true;
  421. }
  422. // we have a block type, check the prototype
  423. const BlockPointerType *BPT =
  424. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  425. if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
  426. S.Diag(Arg3->getLocStart(),
  427. diag::err_opencl_enqueue_kernel_blocks_no_args);
  428. return true;
  429. }
  430. return false;
  431. }
  432. // we can have block + varargs.
  433. if (isBlockPointer(Arg3))
  434. return (checkOpenCLBlockArgs(S, Arg3) ||
  435. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  436. // last two cases with either exactly 7 args or 7 args and varargs.
  437. if (NumArgs >= 7) {
  438. // check common block argument.
  439. Expr *Arg6 = TheCall->getArg(6);
  440. if (!isBlockPointer(Arg6)) {
  441. S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
  442. << TheCall->getDirectCallee() << "block";
  443. return true;
  444. }
  445. if (checkOpenCLBlockArgs(S, Arg6))
  446. return true;
  447. // Forth argument has to be any integer type.
  448. if (!Arg3->getType()->isIntegerType()) {
  449. S.Diag(TheCall->getArg(3)->getLocStart(),
  450. diag::err_opencl_builtin_expected_type)
  451. << TheCall->getDirectCallee() << "integer";
  452. return true;
  453. }
  454. // check remaining common arguments.
  455. Expr *Arg4 = TheCall->getArg(4);
  456. Expr *Arg5 = TheCall->getArg(5);
  457. // Fifth argument is always passed as a pointer to clk_event_t.
  458. if (!Arg4->isNullPointerConstant(S.Context,
  459. Expr::NPC_ValueDependentIsNotNull) &&
  460. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  461. S.Diag(TheCall->getArg(4)->getLocStart(),
  462. diag::err_opencl_builtin_expected_type)
  463. << TheCall->getDirectCallee()
  464. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  465. return true;
  466. }
  467. // Sixth argument is always passed as a pointer to clk_event_t.
  468. if (!Arg5->isNullPointerConstant(S.Context,
  469. Expr::NPC_ValueDependentIsNotNull) &&
  470. !(Arg5->getType()->isPointerType() &&
  471. Arg5->getType()->getPointeeType()->isClkEventT())) {
  472. S.Diag(TheCall->getArg(5)->getLocStart(),
  473. diag::err_opencl_builtin_expected_type)
  474. << TheCall->getDirectCallee()
  475. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  476. return true;
  477. }
  478. if (NumArgs == 7)
  479. return false;
  480. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  481. }
  482. // None of the specific case has been detected, give generic error
  483. S.Diag(TheCall->getLocStart(),
  484. diag::err_opencl_enqueue_kernel_incorrect_args);
  485. return true;
  486. }
  487. /// Returns OpenCL access qual.
  488. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  489. return D->getAttr<OpenCLAccessAttr>();
  490. }
  491. /// Returns true if pipe element type is different from the pointer.
  492. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  493. const Expr *Arg0 = Call->getArg(0);
  494. // First argument type should always be pipe.
  495. if (!Arg0->getType()->isPipeType()) {
  496. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
  497. << Call->getDirectCallee() << Arg0->getSourceRange();
  498. return true;
  499. }
  500. OpenCLAccessAttr *AccessQual =
  501. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  502. // Validates the access qualifier is compatible with the call.
  503. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  504. // read_only and write_only, and assumed to be read_only if no qualifier is
  505. // specified.
  506. switch (Call->getDirectCallee()->getBuiltinID()) {
  507. case Builtin::BIread_pipe:
  508. case Builtin::BIreserve_read_pipe:
  509. case Builtin::BIcommit_read_pipe:
  510. case Builtin::BIwork_group_reserve_read_pipe:
  511. case Builtin::BIsub_group_reserve_read_pipe:
  512. case Builtin::BIwork_group_commit_read_pipe:
  513. case Builtin::BIsub_group_commit_read_pipe:
  514. if (!(!AccessQual || AccessQual->isReadOnly())) {
  515. S.Diag(Arg0->getLocStart(),
  516. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  517. << "read_only" << Arg0->getSourceRange();
  518. return true;
  519. }
  520. break;
  521. case Builtin::BIwrite_pipe:
  522. case Builtin::BIreserve_write_pipe:
  523. case Builtin::BIcommit_write_pipe:
  524. case Builtin::BIwork_group_reserve_write_pipe:
  525. case Builtin::BIsub_group_reserve_write_pipe:
  526. case Builtin::BIwork_group_commit_write_pipe:
  527. case Builtin::BIsub_group_commit_write_pipe:
  528. if (!(AccessQual && AccessQual->isWriteOnly())) {
  529. S.Diag(Arg0->getLocStart(),
  530. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  531. << "write_only" << Arg0->getSourceRange();
  532. return true;
  533. }
  534. break;
  535. default:
  536. break;
  537. }
  538. return false;
  539. }
  540. /// Returns true if pipe element type is different from the pointer.
  541. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  542. const Expr *Arg0 = Call->getArg(0);
  543. const Expr *ArgIdx = Call->getArg(Idx);
  544. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  545. const QualType EltTy = PipeTy->getElementType();
  546. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  547. // The Idx argument should be a pointer and the type of the pointer and
  548. // the type of pipe element should also be the same.
  549. if (!ArgTy ||
  550. !S.Context.hasSameType(
  551. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  552. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  553. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  554. << ArgIdx->getType() << ArgIdx->getSourceRange();
  555. return true;
  556. }
  557. return false;
  558. }
  559. // \brief Performs semantic analysis for the read/write_pipe call.
  560. // \param S Reference to the semantic analyzer.
  561. // \param Call A pointer to the builtin call.
  562. // \return True if a semantic error has been found, false otherwise.
  563. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  564. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  565. // functions have two forms.
  566. switch (Call->getNumArgs()) {
  567. case 2: {
  568. if (checkOpenCLPipeArg(S, Call))
  569. return true;
  570. // The call with 2 arguments should be
  571. // read/write_pipe(pipe T, T*).
  572. // Check packet type T.
  573. if (checkOpenCLPipePacketType(S, Call, 1))
  574. return true;
  575. } break;
  576. case 4: {
  577. if (checkOpenCLPipeArg(S, Call))
  578. return true;
  579. // The call with 4 arguments should be
  580. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  581. // Check reserve_id_t.
  582. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  583. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  584. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  585. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  586. return true;
  587. }
  588. // Check the index.
  589. const Expr *Arg2 = Call->getArg(2);
  590. if (!Arg2->getType()->isIntegerType() &&
  591. !Arg2->getType()->isUnsignedIntegerType()) {
  592. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  593. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  594. << Arg2->getType() << Arg2->getSourceRange();
  595. return true;
  596. }
  597. // Check packet type T.
  598. if (checkOpenCLPipePacketType(S, Call, 3))
  599. return true;
  600. } break;
  601. default:
  602. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
  603. << Call->getDirectCallee() << Call->getSourceRange();
  604. return true;
  605. }
  606. return false;
  607. }
  608. // \brief Performs a semantic analysis on the {work_group_/sub_group_
  609. // /_}reserve_{read/write}_pipe
  610. // \param S Reference to the semantic analyzer.
  611. // \param Call The call to the builtin function to be analyzed.
  612. // \return True if a semantic error was found, false otherwise.
  613. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  614. if (checkArgCount(S, Call, 2))
  615. return true;
  616. if (checkOpenCLPipeArg(S, Call))
  617. return true;
  618. // Check the reserve size.
  619. if (!Call->getArg(1)->getType()->isIntegerType() &&
  620. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  621. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  622. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  623. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  624. return true;
  625. }
  626. // Since return type of reserve_read/write_pipe built-in function is
  627. // reserve_id_t, which is not defined in the builtin def file , we used int
  628. // as return type and need to override the return type of these functions.
  629. Call->setType(S.Context.OCLReserveIDTy);
  630. return false;
  631. }
  632. // \brief Performs a semantic analysis on {work_group_/sub_group_
  633. // /_}commit_{read/write}_pipe
  634. // \param S Reference to the semantic analyzer.
  635. // \param Call The call to the builtin function to be analyzed.
  636. // \return True if a semantic error was found, false otherwise.
  637. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  638. if (checkArgCount(S, Call, 2))
  639. return true;
  640. if (checkOpenCLPipeArg(S, Call))
  641. return true;
  642. // Check reserve_id_t.
  643. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  644. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  645. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  646. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  647. return true;
  648. }
  649. return false;
  650. }
  651. // \brief Performs a semantic analysis on the call to built-in Pipe
  652. // Query Functions.
  653. // \param S Reference to the semantic analyzer.
  654. // \param Call The call to the builtin function to be analyzed.
  655. // \return True if a semantic error was found, false otherwise.
  656. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  657. if (checkArgCount(S, Call, 1))
  658. return true;
  659. if (!Call->getArg(0)->getType()->isPipeType()) {
  660. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
  661. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  662. return true;
  663. }
  664. return false;
  665. }
  666. // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  667. // \brief Performs semantic analysis for the to_global/local/private call.
  668. // \param S Reference to the semantic analyzer.
  669. // \param BuiltinID ID of the builtin function.
  670. // \param Call A pointer to the builtin call.
  671. // \return True if a semantic error has been found, false otherwise.
  672. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  673. CallExpr *Call) {
  674. if (Call->getNumArgs() != 1) {
  675. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
  676. << Call->getDirectCallee() << Call->getSourceRange();
  677. return true;
  678. }
  679. auto RT = Call->getArg(0)->getType();
  680. if (!RT->isPointerType() || RT->getPointeeType()
  681. .getAddressSpace() == LangAS::opencl_constant) {
  682. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
  683. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  684. return true;
  685. }
  686. RT = RT->getPointeeType();
  687. auto Qual = RT.getQualifiers();
  688. switch (BuiltinID) {
  689. case Builtin::BIto_global:
  690. Qual.setAddressSpace(LangAS::opencl_global);
  691. break;
  692. case Builtin::BIto_local:
  693. Qual.setAddressSpace(LangAS::opencl_local);
  694. break;
  695. case Builtin::BIto_private:
  696. Qual.setAddressSpace(LangAS::opencl_private);
  697. break;
  698. default:
  699. llvm_unreachable("Invalid builtin function");
  700. }
  701. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  702. RT.getUnqualifiedType(), Qual)));
  703. return false;
  704. }
  705. ExprResult
  706. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  707. CallExpr *TheCall) {
  708. ExprResult TheCallResult(TheCall);
  709. // Find out if any arguments are required to be integer constant expressions.
  710. unsigned ICEArguments = 0;
  711. ASTContext::GetBuiltinTypeError Error;
  712. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  713. if (Error != ASTContext::GE_None)
  714. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  715. // If any arguments are required to be ICE's, check and diagnose.
  716. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  717. // Skip arguments not required to be ICE's.
  718. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  719. llvm::APSInt Result;
  720. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  721. return true;
  722. ICEArguments &= ~(1 << ArgNo);
  723. }
  724. switch (BuiltinID) {
  725. case Builtin::BI__builtin___CFStringMakeConstantString:
  726. assert(TheCall->getNumArgs() == 1 &&
  727. "Wrong # arguments to builtin CFStringMakeConstantString");
  728. if (CheckObjCString(TheCall->getArg(0)))
  729. return ExprError();
  730. break;
  731. case Builtin::BI__builtin_ms_va_start:
  732. case Builtin::BI__builtin_stdarg_start:
  733. case Builtin::BI__builtin_va_start:
  734. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  735. return ExprError();
  736. break;
  737. case Builtin::BI__va_start: {
  738. switch (Context.getTargetInfo().getTriple().getArch()) {
  739. case llvm::Triple::arm:
  740. case llvm::Triple::thumb:
  741. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  742. return ExprError();
  743. break;
  744. default:
  745. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  746. return ExprError();
  747. break;
  748. }
  749. break;
  750. }
  751. case Builtin::BI__builtin_isgreater:
  752. case Builtin::BI__builtin_isgreaterequal:
  753. case Builtin::BI__builtin_isless:
  754. case Builtin::BI__builtin_islessequal:
  755. case Builtin::BI__builtin_islessgreater:
  756. case Builtin::BI__builtin_isunordered:
  757. if (SemaBuiltinUnorderedCompare(TheCall))
  758. return ExprError();
  759. break;
  760. case Builtin::BI__builtin_fpclassify:
  761. if (SemaBuiltinFPClassification(TheCall, 6))
  762. return ExprError();
  763. break;
  764. case Builtin::BI__builtin_isfinite:
  765. case Builtin::BI__builtin_isinf:
  766. case Builtin::BI__builtin_isinf_sign:
  767. case Builtin::BI__builtin_isnan:
  768. case Builtin::BI__builtin_isnormal:
  769. if (SemaBuiltinFPClassification(TheCall, 1))
  770. return ExprError();
  771. break;
  772. case Builtin::BI__builtin_shufflevector:
  773. return SemaBuiltinShuffleVector(TheCall);
  774. // TheCall will be freed by the smart pointer here, but that's fine, since
  775. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  776. case Builtin::BI__builtin_prefetch:
  777. if (SemaBuiltinPrefetch(TheCall))
  778. return ExprError();
  779. break;
  780. case Builtin::BI__builtin_alloca_with_align:
  781. if (SemaBuiltinAllocaWithAlign(TheCall))
  782. return ExprError();
  783. break;
  784. case Builtin::BI__assume:
  785. case Builtin::BI__builtin_assume:
  786. if (SemaBuiltinAssume(TheCall))
  787. return ExprError();
  788. break;
  789. case Builtin::BI__builtin_assume_aligned:
  790. if (SemaBuiltinAssumeAligned(TheCall))
  791. return ExprError();
  792. break;
  793. case Builtin::BI__builtin_object_size:
  794. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  795. return ExprError();
  796. break;
  797. case Builtin::BI__builtin_longjmp:
  798. if (SemaBuiltinLongjmp(TheCall))
  799. return ExprError();
  800. break;
  801. case Builtin::BI__builtin_setjmp:
  802. if (SemaBuiltinSetjmp(TheCall))
  803. return ExprError();
  804. break;
  805. case Builtin::BI_setjmp:
  806. case Builtin::BI_setjmpex:
  807. if (checkArgCount(*this, TheCall, 1))
  808. return true;
  809. break;
  810. case Builtin::BI__builtin_classify_type:
  811. if (checkArgCount(*this, TheCall, 1)) return true;
  812. TheCall->setType(Context.IntTy);
  813. break;
  814. case Builtin::BI__builtin_constant_p:
  815. if (checkArgCount(*this, TheCall, 1)) return true;
  816. TheCall->setType(Context.IntTy);
  817. break;
  818. case Builtin::BI__sync_fetch_and_add:
  819. case Builtin::BI__sync_fetch_and_add_1:
  820. case Builtin::BI__sync_fetch_and_add_2:
  821. case Builtin::BI__sync_fetch_and_add_4:
  822. case Builtin::BI__sync_fetch_and_add_8:
  823. case Builtin::BI__sync_fetch_and_add_16:
  824. case Builtin::BI__sync_fetch_and_sub:
  825. case Builtin::BI__sync_fetch_and_sub_1:
  826. case Builtin::BI__sync_fetch_and_sub_2:
  827. case Builtin::BI__sync_fetch_and_sub_4:
  828. case Builtin::BI__sync_fetch_and_sub_8:
  829. case Builtin::BI__sync_fetch_and_sub_16:
  830. case Builtin::BI__sync_fetch_and_or:
  831. case Builtin::BI__sync_fetch_and_or_1:
  832. case Builtin::BI__sync_fetch_and_or_2:
  833. case Builtin::BI__sync_fetch_and_or_4:
  834. case Builtin::BI__sync_fetch_and_or_8:
  835. case Builtin::BI__sync_fetch_and_or_16:
  836. case Builtin::BI__sync_fetch_and_and:
  837. case Builtin::BI__sync_fetch_and_and_1:
  838. case Builtin::BI__sync_fetch_and_and_2:
  839. case Builtin::BI__sync_fetch_and_and_4:
  840. case Builtin::BI__sync_fetch_and_and_8:
  841. case Builtin::BI__sync_fetch_and_and_16:
  842. case Builtin::BI__sync_fetch_and_xor:
  843. case Builtin::BI__sync_fetch_and_xor_1:
  844. case Builtin::BI__sync_fetch_and_xor_2:
  845. case Builtin::BI__sync_fetch_and_xor_4:
  846. case Builtin::BI__sync_fetch_and_xor_8:
  847. case Builtin::BI__sync_fetch_and_xor_16:
  848. case Builtin::BI__sync_fetch_and_nand:
  849. case Builtin::BI__sync_fetch_and_nand_1:
  850. case Builtin::BI__sync_fetch_and_nand_2:
  851. case Builtin::BI__sync_fetch_and_nand_4:
  852. case Builtin::BI__sync_fetch_and_nand_8:
  853. case Builtin::BI__sync_fetch_and_nand_16:
  854. case Builtin::BI__sync_add_and_fetch:
  855. case Builtin::BI__sync_add_and_fetch_1:
  856. case Builtin::BI__sync_add_and_fetch_2:
  857. case Builtin::BI__sync_add_and_fetch_4:
  858. case Builtin::BI__sync_add_and_fetch_8:
  859. case Builtin::BI__sync_add_and_fetch_16:
  860. case Builtin::BI__sync_sub_and_fetch:
  861. case Builtin::BI__sync_sub_and_fetch_1:
  862. case Builtin::BI__sync_sub_and_fetch_2:
  863. case Builtin::BI__sync_sub_and_fetch_4:
  864. case Builtin::BI__sync_sub_and_fetch_8:
  865. case Builtin::BI__sync_sub_and_fetch_16:
  866. case Builtin::BI__sync_and_and_fetch:
  867. case Builtin::BI__sync_and_and_fetch_1:
  868. case Builtin::BI__sync_and_and_fetch_2:
  869. case Builtin::BI__sync_and_and_fetch_4:
  870. case Builtin::BI__sync_and_and_fetch_8:
  871. case Builtin::BI__sync_and_and_fetch_16:
  872. case Builtin::BI__sync_or_and_fetch:
  873. case Builtin::BI__sync_or_and_fetch_1:
  874. case Builtin::BI__sync_or_and_fetch_2:
  875. case Builtin::BI__sync_or_and_fetch_4:
  876. case Builtin::BI__sync_or_and_fetch_8:
  877. case Builtin::BI__sync_or_and_fetch_16:
  878. case Builtin::BI__sync_xor_and_fetch:
  879. case Builtin::BI__sync_xor_and_fetch_1:
  880. case Builtin::BI__sync_xor_and_fetch_2:
  881. case Builtin::BI__sync_xor_and_fetch_4:
  882. case Builtin::BI__sync_xor_and_fetch_8:
  883. case Builtin::BI__sync_xor_and_fetch_16:
  884. case Builtin::BI__sync_nand_and_fetch:
  885. case Builtin::BI__sync_nand_and_fetch_1:
  886. case Builtin::BI__sync_nand_and_fetch_2:
  887. case Builtin::BI__sync_nand_and_fetch_4:
  888. case Builtin::BI__sync_nand_and_fetch_8:
  889. case Builtin::BI__sync_nand_and_fetch_16:
  890. case Builtin::BI__sync_val_compare_and_swap:
  891. case Builtin::BI__sync_val_compare_and_swap_1:
  892. case Builtin::BI__sync_val_compare_and_swap_2:
  893. case Builtin::BI__sync_val_compare_and_swap_4:
  894. case Builtin::BI__sync_val_compare_and_swap_8:
  895. case Builtin::BI__sync_val_compare_and_swap_16:
  896. case Builtin::BI__sync_bool_compare_and_swap:
  897. case Builtin::BI__sync_bool_compare_and_swap_1:
  898. case Builtin::BI__sync_bool_compare_and_swap_2:
  899. case Builtin::BI__sync_bool_compare_and_swap_4:
  900. case Builtin::BI__sync_bool_compare_and_swap_8:
  901. case Builtin::BI__sync_bool_compare_and_swap_16:
  902. case Builtin::BI__sync_lock_test_and_set:
  903. case Builtin::BI__sync_lock_test_and_set_1:
  904. case Builtin::BI__sync_lock_test_and_set_2:
  905. case Builtin::BI__sync_lock_test_and_set_4:
  906. case Builtin::BI__sync_lock_test_and_set_8:
  907. case Builtin::BI__sync_lock_test_and_set_16:
  908. case Builtin::BI__sync_lock_release:
  909. case Builtin::BI__sync_lock_release_1:
  910. case Builtin::BI__sync_lock_release_2:
  911. case Builtin::BI__sync_lock_release_4:
  912. case Builtin::BI__sync_lock_release_8:
  913. case Builtin::BI__sync_lock_release_16:
  914. case Builtin::BI__sync_swap:
  915. case Builtin::BI__sync_swap_1:
  916. case Builtin::BI__sync_swap_2:
  917. case Builtin::BI__sync_swap_4:
  918. case Builtin::BI__sync_swap_8:
  919. case Builtin::BI__sync_swap_16:
  920. return SemaBuiltinAtomicOverloaded(TheCallResult);
  921. case Builtin::BI__builtin_nontemporal_load:
  922. case Builtin::BI__builtin_nontemporal_store:
  923. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  924. #define BUILTIN(ID, TYPE, ATTRS)
  925. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  926. case Builtin::BI##ID: \
  927. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  928. #include "clang/Basic/Builtins.def"
  929. case Builtin::BI__annotation:
  930. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  931. return ExprError();
  932. break;
  933. case Builtin::BI__builtin_annotation:
  934. if (SemaBuiltinAnnotation(*this, TheCall))
  935. return ExprError();
  936. break;
  937. case Builtin::BI__builtin_addressof:
  938. if (SemaBuiltinAddressof(*this, TheCall))
  939. return ExprError();
  940. break;
  941. case Builtin::BI__builtin_add_overflow:
  942. case Builtin::BI__builtin_sub_overflow:
  943. case Builtin::BI__builtin_mul_overflow:
  944. if (SemaBuiltinOverflow(*this, TheCall))
  945. return ExprError();
  946. break;
  947. case Builtin::BI__builtin_operator_new:
  948. case Builtin::BI__builtin_operator_delete:
  949. if (!getLangOpts().CPlusPlus) {
  950. Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
  951. << (BuiltinID == Builtin::BI__builtin_operator_new
  952. ? "__builtin_operator_new"
  953. : "__builtin_operator_delete")
  954. << "C++";
  955. return ExprError();
  956. }
  957. // CodeGen assumes it can find the global new and delete to call,
  958. // so ensure that they are declared.
  959. DeclareGlobalNewDelete();
  960. break;
  961. // check secure string manipulation functions where overflows
  962. // are detectable at compile time
  963. case Builtin::BI__builtin___memcpy_chk:
  964. case Builtin::BI__builtin___memmove_chk:
  965. case Builtin::BI__builtin___memset_chk:
  966. case Builtin::BI__builtin___strlcat_chk:
  967. case Builtin::BI__builtin___strlcpy_chk:
  968. case Builtin::BI__builtin___strncat_chk:
  969. case Builtin::BI__builtin___strncpy_chk:
  970. case Builtin::BI__builtin___stpncpy_chk:
  971. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
  972. break;
  973. case Builtin::BI__builtin___memccpy_chk:
  974. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
  975. break;
  976. case Builtin::BI__builtin___snprintf_chk:
  977. case Builtin::BI__builtin___vsnprintf_chk:
  978. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
  979. break;
  980. case Builtin::BI__builtin_call_with_static_chain:
  981. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  982. return ExprError();
  983. break;
  984. case Builtin::BI__exception_code:
  985. case Builtin::BI_exception_code:
  986. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  987. diag::err_seh___except_block))
  988. return ExprError();
  989. break;
  990. case Builtin::BI__exception_info:
  991. case Builtin::BI_exception_info:
  992. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  993. diag::err_seh___except_filter))
  994. return ExprError();
  995. break;
  996. case Builtin::BI__GetExceptionInfo:
  997. if (checkArgCount(*this, TheCall, 1))
  998. return ExprError();
  999. if (CheckCXXThrowOperand(
  1000. TheCall->getLocStart(),
  1001. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1002. TheCall))
  1003. return ExprError();
  1004. TheCall->setType(Context.VoidPtrTy);
  1005. break;
  1006. // OpenCL v2.0, s6.13.16 - Pipe functions
  1007. case Builtin::BIread_pipe:
  1008. case Builtin::BIwrite_pipe:
  1009. // Since those two functions are declared with var args, we need a semantic
  1010. // check for the argument.
  1011. if (SemaBuiltinRWPipe(*this, TheCall))
  1012. return ExprError();
  1013. TheCall->setType(Context.IntTy);
  1014. break;
  1015. case Builtin::BIreserve_read_pipe:
  1016. case Builtin::BIreserve_write_pipe:
  1017. case Builtin::BIwork_group_reserve_read_pipe:
  1018. case Builtin::BIwork_group_reserve_write_pipe:
  1019. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1020. return ExprError();
  1021. break;
  1022. case Builtin::BIsub_group_reserve_read_pipe:
  1023. case Builtin::BIsub_group_reserve_write_pipe:
  1024. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1025. SemaBuiltinReserveRWPipe(*this, TheCall))
  1026. return ExprError();
  1027. break;
  1028. case Builtin::BIcommit_read_pipe:
  1029. case Builtin::BIcommit_write_pipe:
  1030. case Builtin::BIwork_group_commit_read_pipe:
  1031. case Builtin::BIwork_group_commit_write_pipe:
  1032. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1033. return ExprError();
  1034. break;
  1035. case Builtin::BIsub_group_commit_read_pipe:
  1036. case Builtin::BIsub_group_commit_write_pipe:
  1037. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1038. SemaBuiltinCommitRWPipe(*this, TheCall))
  1039. return ExprError();
  1040. break;
  1041. case Builtin::BIget_pipe_num_packets:
  1042. case Builtin::BIget_pipe_max_packets:
  1043. if (SemaBuiltinPipePackets(*this, TheCall))
  1044. return ExprError();
  1045. TheCall->setType(Context.UnsignedIntTy);
  1046. break;
  1047. case Builtin::BIto_global:
  1048. case Builtin::BIto_local:
  1049. case Builtin::BIto_private:
  1050. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1051. return ExprError();
  1052. break;
  1053. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1054. case Builtin::BIenqueue_kernel:
  1055. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1056. return ExprError();
  1057. break;
  1058. case Builtin::BIget_kernel_work_group_size:
  1059. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1060. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1061. return ExprError();
  1062. break;
  1063. break;
  1064. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1065. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1066. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1067. return ExprError();
  1068. break;
  1069. case Builtin::BI__builtin_os_log_format:
  1070. case Builtin::BI__builtin_os_log_format_buffer_size:
  1071. if (SemaBuiltinOSLogFormat(TheCall)) {
  1072. return ExprError();
  1073. }
  1074. break;
  1075. }
  1076. // Since the target specific builtins for each arch overlap, only check those
  1077. // of the arch we are compiling for.
  1078. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  1079. switch (Context.getTargetInfo().getTriple().getArch()) {
  1080. case llvm::Triple::arm:
  1081. case llvm::Triple::armeb:
  1082. case llvm::Triple::thumb:
  1083. case llvm::Triple::thumbeb:
  1084. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  1085. return ExprError();
  1086. break;
  1087. case llvm::Triple::aarch64:
  1088. case llvm::Triple::aarch64_be:
  1089. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  1090. return ExprError();
  1091. break;
  1092. case llvm::Triple::mips:
  1093. case llvm::Triple::mipsel:
  1094. case llvm::Triple::mips64:
  1095. case llvm::Triple::mips64el:
  1096. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  1097. return ExprError();
  1098. break;
  1099. case llvm::Triple::systemz:
  1100. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  1101. return ExprError();
  1102. break;
  1103. case llvm::Triple::x86:
  1104. case llvm::Triple::x86_64:
  1105. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  1106. return ExprError();
  1107. break;
  1108. case llvm::Triple::ppc:
  1109. case llvm::Triple::ppc64:
  1110. case llvm::Triple::ppc64le:
  1111. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  1112. return ExprError();
  1113. break;
  1114. default:
  1115. break;
  1116. }
  1117. }
  1118. return TheCallResult;
  1119. }
  1120. // Get the valid immediate range for the specified NEON type code.
  1121. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  1122. NeonTypeFlags Type(t);
  1123. int IsQuad = ForceQuad ? true : Type.isQuad();
  1124. switch (Type.getEltType()) {
  1125. case NeonTypeFlags::Int8:
  1126. case NeonTypeFlags::Poly8:
  1127. return shift ? 7 : (8 << IsQuad) - 1;
  1128. case NeonTypeFlags::Int16:
  1129. case NeonTypeFlags::Poly16:
  1130. return shift ? 15 : (4 << IsQuad) - 1;
  1131. case NeonTypeFlags::Int32:
  1132. return shift ? 31 : (2 << IsQuad) - 1;
  1133. case NeonTypeFlags::Int64:
  1134. case NeonTypeFlags::Poly64:
  1135. return shift ? 63 : (1 << IsQuad) - 1;
  1136. case NeonTypeFlags::Poly128:
  1137. return shift ? 127 : (1 << IsQuad) - 1;
  1138. case NeonTypeFlags::Float16:
  1139. assert(!shift && "cannot shift float types!");
  1140. return (4 << IsQuad) - 1;
  1141. case NeonTypeFlags::Float32:
  1142. assert(!shift && "cannot shift float types!");
  1143. return (2 << IsQuad) - 1;
  1144. case NeonTypeFlags::Float64:
  1145. assert(!shift && "cannot shift float types!");
  1146. return (1 << IsQuad) - 1;
  1147. }
  1148. llvm_unreachable("Invalid NeonTypeFlag!");
  1149. }
  1150. /// getNeonEltType - Return the QualType corresponding to the elements of
  1151. /// the vector type specified by the NeonTypeFlags. This is used to check
  1152. /// the pointer arguments for Neon load/store intrinsics.
  1153. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  1154. bool IsPolyUnsigned, bool IsInt64Long) {
  1155. switch (Flags.getEltType()) {
  1156. case NeonTypeFlags::Int8:
  1157. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  1158. case NeonTypeFlags::Int16:
  1159. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  1160. case NeonTypeFlags::Int32:
  1161. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  1162. case NeonTypeFlags::Int64:
  1163. if (IsInt64Long)
  1164. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  1165. else
  1166. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  1167. : Context.LongLongTy;
  1168. case NeonTypeFlags::Poly8:
  1169. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  1170. case NeonTypeFlags::Poly16:
  1171. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  1172. case NeonTypeFlags::Poly64:
  1173. if (IsInt64Long)
  1174. return Context.UnsignedLongTy;
  1175. else
  1176. return Context.UnsignedLongLongTy;
  1177. case NeonTypeFlags::Poly128:
  1178. break;
  1179. case NeonTypeFlags::Float16:
  1180. return Context.HalfTy;
  1181. case NeonTypeFlags::Float32:
  1182. return Context.FloatTy;
  1183. case NeonTypeFlags::Float64:
  1184. return Context.DoubleTy;
  1185. }
  1186. llvm_unreachable("Invalid NeonTypeFlag!");
  1187. }
  1188. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1189. llvm::APSInt Result;
  1190. uint64_t mask = 0;
  1191. unsigned TV = 0;
  1192. int PtrArgNum = -1;
  1193. bool HasConstPtr = false;
  1194. switch (BuiltinID) {
  1195. #define GET_NEON_OVERLOAD_CHECK
  1196. #include "clang/Basic/arm_neon.inc"
  1197. #undef GET_NEON_OVERLOAD_CHECK
  1198. }
  1199. // For NEON intrinsics which are overloaded on vector element type, validate
  1200. // the immediate which specifies which variant to emit.
  1201. unsigned ImmArg = TheCall->getNumArgs()-1;
  1202. if (mask) {
  1203. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  1204. return true;
  1205. TV = Result.getLimitedValue(64);
  1206. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  1207. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  1208. << TheCall->getArg(ImmArg)->getSourceRange();
  1209. }
  1210. if (PtrArgNum >= 0) {
  1211. // Check that pointer arguments have the specified type.
  1212. Expr *Arg = TheCall->getArg(PtrArgNum);
  1213. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  1214. Arg = ICE->getSubExpr();
  1215. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  1216. QualType RHSTy = RHS.get()->getType();
  1217. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  1218. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  1219. Arch == llvm::Triple::aarch64_be;
  1220. bool IsInt64Long =
  1221. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  1222. QualType EltTy =
  1223. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  1224. if (HasConstPtr)
  1225. EltTy = EltTy.withConst();
  1226. QualType LHSTy = Context.getPointerType(EltTy);
  1227. AssignConvertType ConvTy;
  1228. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  1229. if (RHS.isInvalid())
  1230. return true;
  1231. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  1232. RHS.get(), AA_Assigning))
  1233. return true;
  1234. }
  1235. // For NEON intrinsics which take an immediate value as part of the
  1236. // instruction, range check them here.
  1237. unsigned i = 0, l = 0, u = 0;
  1238. switch (BuiltinID) {
  1239. default:
  1240. return false;
  1241. #define GET_NEON_IMMEDIATE_CHECK
  1242. #include "clang/Basic/arm_neon.inc"
  1243. #undef GET_NEON_IMMEDIATE_CHECK
  1244. }
  1245. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1246. }
  1247. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  1248. unsigned MaxWidth) {
  1249. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1250. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1251. BuiltinID == ARM::BI__builtin_arm_strex ||
  1252. BuiltinID == ARM::BI__builtin_arm_stlex ||
  1253. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1254. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1255. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1256. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  1257. "unexpected ARM builtin");
  1258. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1259. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1260. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1261. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  1262. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1263. // Ensure that we have the proper number of arguments.
  1264. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  1265. return true;
  1266. // Inspect the pointer argument of the atomic builtin. This should always be
  1267. // a pointer type, whose element is an integral scalar or pointer type.
  1268. // Because it is a pointer type, we don't have to worry about any implicit
  1269. // casts here.
  1270. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  1271. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  1272. if (PointerArgRes.isInvalid())
  1273. return true;
  1274. PointerArg = PointerArgRes.get();
  1275. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  1276. if (!pointerType) {
  1277. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  1278. << PointerArg->getType() << PointerArg->getSourceRange();
  1279. return true;
  1280. }
  1281. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  1282. // task is to insert the appropriate casts into the AST. First work out just
  1283. // what the appropriate type is.
  1284. QualType ValType = pointerType->getPointeeType();
  1285. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  1286. if (IsLdrex)
  1287. AddrType.addConst();
  1288. // Issue a warning if the cast is dodgy.
  1289. CastKind CastNeeded = CK_NoOp;
  1290. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  1291. CastNeeded = CK_BitCast;
  1292. Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
  1293. << PointerArg->getType()
  1294. << Context.getPointerType(AddrType)
  1295. << AA_Passing << PointerArg->getSourceRange();
  1296. }
  1297. // Finally, do the cast and replace the argument with the corrected version.
  1298. AddrType = Context.getPointerType(AddrType);
  1299. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  1300. if (PointerArgRes.isInvalid())
  1301. return true;
  1302. PointerArg = PointerArgRes.get();
  1303. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  1304. // In general, we allow ints, floats and pointers to be loaded and stored.
  1305. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1306. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  1307. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  1308. << PointerArg->getType() << PointerArg->getSourceRange();
  1309. return true;
  1310. }
  1311. // But ARM doesn't have instructions to deal with 128-bit versions.
  1312. if (Context.getTypeSize(ValType) > MaxWidth) {
  1313. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  1314. Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
  1315. << PointerArg->getType() << PointerArg->getSourceRange();
  1316. return true;
  1317. }
  1318. switch (ValType.getObjCLifetime()) {
  1319. case Qualifiers::OCL_None:
  1320. case Qualifiers::OCL_ExplicitNone:
  1321. // okay
  1322. break;
  1323. case Qualifiers::OCL_Weak:
  1324. case Qualifiers::OCL_Strong:
  1325. case Qualifiers::OCL_Autoreleasing:
  1326. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  1327. << ValType << PointerArg->getSourceRange();
  1328. return true;
  1329. }
  1330. if (IsLdrex) {
  1331. TheCall->setType(ValType);
  1332. return false;
  1333. }
  1334. // Initialize the argument to be stored.
  1335. ExprResult ValArg = TheCall->getArg(0);
  1336. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  1337. Context, ValType, /*consume*/ false);
  1338. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  1339. if (ValArg.isInvalid())
  1340. return true;
  1341. TheCall->setArg(0, ValArg.get());
  1342. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  1343. // but the custom checker bypasses all default analysis.
  1344. TheCall->setType(Context.IntTy);
  1345. return false;
  1346. }
  1347. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1348. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1349. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1350. BuiltinID == ARM::BI__builtin_arm_strex ||
  1351. BuiltinID == ARM::BI__builtin_arm_stlex) {
  1352. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  1353. }
  1354. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  1355. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1356. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  1357. }
  1358. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  1359. BuiltinID == ARM::BI__builtin_arm_wsr64)
  1360. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  1361. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  1362. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  1363. BuiltinID == ARM::BI__builtin_arm_wsr ||
  1364. BuiltinID == ARM::BI__builtin_arm_wsrp)
  1365. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1366. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1367. return true;
  1368. // For intrinsics which take an immediate value as part of the instruction,
  1369. // range check them here.
  1370. unsigned i = 0, l = 0, u = 0;
  1371. switch (BuiltinID) {
  1372. default: return false;
  1373. case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
  1374. case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
  1375. case ARM::BI__builtin_arm_vcvtr_f:
  1376. case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
  1377. case ARM::BI__builtin_arm_dmb:
  1378. case ARM::BI__builtin_arm_dsb:
  1379. case ARM::BI__builtin_arm_isb:
  1380. case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
  1381. }
  1382. // FIXME: VFP Intrinsics should error if VFP not present.
  1383. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1384. }
  1385. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  1386. CallExpr *TheCall) {
  1387. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1388. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1389. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1390. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  1391. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  1392. }
  1393. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  1394. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1395. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  1396. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  1397. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  1398. }
  1399. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  1400. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  1401. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1402. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  1403. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  1404. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  1405. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  1406. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1407. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1408. return true;
  1409. // For intrinsics which take an immediate value as part of the instruction,
  1410. // range check them here.
  1411. unsigned i = 0, l = 0, u = 0;
  1412. switch (BuiltinID) {
  1413. default: return false;
  1414. case AArch64::BI__builtin_arm_dmb:
  1415. case AArch64::BI__builtin_arm_dsb:
  1416. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  1417. }
  1418. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1419. }
  1420. // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
  1421. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  1422. // ordering for DSP is unspecified. MSA is ordered by the data format used
  1423. // by the underlying instruction i.e., df/m, df/n and then by size.
  1424. //
  1425. // FIXME: The size tests here should instead be tablegen'd along with the
  1426. // definitions from include/clang/Basic/BuiltinsMips.def.
  1427. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  1428. // be too.
  1429. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1430. unsigned i = 0, l = 0, u = 0, m = 0;
  1431. switch (BuiltinID) {
  1432. default: return false;
  1433. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  1434. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  1435. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  1436. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  1437. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  1438. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  1439. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  1440. // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
  1441. // df/m field.
  1442. // These intrinsics take an unsigned 3 bit immediate.
  1443. case Mips::BI__builtin_msa_bclri_b:
  1444. case Mips::BI__builtin_msa_bnegi_b:
  1445. case Mips::BI__builtin_msa_bseti_b:
  1446. case Mips::BI__builtin_msa_sat_s_b:
  1447. case Mips::BI__builtin_msa_sat_u_b:
  1448. case Mips::BI__builtin_msa_slli_b:
  1449. case Mips::BI__builtin_msa_srai_b:
  1450. case Mips::BI__builtin_msa_srari_b:
  1451. case Mips::BI__builtin_msa_srli_b:
  1452. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  1453. case Mips::BI__builtin_msa_binsli_b:
  1454. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  1455. // These intrinsics take an unsigned 4 bit immediate.
  1456. case Mips::BI__builtin_msa_bclri_h:
  1457. case Mips::BI__builtin_msa_bnegi_h:
  1458. case Mips::BI__builtin_msa_bseti_h:
  1459. case Mips::BI__builtin_msa_sat_s_h:
  1460. case Mips::BI__builtin_msa_sat_u_h:
  1461. case Mips::BI__builtin_msa_slli_h:
  1462. case Mips::BI__builtin_msa_srai_h:
  1463. case Mips::BI__builtin_msa_srari_h:
  1464. case Mips::BI__builtin_msa_srli_h:
  1465. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  1466. case Mips::BI__builtin_msa_binsli_h:
  1467. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  1468. // These intrinsics take an unsigned 5 bit immedate.
  1469. // The first block of intrinsics actually have an unsigned 5 bit field,
  1470. // not a df/n field.
  1471. case Mips::BI__builtin_msa_clei_u_b:
  1472. case Mips::BI__builtin_msa_clei_u_h:
  1473. case Mips::BI__builtin_msa_clei_u_w:
  1474. case Mips::BI__builtin_msa_clei_u_d:
  1475. case Mips::BI__builtin_msa_clti_u_b:
  1476. case Mips::BI__builtin_msa_clti_u_h:
  1477. case Mips::BI__builtin_msa_clti_u_w:
  1478. case Mips::BI__builtin_msa_clti_u_d:
  1479. case Mips::BI__builtin_msa_maxi_u_b:
  1480. case Mips::BI__builtin_msa_maxi_u_h:
  1481. case Mips::BI__builtin_msa_maxi_u_w:
  1482. case Mips::BI__builtin_msa_maxi_u_d:
  1483. case Mips::BI__builtin_msa_mini_u_b:
  1484. case Mips::BI__builtin_msa_mini_u_h:
  1485. case Mips::BI__builtin_msa_mini_u_w:
  1486. case Mips::BI__builtin_msa_mini_u_d:
  1487. case Mips::BI__builtin_msa_addvi_b:
  1488. case Mips::BI__builtin_msa_addvi_h:
  1489. case Mips::BI__builtin_msa_addvi_w:
  1490. case Mips::BI__builtin_msa_addvi_d:
  1491. case Mips::BI__builtin_msa_bclri_w:
  1492. case Mips::BI__builtin_msa_bnegi_w:
  1493. case Mips::BI__builtin_msa_bseti_w:
  1494. case Mips::BI__builtin_msa_sat_s_w:
  1495. case Mips::BI__builtin_msa_sat_u_w:
  1496. case Mips::BI__builtin_msa_slli_w:
  1497. case Mips::BI__builtin_msa_srai_w:
  1498. case Mips::BI__builtin_msa_srari_w:
  1499. case Mips::BI__builtin_msa_srli_w:
  1500. case Mips::BI__builtin_msa_srlri_w:
  1501. case Mips::BI__builtin_msa_subvi_b:
  1502. case Mips::BI__builtin_msa_subvi_h:
  1503. case Mips::BI__builtin_msa_subvi_w:
  1504. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  1505. case Mips::BI__builtin_msa_binsli_w:
  1506. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  1507. // These intrinsics take an unsigned 6 bit immediate.
  1508. case Mips::BI__builtin_msa_bclri_d:
  1509. case Mips::BI__builtin_msa_bnegi_d:
  1510. case Mips::BI__builtin_msa_bseti_d:
  1511. case Mips::BI__builtin_msa_sat_s_d:
  1512. case Mips::BI__builtin_msa_sat_u_d:
  1513. case Mips::BI__builtin_msa_slli_d:
  1514. case Mips::BI__builtin_msa_srai_d:
  1515. case Mips::BI__builtin_msa_srari_d:
  1516. case Mips::BI__builtin_msa_srli_d:
  1517. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  1518. case Mips::BI__builtin_msa_binsli_d:
  1519. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  1520. // These intrinsics take a signed 5 bit immediate.
  1521. case Mips::BI__builtin_msa_ceqi_b:
  1522. case Mips::BI__builtin_msa_ceqi_h:
  1523. case Mips::BI__builtin_msa_ceqi_w:
  1524. case Mips::BI__builtin_msa_ceqi_d:
  1525. case Mips::BI__builtin_msa_clti_s_b:
  1526. case Mips::BI__builtin_msa_clti_s_h:
  1527. case Mips::BI__builtin_msa_clti_s_w:
  1528. case Mips::BI__builtin_msa_clti_s_d:
  1529. case Mips::BI__builtin_msa_clei_s_b:
  1530. case Mips::BI__builtin_msa_clei_s_h:
  1531. case Mips::BI__builtin_msa_clei_s_w:
  1532. case Mips::BI__builtin_msa_clei_s_d:
  1533. case Mips::BI__builtin_msa_maxi_s_b:
  1534. case Mips::BI__builtin_msa_maxi_s_h:
  1535. case Mips::BI__builtin_msa_maxi_s_w:
  1536. case Mips::BI__builtin_msa_maxi_s_d:
  1537. case Mips::BI__builtin_msa_mini_s_b:
  1538. case Mips::BI__builtin_msa_mini_s_h:
  1539. case Mips::BI__builtin_msa_mini_s_w:
  1540. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  1541. // These intrinsics take an unsigned 8 bit immediate.
  1542. case Mips::BI__builtin_msa_andi_b:
  1543. case Mips::BI__builtin_msa_nori_b:
  1544. case Mips::BI__builtin_msa_ori_b:
  1545. case Mips::BI__builtin_msa_shf_b:
  1546. case Mips::BI__builtin_msa_shf_h:
  1547. case Mips::BI__builtin_msa_shf_w:
  1548. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  1549. case Mips::BI__builtin_msa_bseli_b:
  1550. case Mips::BI__builtin_msa_bmnzi_b:
  1551. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  1552. // df/n format
  1553. // These intrinsics take an unsigned 4 bit immediate.
  1554. case Mips::BI__builtin_msa_copy_s_b:
  1555. case Mips::BI__builtin_msa_copy_u_b:
  1556. case Mips::BI__builtin_msa_insve_b:
  1557. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  1558. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  1559. // These intrinsics take an unsigned 3 bit immediate.
  1560. case Mips::BI__builtin_msa_copy_s_h:
  1561. case Mips::BI__builtin_msa_copy_u_h:
  1562. case Mips::BI__builtin_msa_insve_h:
  1563. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  1564. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  1565. // These intrinsics take an unsigned 2 bit immediate.
  1566. case Mips::BI__builtin_msa_copy_s_w:
  1567. case Mips::BI__builtin_msa_copy_u_w:
  1568. case Mips::BI__builtin_msa_insve_w:
  1569. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  1570. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  1571. // These intrinsics take an unsigned 1 bit immediate.
  1572. case Mips::BI__builtin_msa_copy_s_d:
  1573. case Mips::BI__builtin_msa_copy_u_d:
  1574. case Mips::BI__builtin_msa_insve_d:
  1575. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  1576. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  1577. // Memory offsets and immediate loads.
  1578. // These intrinsics take a signed 10 bit immediate.
  1579. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  1580. case Mips::BI__builtin_msa_ldi_h:
  1581. case Mips::BI__builtin_msa_ldi_w:
  1582. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  1583. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
  1584. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
  1585. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
  1586. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
  1587. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
  1588. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
  1589. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
  1590. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
  1591. }
  1592. if (!m)
  1593. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  1594. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  1595. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  1596. }
  1597. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1598. unsigned i = 0, l = 0, u = 0;
  1599. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  1600. BuiltinID == PPC::BI__builtin_divdeu ||
  1601. BuiltinID == PPC::BI__builtin_bpermd;
  1602. bool IsTarget64Bit = Context.getTargetInfo()
  1603. .getTypeWidth(Context
  1604. .getTargetInfo()
  1605. .getIntPtrType()) == 64;
  1606. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  1607. BuiltinID == PPC::BI__builtin_divweu ||
  1608. BuiltinID == PPC::BI__builtin_divde ||
  1609. BuiltinID == PPC::BI__builtin_divdeu;
  1610. if (Is64BitBltin && !IsTarget64Bit)
  1611. return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
  1612. << TheCall->getSourceRange();
  1613. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  1614. (BuiltinID == PPC::BI__builtin_bpermd &&
  1615. !Context.getTargetInfo().hasFeature("bpermd")))
  1616. return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
  1617. << TheCall->getSourceRange();
  1618. switch (BuiltinID) {
  1619. default: return false;
  1620. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  1621. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  1622. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1623. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  1624. case PPC::BI__builtin_tbegin:
  1625. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  1626. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  1627. case PPC::BI__builtin_tabortwc:
  1628. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  1629. case PPC::BI__builtin_tabortwci:
  1630. case PPC::BI__builtin_tabortdci:
  1631. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  1632. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  1633. case PPC::BI__builtin_vsx_xxpermdi:
  1634. case PPC::BI__builtin_vsx_xxsldwi:
  1635. return SemaBuiltinVSX(TheCall);
  1636. }
  1637. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  1638. }
  1639. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  1640. CallExpr *TheCall) {
  1641. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  1642. Expr *Arg = TheCall->getArg(0);
  1643. llvm::APSInt AbortCode(32);
  1644. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  1645. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  1646. return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
  1647. << Arg->getSourceRange();
  1648. }
  1649. // For intrinsics which take an immediate value as part of the instruction,
  1650. // range check them here.
  1651. unsigned i = 0, l = 0, u = 0;
  1652. switch (BuiltinID) {
  1653. default: return false;
  1654. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  1655. case SystemZ::BI__builtin_s390_verimb:
  1656. case SystemZ::BI__builtin_s390_verimh:
  1657. case SystemZ::BI__builtin_s390_verimf:
  1658. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  1659. case SystemZ::BI__builtin_s390_vfaeb:
  1660. case SystemZ::BI__builtin_s390_vfaeh:
  1661. case SystemZ::BI__builtin_s390_vfaef:
  1662. case SystemZ::BI__builtin_s390_vfaebs:
  1663. case SystemZ::BI__builtin_s390_vfaehs:
  1664. case SystemZ::BI__builtin_s390_vfaefs:
  1665. case SystemZ::BI__builtin_s390_vfaezb:
  1666. case SystemZ::BI__builtin_s390_vfaezh:
  1667. case SystemZ::BI__builtin_s390_vfaezf:
  1668. case SystemZ::BI__builtin_s390_vfaezbs:
  1669. case SystemZ::BI__builtin_s390_vfaezhs:
  1670. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  1671. case SystemZ::BI__builtin_s390_vfisb:
  1672. case SystemZ::BI__builtin_s390_vfidb:
  1673. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  1674. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  1675. case SystemZ::BI__builtin_s390_vftcisb:
  1676. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  1677. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  1678. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  1679. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  1680. case SystemZ::BI__builtin_s390_vstrcb:
  1681. case SystemZ::BI__builtin_s390_vstrch:
  1682. case SystemZ::BI__builtin_s390_vstrcf:
  1683. case SystemZ::BI__builtin_s390_vstrczb:
  1684. case SystemZ::BI__builtin_s390_vstrczh:
  1685. case SystemZ::BI__builtin_s390_vstrczf:
  1686. case SystemZ::BI__builtin_s390_vstrcbs:
  1687. case SystemZ::BI__builtin_s390_vstrchs:
  1688. case SystemZ::BI__builtin_s390_vstrcfs:
  1689. case SystemZ::BI__builtin_s390_vstrczbs:
  1690. case SystemZ::BI__builtin_s390_vstrczhs:
  1691. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  1692. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  1693. case SystemZ::BI__builtin_s390_vfminsb:
  1694. case SystemZ::BI__builtin_s390_vfmaxsb:
  1695. case SystemZ::BI__builtin_s390_vfmindb:
  1696. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  1697. }
  1698. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  1699. }
  1700. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  1701. /// This checks that the target supports __builtin_cpu_supports and
  1702. /// that the string argument is constant and valid.
  1703. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  1704. Expr *Arg = TheCall->getArg(0);
  1705. // Check if the argument is a string literal.
  1706. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  1707. return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  1708. << Arg->getSourceRange();
  1709. // Check the contents of the string.
  1710. StringRef Feature =
  1711. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  1712. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  1713. return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
  1714. << Arg->getSourceRange();
  1715. return false;
  1716. }
  1717. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  1718. /// This checks that the target supports __builtin_cpu_is and
  1719. /// that the string argument is constant and valid.
  1720. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  1721. Expr *Arg = TheCall->getArg(0);
  1722. // Check if the argument is a string literal.
  1723. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  1724. return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  1725. << Arg->getSourceRange();
  1726. // Check the contents of the string.
  1727. StringRef Feature =
  1728. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  1729. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  1730. return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
  1731. << Arg->getSourceRange();
  1732. return false;
  1733. }
  1734. // Check if the rounding mode is legal.
  1735. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  1736. // Indicates if this instruction has rounding control or just SAE.
  1737. bool HasRC = false;
  1738. unsigned ArgNum = 0;
  1739. switch (BuiltinID) {
  1740. default:
  1741. return false;
  1742. case X86::BI__builtin_ia32_vcvttsd2si32:
  1743. case X86::BI__builtin_ia32_vcvttsd2si64:
  1744. case X86::BI__builtin_ia32_vcvttsd2usi32:
  1745. case X86::BI__builtin_ia32_vcvttsd2usi64:
  1746. case X86::BI__builtin_ia32_vcvttss2si32:
  1747. case X86::BI__builtin_ia32_vcvttss2si64:
  1748. case X86::BI__builtin_ia32_vcvttss2usi32:
  1749. case X86::BI__builtin_ia32_vcvttss2usi64:
  1750. ArgNum = 1;
  1751. break;
  1752. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  1753. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  1754. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  1755. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  1756. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  1757. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  1758. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  1759. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  1760. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  1761. case X86::BI__builtin_ia32_exp2pd_mask:
  1762. case X86::BI__builtin_ia32_exp2ps_mask:
  1763. case X86::BI__builtin_ia32_getexppd512_mask:
  1764. case X86::BI__builtin_ia32_getexpps512_mask:
  1765. case X86::BI__builtin_ia32_rcp28pd_mask:
  1766. case X86::BI__builtin_ia32_rcp28ps_mask:
  1767. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  1768. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  1769. case X86::BI__builtin_ia32_vcomisd:
  1770. case X86::BI__builtin_ia32_vcomiss:
  1771. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  1772. ArgNum = 3;
  1773. break;
  1774. case X86::BI__builtin_ia32_cmppd512_mask:
  1775. case X86::BI__builtin_ia32_cmpps512_mask:
  1776. case X86::BI__builtin_ia32_cmpsd_mask:
  1777. case X86::BI__builtin_ia32_cmpss_mask:
  1778. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  1779. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  1780. case X86::BI__builtin_ia32_getexpss128_round_mask:
  1781. case X86::BI__builtin_ia32_maxpd512_mask:
  1782. case X86::BI__builtin_ia32_maxps512_mask:
  1783. case X86::BI__builtin_ia32_maxsd_round_mask:
  1784. case X86::BI__builtin_ia32_maxss_round_mask:
  1785. case X86::BI__builtin_ia32_minpd512_mask:
  1786. case X86::BI__builtin_ia32_minps512_mask:
  1787. case X86::BI__builtin_ia32_minsd_round_mask:
  1788. case X86::BI__builtin_ia32_minss_round_mask:
  1789. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  1790. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  1791. case X86::BI__builtin_ia32_reducepd512_mask:
  1792. case X86::BI__builtin_ia32_reduceps512_mask:
  1793. case X86::BI__builtin_ia32_rndscalepd_mask:
  1794. case X86::BI__builtin_ia32_rndscaleps_mask:
  1795. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  1796. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  1797. ArgNum = 4;
  1798. break;
  1799. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  1800. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  1801. case X86::BI__builtin_ia32_fixupimmps512_mask:
  1802. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  1803. case X86::BI__builtin_ia32_fixupimmsd_mask:
  1804. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  1805. case X86::BI__builtin_ia32_fixupimmss_mask:
  1806. case X86::BI__builtin_ia32_fixupimmss_maskz:
  1807. case X86::BI__builtin_ia32_rangepd512_mask:
  1808. case X86::BI__builtin_ia32_rangeps512_mask:
  1809. case X86::BI__builtin_ia32_rangesd128_round_mask:
  1810. case X86::BI__builtin_ia32_rangess128_round_mask:
  1811. case X86::BI__builtin_ia32_reducesd_mask:
  1812. case X86::BI__builtin_ia32_reducess_mask:
  1813. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  1814. case X86::BI__builtin_ia32_rndscaless_round_mask:
  1815. ArgNum = 5;
  1816. break;
  1817. case X86::BI__builtin_ia32_vcvtsd2si64:
  1818. case X86::BI__builtin_ia32_vcvtsd2si32:
  1819. case X86::BI__builtin_ia32_vcvtsd2usi32:
  1820. case X86::BI__builtin_ia32_vcvtsd2usi64:
  1821. case X86::BI__builtin_ia32_vcvtss2si32:
  1822. case X86::BI__builtin_ia32_vcvtss2si64:
  1823. case X86::BI__builtin_ia32_vcvtss2usi32:
  1824. case X86::BI__builtin_ia32_vcvtss2usi64:
  1825. ArgNum = 1;
  1826. HasRC = true;
  1827. break;
  1828. case X86::BI__builtin_ia32_cvtsi2sd64:
  1829. case X86::BI__builtin_ia32_cvtsi2ss32:
  1830. case X86::BI__builtin_ia32_cvtsi2ss64:
  1831. case X86::BI__builtin_ia32_cvtusi2sd64:
  1832. case X86::BI__builtin_ia32_cvtusi2ss32:
  1833. case X86::BI__builtin_ia32_cvtusi2ss64:
  1834. ArgNum = 2;
  1835. HasRC = true;
  1836. break;
  1837. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  1838. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  1839. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  1840. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  1841. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  1842. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  1843. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  1844. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  1845. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  1846. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  1847. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  1848. case X86::BI__builtin_ia32_sqrtpd512_mask:
  1849. case X86::BI__builtin_ia32_sqrtps512_mask:
  1850. ArgNum = 3;
  1851. HasRC = true;
  1852. break;
  1853. case X86::BI__builtin_ia32_addpd512_mask:
  1854. case X86::BI__builtin_ia32_addps512_mask:
  1855. case X86::BI__builtin_ia32_divpd512_mask:
  1856. case X86::BI__builtin_ia32_divps512_mask:
  1857. case X86::BI__builtin_ia32_mulpd512_mask:
  1858. case X86::BI__builtin_ia32_mulps512_mask:
  1859. case X86::BI__builtin_ia32_subpd512_mask:
  1860. case X86::BI__builtin_ia32_subps512_mask:
  1861. case X86::BI__builtin_ia32_addss_round_mask:
  1862. case X86::BI__builtin_ia32_addsd_round_mask:
  1863. case X86::BI__builtin_ia32_divss_round_mask:
  1864. case X86::BI__builtin_ia32_divsd_round_mask:
  1865. case X86::BI__builtin_ia32_mulss_round_mask:
  1866. case X86::BI__builtin_ia32_mulsd_round_mask:
  1867. case X86::BI__builtin_ia32_subss_round_mask:
  1868. case X86::BI__builtin_ia32_subsd_round_mask:
  1869. case X86::BI__builtin_ia32_scalefpd512_mask:
  1870. case X86::BI__builtin_ia32_scalefps512_mask:
  1871. case X86::BI__builtin_ia32_scalefsd_round_mask:
  1872. case X86::BI__builtin_ia32_scalefss_round_mask:
  1873. case X86::BI__builtin_ia32_getmantpd512_mask:
  1874. case X86::BI__builtin_ia32_getmantps512_mask:
  1875. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  1876. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  1877. case X86::BI__builtin_ia32_sqrtss_round_mask:
  1878. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  1879. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  1880. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  1881. case X86::BI__builtin_ia32_vfmaddps512_mask:
  1882. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  1883. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  1884. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  1885. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  1886. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  1887. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  1888. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  1889. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  1890. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  1891. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  1892. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  1893. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  1894. case X86::BI__builtin_ia32_vfnmaddpd512_mask:
  1895. case X86::BI__builtin_ia32_vfnmaddps512_mask:
  1896. case X86::BI__builtin_ia32_vfnmsubpd512_mask:
  1897. case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
  1898. case X86::BI__builtin_ia32_vfnmsubps512_mask:
  1899. case X86::BI__builtin_ia32_vfnmsubps512_mask3:
  1900. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  1901. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  1902. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  1903. case X86::BI__builtin_ia32_vfmaddss3_mask:
  1904. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  1905. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  1906. ArgNum = 4;
  1907. HasRC = true;
  1908. break;
  1909. case X86::BI__builtin_ia32_getmantsd_round_mask:
  1910. case X86::BI__builtin_ia32_getmantss_round_mask:
  1911. ArgNum = 5;
  1912. HasRC = true;
  1913. break;
  1914. }
  1915. llvm::APSInt Result;
  1916. // We can't check the value of a dependent argument.
  1917. Expr *Arg = TheCall->getArg(ArgNum);
  1918. if (Arg->isTypeDependent() || Arg->isValueDependent())
  1919. return false;
  1920. // Check constant-ness first.
  1921. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  1922. return true;
  1923. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  1924. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  1925. // combined with ROUND_NO_EXC.
  1926. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  1927. Result == 8/*ROUND_NO_EXC*/ ||
  1928. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  1929. return false;
  1930. return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
  1931. << Arg->getSourceRange();
  1932. }
  1933. // Check if the gather/scatter scale is legal.
  1934. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  1935. CallExpr *TheCall) {
  1936. unsigned ArgNum = 0;
  1937. switch (BuiltinID) {
  1938. default:
  1939. return false;
  1940. case X86::BI__builtin_ia32_gatherpfdpd:
  1941. case X86::BI__builtin_ia32_gatherpfdps:
  1942. case X86::BI__builtin_ia32_gatherpfqpd:
  1943. case X86::BI__builtin_ia32_gatherpfqps:
  1944. case X86::BI__builtin_ia32_scatterpfdpd:
  1945. case X86::BI__builtin_ia32_scatterpfdps:
  1946. case X86::BI__builtin_ia32_scatterpfqpd:
  1947. case X86::BI__builtin_ia32_scatterpfqps:
  1948. ArgNum = 3;
  1949. break;
  1950. case X86::BI__builtin_ia32_gatherd_pd:
  1951. case X86::BI__builtin_ia32_gatherd_pd256:
  1952. case X86::BI__builtin_ia32_gatherq_pd:
  1953. case X86::BI__builtin_ia32_gatherq_pd256:
  1954. case X86::BI__builtin_ia32_gatherd_ps:
  1955. case X86::BI__builtin_ia32_gatherd_ps256:
  1956. case X86::BI__builtin_ia32_gatherq_ps:
  1957. case X86::BI__builtin_ia32_gatherq_ps256:
  1958. case X86::BI__builtin_ia32_gatherd_q:
  1959. case X86::BI__builtin_ia32_gatherd_q256:
  1960. case X86::BI__builtin_ia32_gatherq_q:
  1961. case X86::BI__builtin_ia32_gatherq_q256:
  1962. case X86::BI__builtin_ia32_gatherd_d:
  1963. case X86::BI__builtin_ia32_gatherd_d256:
  1964. case X86::BI__builtin_ia32_gatherq_d:
  1965. case X86::BI__builtin_ia32_gatherq_d256:
  1966. case X86::BI__builtin_ia32_gather3div2df:
  1967. case X86::BI__builtin_ia32_gather3div2di:
  1968. case X86::BI__builtin_ia32_gather3div4df:
  1969. case X86::BI__builtin_ia32_gather3div4di:
  1970. case X86::BI__builtin_ia32_gather3div4sf:
  1971. case X86::BI__builtin_ia32_gather3div4si:
  1972. case X86::BI__builtin_ia32_gather3div8sf:
  1973. case X86::BI__builtin_ia32_gather3div8si:
  1974. case X86::BI__builtin_ia32_gather3siv2df:
  1975. case X86::BI__builtin_ia32_gather3siv2di:
  1976. case X86::BI__builtin_ia32_gather3siv4df:
  1977. case X86::BI__builtin_ia32_gather3siv4di:
  1978. case X86::BI__builtin_ia32_gather3siv4sf:
  1979. case X86::BI__builtin_ia32_gather3siv4si:
  1980. case X86::BI__builtin_ia32_gather3siv8sf:
  1981. case X86::BI__builtin_ia32_gather3siv8si:
  1982. case X86::BI__builtin_ia32_gathersiv8df:
  1983. case X86::BI__builtin_ia32_gathersiv16sf:
  1984. case X86::BI__builtin_ia32_gatherdiv8df:
  1985. case X86::BI__builtin_ia32_gatherdiv16sf:
  1986. case X86::BI__builtin_ia32_gathersiv8di:
  1987. case X86::BI__builtin_ia32_gathersiv16si:
  1988. case X86::BI__builtin_ia32_gatherdiv8di:
  1989. case X86::BI__builtin_ia32_gatherdiv16si:
  1990. case X86::BI__builtin_ia32_scatterdiv2df:
  1991. case X86::BI__builtin_ia32_scatterdiv2di:
  1992. case X86::BI__builtin_ia32_scatterdiv4df:
  1993. case X86::BI__builtin_ia32_scatterdiv4di:
  1994. case X86::BI__builtin_ia32_scatterdiv4sf:
  1995. case X86::BI__builtin_ia32_scatterdiv4si:
  1996. case X86::BI__builtin_ia32_scatterdiv8sf:
  1997. case X86::BI__builtin_ia32_scatterdiv8si:
  1998. case X86::BI__builtin_ia32_scattersiv2df:
  1999. case X86::BI__builtin_ia32_scattersiv2di:
  2000. case X86::BI__builtin_ia32_scattersiv4df:
  2001. case X86::BI__builtin_ia32_scattersiv4di:
  2002. case X86::BI__builtin_ia32_scattersiv4sf:
  2003. case X86::BI__builtin_ia32_scattersiv4si:
  2004. case X86::BI__builtin_ia32_scattersiv8sf:
  2005. case X86::BI__builtin_ia32_scattersiv8si:
  2006. case X86::BI__builtin_ia32_scattersiv8df:
  2007. case X86::BI__builtin_ia32_scattersiv16sf:
  2008. case X86::BI__builtin_ia32_scatterdiv8df:
  2009. case X86::BI__builtin_ia32_scatterdiv16sf:
  2010. case X86::BI__builtin_ia32_scattersiv8di:
  2011. case X86::BI__builtin_ia32_scattersiv16si:
  2012. case X86::BI__builtin_ia32_scatterdiv8di:
  2013. case X86::BI__builtin_ia32_scatterdiv16si:
  2014. ArgNum = 4;
  2015. break;
  2016. }
  2017. llvm::APSInt Result;
  2018. // We can't check the value of a dependent argument.
  2019. Expr *Arg = TheCall->getArg(ArgNum);
  2020. if (Arg->isTypeDependent() || Arg->isValueDependent())
  2021. return false;
  2022. // Check constant-ness first.
  2023. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  2024. return true;
  2025. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  2026. return false;
  2027. return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
  2028. << Arg->getSourceRange();
  2029. }
  2030. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2031. if (BuiltinID == X86::BI__builtin_cpu_supports)
  2032. return SemaBuiltinCpuSupports(*this, TheCall);
  2033. if (BuiltinID == X86::BI__builtin_cpu_is)
  2034. return SemaBuiltinCpuIs(*this, TheCall);
  2035. // If the intrinsic has rounding or SAE make sure its valid.
  2036. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  2037. return true;
  2038. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  2039. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  2040. return true;
  2041. // For intrinsics which take an immediate value as part of the instruction,
  2042. // range check them here.
  2043. int i = 0, l = 0, u = 0;
  2044. switch (BuiltinID) {
  2045. default:
  2046. return false;
  2047. case X86::BI_mm_prefetch:
  2048. i = 1; l = 0; u = 3;
  2049. break;
  2050. case X86::BI__builtin_ia32_sha1rnds4:
  2051. case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
  2052. case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
  2053. case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
  2054. case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
  2055. i = 2; l = 0; u = 3;
  2056. break;
  2057. case X86::BI__builtin_ia32_vpermil2pd:
  2058. case X86::BI__builtin_ia32_vpermil2pd256:
  2059. case X86::BI__builtin_ia32_vpermil2ps:
  2060. case X86::BI__builtin_ia32_vpermil2ps256:
  2061. i = 3; l = 0; u = 3;
  2062. break;
  2063. case X86::BI__builtin_ia32_cmpb128_mask:
  2064. case X86::BI__builtin_ia32_cmpw128_mask:
  2065. case X86::BI__builtin_ia32_cmpd128_mask:
  2066. case X86::BI__builtin_ia32_cmpq128_mask:
  2067. case X86::BI__builtin_ia32_cmpb256_mask:
  2068. case X86::BI__builtin_ia32_cmpw256_mask:
  2069. case X86::BI__builtin_ia32_cmpd256_mask:
  2070. case X86::BI__builtin_ia32_cmpq256_mask:
  2071. case X86::BI__builtin_ia32_cmpb512_mask:
  2072. case X86::BI__builtin_ia32_cmpw512_mask:
  2073. case X86::BI__builtin_ia32_cmpd512_mask:
  2074. case X86::BI__builtin_ia32_cmpq512_mask:
  2075. case X86::BI__builtin_ia32_ucmpb128_mask:
  2076. case X86::BI__builtin_ia32_ucmpw128_mask:
  2077. case X86::BI__builtin_ia32_ucmpd128_mask:
  2078. case X86::BI__builtin_ia32_ucmpq128_mask:
  2079. case X86::BI__builtin_ia32_ucmpb256_mask:
  2080. case X86::BI__builtin_ia32_ucmpw256_mask:
  2081. case X86::BI__builtin_ia32_ucmpd256_mask:
  2082. case X86::BI__builtin_ia32_ucmpq256_mask:
  2083. case X86::BI__builtin_ia32_ucmpb512_mask:
  2084. case X86::BI__builtin_ia32_ucmpw512_mask:
  2085. case X86::BI__builtin_ia32_ucmpd512_mask:
  2086. case X86::BI__builtin_ia32_ucmpq512_mask:
  2087. case X86::BI__builtin_ia32_vpcomub:
  2088. case X86::BI__builtin_ia32_vpcomuw:
  2089. case X86::BI__builtin_ia32_vpcomud:
  2090. case X86::BI__builtin_ia32_vpcomuq:
  2091. case X86::BI__builtin_ia32_vpcomb:
  2092. case X86::BI__builtin_ia32_vpcomw:
  2093. case X86::BI__builtin_ia32_vpcomd:
  2094. case X86::BI__builtin_ia32_vpcomq:
  2095. i = 2; l = 0; u = 7;
  2096. break;
  2097. case X86::BI__builtin_ia32_roundps:
  2098. case X86::BI__builtin_ia32_roundpd:
  2099. case X86::BI__builtin_ia32_roundps256:
  2100. case X86::BI__builtin_ia32_roundpd256:
  2101. i = 1; l = 0; u = 15;
  2102. break;
  2103. case X86::BI__builtin_ia32_roundss:
  2104. case X86::BI__builtin_ia32_roundsd:
  2105. case X86::BI__builtin_ia32_rangepd128_mask:
  2106. case X86::BI__builtin_ia32_rangepd256_mask:
  2107. case X86::BI__builtin_ia32_rangepd512_mask:
  2108. case X86::BI__builtin_ia32_rangeps128_mask:
  2109. case X86::BI__builtin_ia32_rangeps256_mask:
  2110. case X86::BI__builtin_ia32_rangeps512_mask:
  2111. case X86::BI__builtin_ia32_getmantsd_round_mask:
  2112. case X86::BI__builtin_ia32_getmantss_round_mask:
  2113. i = 2; l = 0; u = 15;
  2114. break;
  2115. case X86::BI__builtin_ia32_cmpps:
  2116. case X86::BI__builtin_ia32_cmpss:
  2117. case X86::BI__builtin_ia32_cmppd:
  2118. case X86::BI__builtin_ia32_cmpsd:
  2119. case X86::BI__builtin_ia32_cmpps256:
  2120. case X86::BI__builtin_ia32_cmppd256:
  2121. case X86::BI__builtin_ia32_cmpps128_mask:
  2122. case X86::BI__builtin_ia32_cmppd128_mask:
  2123. case X86::BI__builtin_ia32_cmpps256_mask:
  2124. case X86::BI__builtin_ia32_cmppd256_mask:
  2125. case X86::BI__builtin_ia32_cmpps512_mask:
  2126. case X86::BI__builtin_ia32_cmppd512_mask:
  2127. case X86::BI__builtin_ia32_cmpsd_mask:
  2128. case X86::BI__builtin_ia32_cmpss_mask:
  2129. i = 2; l = 0; u = 31;
  2130. break;
  2131. case X86::BI__builtin_ia32_xabort:
  2132. i = 0; l = -128; u = 255;
  2133. break;
  2134. case X86::BI__builtin_ia32_pshufw:
  2135. case X86::BI__builtin_ia32_aeskeygenassist128:
  2136. i = 1; l = -128; u = 255;
  2137. break;
  2138. case X86::BI__builtin_ia32_vcvtps2ph:
  2139. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  2140. case X86::BI__builtin_ia32_vcvtps2ph256:
  2141. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  2142. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  2143. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  2144. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  2145. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  2146. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  2147. case X86::BI__builtin_ia32_rndscaleps_mask:
  2148. case X86::BI__builtin_ia32_rndscalepd_mask:
  2149. case X86::BI__builtin_ia32_reducepd128_mask:
  2150. case X86::BI__builtin_ia32_reducepd256_mask:
  2151. case X86::BI__builtin_ia32_reducepd512_mask:
  2152. case X86::BI__builtin_ia32_reduceps128_mask:
  2153. case X86::BI__builtin_ia32_reduceps256_mask:
  2154. case X86::BI__builtin_ia32_reduceps512_mask:
  2155. case X86::BI__builtin_ia32_prold512_mask:
  2156. case X86::BI__builtin_ia32_prolq512_mask:
  2157. case X86::BI__builtin_ia32_prold128_mask:
  2158. case X86::BI__builtin_ia32_prold256_mask:
  2159. case X86::BI__builtin_ia32_prolq128_mask:
  2160. case X86::BI__builtin_ia32_prolq256_mask:
  2161. case X86::BI__builtin_ia32_prord128_mask:
  2162. case X86::BI__builtin_ia32_prord256_mask:
  2163. case X86::BI__builtin_ia32_prorq128_mask:
  2164. case X86::BI__builtin_ia32_prorq256_mask:
  2165. case X86::BI__builtin_ia32_fpclasspd128_mask:
  2166. case X86::BI__builtin_ia32_fpclasspd256_mask:
  2167. case X86::BI__builtin_ia32_fpclassps128_mask:
  2168. case X86::BI__builtin_ia32_fpclassps256_mask:
  2169. case X86::BI__builtin_ia32_fpclassps512_mask:
  2170. case X86::BI__builtin_ia32_fpclasspd512_mask:
  2171. case X86::BI__builtin_ia32_fpclasssd_mask:
  2172. case X86::BI__builtin_ia32_fpclassss_mask:
  2173. i = 1; l = 0; u = 255;
  2174. break;
  2175. case X86::BI__builtin_ia32_palignr:
  2176. case X86::BI__builtin_ia32_insertps128:
  2177. case X86::BI__builtin_ia32_dpps:
  2178. case X86::BI__builtin_ia32_dppd:
  2179. case X86::BI__builtin_ia32_dpps256:
  2180. case X86::BI__builtin_ia32_mpsadbw128:
  2181. case X86::BI__builtin_ia32_mpsadbw256:
  2182. case X86::BI__builtin_ia32_pcmpistrm128:
  2183. case X86::BI__builtin_ia32_pcmpistri128:
  2184. case X86::BI__builtin_ia32_pcmpistria128:
  2185. case X86::BI__builtin_ia32_pcmpistric128:
  2186. case X86::BI__builtin_ia32_pcmpistrio128:
  2187. case X86::BI__builtin_ia32_pcmpistris128:
  2188. case X86::BI__builtin_ia32_pcmpistriz128:
  2189. case X86::BI__builtin_ia32_pclmulqdq128:
  2190. case X86::BI__builtin_ia32_vperm2f128_pd256:
  2191. case X86::BI__builtin_ia32_vperm2f128_ps256:
  2192. case X86::BI__builtin_ia32_vperm2f128_si256:
  2193. case X86::BI__builtin_ia32_permti256:
  2194. i = 2; l = -128; u = 255;
  2195. break;
  2196. case X86::BI__builtin_ia32_palignr128:
  2197. case X86::BI__builtin_ia32_palignr256:
  2198. case X86::BI__builtin_ia32_palignr512_mask:
  2199. case X86::BI__builtin_ia32_vcomisd:
  2200. case X86::BI__builtin_ia32_vcomiss:
  2201. case X86::BI__builtin_ia32_shuf_f32x4_mask:
  2202. case X86::BI__builtin_ia32_shuf_f64x2_mask:
  2203. case X86::BI__builtin_ia32_shuf_i32x4_mask:
  2204. case X86::BI__builtin_ia32_shuf_i64x2_mask:
  2205. case X86::BI__builtin_ia32_dbpsadbw128_mask:
  2206. case X86::BI__builtin_ia32_dbpsadbw256_mask:
  2207. case X86::BI__builtin_ia32_dbpsadbw512_mask:
  2208. i = 2; l = 0; u = 255;
  2209. break;
  2210. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  2211. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  2212. case X86::BI__builtin_ia32_fixupimmps512_mask:
  2213. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  2214. case X86::BI__builtin_ia32_fixupimmsd_mask:
  2215. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  2216. case X86::BI__builtin_ia32_fixupimmss_mask:
  2217. case X86::BI__builtin_ia32_fixupimmss_maskz:
  2218. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  2219. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  2220. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  2221. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  2222. case X86::BI__builtin_ia32_fixupimmps128_mask:
  2223. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  2224. case X86::BI__builtin_ia32_fixupimmps256_mask:
  2225. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  2226. case X86::BI__builtin_ia32_pternlogd512_mask:
  2227. case X86::BI__builtin_ia32_pternlogd512_maskz:
  2228. case X86::BI__builtin_ia32_pternlogq512_mask:
  2229. case X86::BI__builtin_ia32_pternlogq512_maskz:
  2230. case X86::BI__builtin_ia32_pternlogd128_mask:
  2231. case X86::BI__builtin_ia32_pternlogd128_maskz:
  2232. case X86::BI__builtin_ia32_pternlogd256_mask:
  2233. case X86::BI__builtin_ia32_pternlogd256_maskz:
  2234. case X86::BI__builtin_ia32_pternlogq128_mask:
  2235. case X86::BI__builtin_ia32_pternlogq128_maskz:
  2236. case X86::BI__builtin_ia32_pternlogq256_mask:
  2237. case X86::BI__builtin_ia32_pternlogq256_maskz:
  2238. i = 3; l = 0; u = 255;
  2239. break;
  2240. case X86::BI__builtin_ia32_gatherpfdpd:
  2241. case X86::BI__builtin_ia32_gatherpfdps:
  2242. case X86::BI__builtin_ia32_gatherpfqpd:
  2243. case X86::BI__builtin_ia32_gatherpfqps:
  2244. case X86::BI__builtin_ia32_scatterpfdpd:
  2245. case X86::BI__builtin_ia32_scatterpfdps:
  2246. case X86::BI__builtin_ia32_scatterpfqpd:
  2247. case X86::BI__builtin_ia32_scatterpfqps:
  2248. i = 4; l = 2; u = 3;
  2249. break;
  2250. case X86::BI__builtin_ia32_pcmpestrm128:
  2251. case X86::BI__builtin_ia32_pcmpestri128:
  2252. case X86::BI__builtin_ia32_pcmpestria128:
  2253. case X86::BI__builtin_ia32_pcmpestric128:
  2254. case X86::BI__builtin_ia32_pcmpestrio128:
  2255. case X86::BI__builtin_ia32_pcmpestris128:
  2256. case X86::BI__builtin_ia32_pcmpestriz128:
  2257. i = 4; l = -128; u = 255;
  2258. break;
  2259. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  2260. case X86::BI__builtin_ia32_rndscaless_round_mask:
  2261. i = 4; l = 0; u = 255;
  2262. break;
  2263. }
  2264. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2265. }
  2266. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  2267. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  2268. /// Returns true when the format fits the function and the FormatStringInfo has
  2269. /// been populated.
  2270. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  2271. FormatStringInfo *FSI) {
  2272. FSI->HasVAListArg = Format->getFirstArg() == 0;
  2273. FSI->FormatIdx = Format->getFormatIdx() - 1;
  2274. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  2275. // The way the format attribute works in GCC, the implicit this argument
  2276. // of member functions is counted. However, it doesn't appear in our own
  2277. // lists, so decrement format_idx in that case.
  2278. if (IsCXXMember) {
  2279. if(FSI->FormatIdx == 0)
  2280. return false;
  2281. --FSI->FormatIdx;
  2282. if (FSI->FirstDataArg != 0)
  2283. --FSI->FirstDataArg;
  2284. }
  2285. return true;
  2286. }
  2287. /// Checks if a the given expression evaluates to null.
  2288. ///
  2289. /// \brief Returns true if the value evaluates to null.
  2290. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  2291. // If the expression has non-null type, it doesn't evaluate to null.
  2292. if (auto nullability
  2293. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  2294. if (*nullability == NullabilityKind::NonNull)
  2295. return false;
  2296. }
  2297. // As a special case, transparent unions initialized with zero are
  2298. // considered null for the purposes of the nonnull attribute.
  2299. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  2300. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  2301. if (const CompoundLiteralExpr *CLE =
  2302. dyn_cast<CompoundLiteralExpr>(Expr))
  2303. if (const InitListExpr *ILE =
  2304. dyn_cast<InitListExpr>(CLE->getInitializer()))
  2305. Expr = ILE->getInit(0);
  2306. }
  2307. bool Result;
  2308. return (!Expr->isValueDependent() &&
  2309. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  2310. !Result);
  2311. }
  2312. static void CheckNonNullArgument(Sema &S,
  2313. const Expr *ArgExpr,
  2314. SourceLocation CallSiteLoc) {
  2315. if (CheckNonNullExpr(S, ArgExpr))
  2316. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  2317. S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
  2318. }
  2319. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  2320. FormatStringInfo FSI;
  2321. if ((GetFormatStringType(Format) == FST_NSString) &&
  2322. getFormatStringInfo(Format, false, &FSI)) {
  2323. Idx = FSI.FormatIdx;
  2324. return true;
  2325. }
  2326. return false;
  2327. }
  2328. /// \brief Diagnose use of %s directive in an NSString which is being passed
  2329. /// as formatting string to formatting method.
  2330. static void
  2331. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  2332. const NamedDecl *FDecl,
  2333. Expr **Args,
  2334. unsigned NumArgs) {
  2335. unsigned Idx = 0;
  2336. bool Format = false;
  2337. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  2338. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  2339. Idx = 2;
  2340. Format = true;
  2341. }
  2342. else
  2343. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  2344. if (S.GetFormatNSStringIdx(I, Idx)) {
  2345. Format = true;
  2346. break;
  2347. }
  2348. }
  2349. if (!Format || NumArgs <= Idx)
  2350. return;
  2351. const Expr *FormatExpr = Args[Idx];
  2352. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  2353. FormatExpr = CSCE->getSubExpr();
  2354. const StringLiteral *FormatString;
  2355. if (const ObjCStringLiteral *OSL =
  2356. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  2357. FormatString = OSL->getString();
  2358. else
  2359. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  2360. if (!FormatString)
  2361. return;
  2362. if (S.FormatStringHasSArg(FormatString)) {
  2363. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  2364. << "%s" << 1 << 1;
  2365. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  2366. << FDecl->getDeclName();
  2367. }
  2368. }
  2369. /// Determine whether the given type has a non-null nullability annotation.
  2370. static bool isNonNullType(ASTContext &ctx, QualType type) {
  2371. if (auto nullability = type->getNullability(ctx))
  2372. return *nullability == NullabilityKind::NonNull;
  2373. return false;
  2374. }
  2375. static void CheckNonNullArguments(Sema &S,
  2376. const NamedDecl *FDecl,
  2377. const FunctionProtoType *Proto,
  2378. ArrayRef<const Expr *> Args,
  2379. SourceLocation CallSiteLoc) {
  2380. assert((FDecl || Proto) && "Need a function declaration or prototype");
  2381. // Check the attributes attached to the method/function itself.
  2382. llvm::SmallBitVector NonNullArgs;
  2383. if (FDecl) {
  2384. // Handle the nonnull attribute on the function/method declaration itself.
  2385. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  2386. if (!NonNull->args_size()) {
  2387. // Easy case: all pointer arguments are nonnull.
  2388. for (const auto *Arg : Args)
  2389. if (S.isValidPointerAttrType(Arg->getType()))
  2390. CheckNonNullArgument(S, Arg, CallSiteLoc);
  2391. return;
  2392. }
  2393. for (unsigned Val : NonNull->args()) {
  2394. if (Val >= Args.size())
  2395. continue;
  2396. if (NonNullArgs.empty())
  2397. NonNullArgs.resize(Args.size());
  2398. NonNullArgs.set(Val);
  2399. }
  2400. }
  2401. }
  2402. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  2403. // Handle the nonnull attribute on the parameters of the
  2404. // function/method.
  2405. ArrayRef<ParmVarDecl*> parms;
  2406. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  2407. parms = FD->parameters();
  2408. else
  2409. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  2410. unsigned ParamIndex = 0;
  2411. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  2412. I != E; ++I, ++ParamIndex) {
  2413. const ParmVarDecl *PVD = *I;
  2414. if (PVD->hasAttr<NonNullAttr>() ||
  2415. isNonNullType(S.Context, PVD->getType())) {
  2416. if (NonNullArgs.empty())
  2417. NonNullArgs.resize(Args.size());
  2418. NonNullArgs.set(ParamIndex);
  2419. }
  2420. }
  2421. } else {
  2422. // If we have a non-function, non-method declaration but no
  2423. // function prototype, try to dig out the function prototype.
  2424. if (!Proto) {
  2425. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  2426. QualType type = VD->getType().getNonReferenceType();
  2427. if (auto pointerType = type->getAs<PointerType>())
  2428. type = pointerType->getPointeeType();
  2429. else if (auto blockType = type->getAs<BlockPointerType>())
  2430. type = blockType->getPointeeType();
  2431. // FIXME: data member pointers?
  2432. // Dig out the function prototype, if there is one.
  2433. Proto = type->getAs<FunctionProtoType>();
  2434. }
  2435. }
  2436. // Fill in non-null argument information from the nullability
  2437. // information on the parameter types (if we have them).
  2438. if (Proto) {
  2439. unsigned Index = 0;
  2440. for (auto paramType : Proto->getParamTypes()) {
  2441. if (isNonNullType(S.Context, paramType)) {
  2442. if (NonNullArgs.empty())
  2443. NonNullArgs.resize(Args.size());
  2444. NonNullArgs.set(Index);
  2445. }
  2446. ++Index;
  2447. }
  2448. }
  2449. }
  2450. // Check for non-null arguments.
  2451. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  2452. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  2453. if (NonNullArgs[ArgIndex])
  2454. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  2455. }
  2456. }
  2457. /// Handles the checks for format strings, non-POD arguments to vararg
  2458. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  2459. /// attributes.
  2460. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  2461. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  2462. bool IsMemberFunction, SourceLocation Loc,
  2463. SourceRange Range, VariadicCallType CallType) {
  2464. // FIXME: We should check as much as we can in the template definition.
  2465. if (CurContext->isDependentContext())
  2466. return;
  2467. // Printf and scanf checking.
  2468. llvm::SmallBitVector CheckedVarArgs;
  2469. if (FDecl) {
  2470. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  2471. // Only create vector if there are format attributes.
  2472. CheckedVarArgs.resize(Args.size());
  2473. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  2474. CheckedVarArgs);
  2475. }
  2476. }
  2477. // Refuse POD arguments that weren't caught by the format string
  2478. // checks above.
  2479. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  2480. if (CallType != VariadicDoesNotApply &&
  2481. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  2482. unsigned NumParams = Proto ? Proto->getNumParams()
  2483. : FDecl && isa<FunctionDecl>(FDecl)
  2484. ? cast<FunctionDecl>(FDecl)->getNumParams()
  2485. : FDecl && isa<ObjCMethodDecl>(FDecl)
  2486. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  2487. : 0;
  2488. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  2489. // Args[ArgIdx] can be null in malformed code.
  2490. if (const Expr *Arg = Args[ArgIdx]) {
  2491. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  2492. checkVariadicArgument(Arg, CallType);
  2493. }
  2494. }
  2495. }
  2496. if (FDecl || Proto) {
  2497. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  2498. // Type safety checking.
  2499. if (FDecl) {
  2500. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  2501. CheckArgumentWithTypeTag(I, Args.data());
  2502. }
  2503. }
  2504. if (FD)
  2505. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  2506. }
  2507. /// CheckConstructorCall - Check a constructor call for correctness and safety
  2508. /// properties not enforced by the C type system.
  2509. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  2510. ArrayRef<const Expr *> Args,
  2511. const FunctionProtoType *Proto,
  2512. SourceLocation Loc) {
  2513. VariadicCallType CallType =
  2514. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  2515. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  2516. Loc, SourceRange(), CallType);
  2517. }
  2518. /// CheckFunctionCall - Check a direct function call for various correctness
  2519. /// and safety properties not strictly enforced by the C type system.
  2520. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  2521. const FunctionProtoType *Proto) {
  2522. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  2523. isa<CXXMethodDecl>(FDecl);
  2524. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  2525. IsMemberOperatorCall;
  2526. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  2527. TheCall->getCallee());
  2528. Expr** Args = TheCall->getArgs();
  2529. unsigned NumArgs = TheCall->getNumArgs();
  2530. Expr *ImplicitThis = nullptr;
  2531. if (IsMemberOperatorCall) {
  2532. // If this is a call to a member operator, hide the first argument
  2533. // from checkCall.
  2534. // FIXME: Our choice of AST representation here is less than ideal.
  2535. ImplicitThis = Args[0];
  2536. ++Args;
  2537. --NumArgs;
  2538. } else if (IsMemberFunction)
  2539. ImplicitThis =
  2540. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  2541. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  2542. IsMemberFunction, TheCall->getRParenLoc(),
  2543. TheCall->getCallee()->getSourceRange(), CallType);
  2544. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  2545. // None of the checks below are needed for functions that don't have
  2546. // simple names (e.g., C++ conversion functions).
  2547. if (!FnInfo)
  2548. return false;
  2549. CheckAbsoluteValueFunction(TheCall, FDecl);
  2550. CheckMaxUnsignedZero(TheCall, FDecl);
  2551. if (getLangOpts().ObjC1)
  2552. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  2553. unsigned CMId = FDecl->getMemoryFunctionKind();
  2554. if (CMId == 0)
  2555. return false;
  2556. // Handle memory setting and copying functions.
  2557. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  2558. CheckStrlcpycatArguments(TheCall, FnInfo);
  2559. else if (CMId == Builtin::BIstrncat)
  2560. CheckStrncatArguments(TheCall, FnInfo);
  2561. else
  2562. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  2563. return false;
  2564. }
  2565. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  2566. ArrayRef<const Expr *> Args) {
  2567. VariadicCallType CallType =
  2568. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  2569. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  2570. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  2571. CallType);
  2572. return false;
  2573. }
  2574. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  2575. const FunctionProtoType *Proto) {
  2576. QualType Ty;
  2577. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  2578. Ty = V->getType().getNonReferenceType();
  2579. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  2580. Ty = F->getType().getNonReferenceType();
  2581. else
  2582. return false;
  2583. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  2584. !Ty->isFunctionProtoType())
  2585. return false;
  2586. VariadicCallType CallType;
  2587. if (!Proto || !Proto->isVariadic()) {
  2588. CallType = VariadicDoesNotApply;
  2589. } else if (Ty->isBlockPointerType()) {
  2590. CallType = VariadicBlock;
  2591. } else { // Ty->isFunctionPointerType()
  2592. CallType = VariadicFunction;
  2593. }
  2594. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  2595. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  2596. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  2597. TheCall->getCallee()->getSourceRange(), CallType);
  2598. return false;
  2599. }
  2600. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  2601. /// such as function pointers returned from functions.
  2602. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  2603. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  2604. TheCall->getCallee());
  2605. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  2606. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  2607. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  2608. TheCall->getCallee()->getSourceRange(), CallType);
  2609. return false;
  2610. }
  2611. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  2612. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  2613. return false;
  2614. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  2615. switch (Op) {
  2616. case AtomicExpr::AO__c11_atomic_init:
  2617. case AtomicExpr::AO__opencl_atomic_init:
  2618. llvm_unreachable("There is no ordering argument for an init");
  2619. case AtomicExpr::AO__c11_atomic_load:
  2620. case AtomicExpr::AO__opencl_atomic_load:
  2621. case AtomicExpr::AO__atomic_load_n:
  2622. case AtomicExpr::AO__atomic_load:
  2623. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  2624. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  2625. case AtomicExpr::AO__c11_atomic_store:
  2626. case AtomicExpr::AO__opencl_atomic_store:
  2627. case AtomicExpr::AO__atomic_store:
  2628. case AtomicExpr::AO__atomic_store_n:
  2629. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  2630. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  2631. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  2632. default:
  2633. return true;
  2634. }
  2635. }
  2636. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  2637. AtomicExpr::AtomicOp Op) {
  2638. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  2639. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  2640. // All the non-OpenCL operations take one of the following forms.
  2641. // The OpenCL operations take the __c11 forms with one extra argument for
  2642. // synchronization scope.
  2643. enum {
  2644. // C __c11_atomic_init(A *, C)
  2645. Init,
  2646. // C __c11_atomic_load(A *, int)
  2647. Load,
  2648. // void __atomic_load(A *, CP, int)
  2649. LoadCopy,
  2650. // void __atomic_store(A *, CP, int)
  2651. Copy,
  2652. // C __c11_atomic_add(A *, M, int)
  2653. Arithmetic,
  2654. // C __atomic_exchange_n(A *, CP, int)
  2655. Xchg,
  2656. // void __atomic_exchange(A *, C *, CP, int)
  2657. GNUXchg,
  2658. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  2659. C11CmpXchg,
  2660. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  2661. GNUCmpXchg
  2662. } Form = Init;
  2663. const unsigned NumForm = GNUCmpXchg + 1;
  2664. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  2665. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  2666. // where:
  2667. // C is an appropriate type,
  2668. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  2669. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  2670. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  2671. // the int parameters are for orderings.
  2672. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  2673. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  2674. "need to update code for modified forms");
  2675. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  2676. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  2677. AtomicExpr::AO__atomic_load,
  2678. "need to update code for modified C11 atomics");
  2679. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  2680. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  2681. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  2682. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  2683. IsOpenCL;
  2684. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  2685. Op == AtomicExpr::AO__atomic_store_n ||
  2686. Op == AtomicExpr::AO__atomic_exchange_n ||
  2687. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  2688. bool IsAddSub = false;
  2689. switch (Op) {
  2690. case AtomicExpr::AO__c11_atomic_init:
  2691. case AtomicExpr::AO__opencl_atomic_init:
  2692. Form = Init;
  2693. break;
  2694. case AtomicExpr::AO__c11_atomic_load:
  2695. case AtomicExpr::AO__opencl_atomic_load:
  2696. case AtomicExpr::AO__atomic_load_n:
  2697. Form = Load;
  2698. break;
  2699. case AtomicExpr::AO__atomic_load:
  2700. Form = LoadCopy;
  2701. break;
  2702. case AtomicExpr::AO__c11_atomic_store:
  2703. case AtomicExpr::AO__opencl_atomic_store:
  2704. case AtomicExpr::AO__atomic_store:
  2705. case AtomicExpr::AO__atomic_store_n:
  2706. Form = Copy;
  2707. break;
  2708. case AtomicExpr::AO__c11_atomic_fetch_add:
  2709. case AtomicExpr::AO__c11_atomic_fetch_sub:
  2710. case AtomicExpr::AO__opencl_atomic_fetch_add:
  2711. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  2712. case AtomicExpr::AO__opencl_atomic_fetch_min:
  2713. case AtomicExpr::AO__opencl_atomic_fetch_max:
  2714. case AtomicExpr::AO__atomic_fetch_add:
  2715. case AtomicExpr::AO__atomic_fetch_sub:
  2716. case AtomicExpr::AO__atomic_add_fetch:
  2717. case AtomicExpr::AO__atomic_sub_fetch:
  2718. IsAddSub = true;
  2719. // Fall through.
  2720. case AtomicExpr::AO__c11_atomic_fetch_and:
  2721. case AtomicExpr::AO__c11_atomic_fetch_or:
  2722. case AtomicExpr::AO__c11_atomic_fetch_xor:
  2723. case AtomicExpr::AO__opencl_atomic_fetch_and:
  2724. case AtomicExpr::AO__opencl_atomic_fetch_or:
  2725. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  2726. case AtomicExpr::AO__atomic_fetch_and:
  2727. case AtomicExpr::AO__atomic_fetch_or:
  2728. case AtomicExpr::AO__atomic_fetch_xor:
  2729. case AtomicExpr::AO__atomic_fetch_nand:
  2730. case AtomicExpr::AO__atomic_and_fetch:
  2731. case AtomicExpr::AO__atomic_or_fetch:
  2732. case AtomicExpr::AO__atomic_xor_fetch:
  2733. case AtomicExpr::AO__atomic_nand_fetch:
  2734. Form = Arithmetic;
  2735. break;
  2736. case AtomicExpr::AO__c11_atomic_exchange:
  2737. case AtomicExpr::AO__opencl_atomic_exchange:
  2738. case AtomicExpr::AO__atomic_exchange_n:
  2739. Form = Xchg;
  2740. break;
  2741. case AtomicExpr::AO__atomic_exchange:
  2742. Form = GNUXchg;
  2743. break;
  2744. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  2745. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  2746. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  2747. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  2748. Form = C11CmpXchg;
  2749. break;
  2750. case AtomicExpr::AO__atomic_compare_exchange:
  2751. case AtomicExpr::AO__atomic_compare_exchange_n:
  2752. Form = GNUCmpXchg;
  2753. break;
  2754. }
  2755. unsigned AdjustedNumArgs = NumArgs[Form];
  2756. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  2757. ++AdjustedNumArgs;
  2758. // Check we have the right number of arguments.
  2759. if (TheCall->getNumArgs() < AdjustedNumArgs) {
  2760. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  2761. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  2762. << TheCall->getCallee()->getSourceRange();
  2763. return ExprError();
  2764. } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
  2765. Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
  2766. diag::err_typecheck_call_too_many_args)
  2767. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  2768. << TheCall->getCallee()->getSourceRange();
  2769. return ExprError();
  2770. }
  2771. // Inspect the first argument of the atomic operation.
  2772. Expr *Ptr = TheCall->getArg(0);
  2773. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  2774. if (ConvertedPtr.isInvalid())
  2775. return ExprError();
  2776. Ptr = ConvertedPtr.get();
  2777. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  2778. if (!pointerType) {
  2779. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  2780. << Ptr->getType() << Ptr->getSourceRange();
  2781. return ExprError();
  2782. }
  2783. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  2784. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  2785. QualType ValType = AtomTy; // 'C'
  2786. if (IsC11) {
  2787. if (!AtomTy->isAtomicType()) {
  2788. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  2789. << Ptr->getType() << Ptr->getSourceRange();
  2790. return ExprError();
  2791. }
  2792. if (AtomTy.isConstQualified() ||
  2793. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  2794. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
  2795. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  2796. << Ptr->getSourceRange();
  2797. return ExprError();
  2798. }
  2799. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  2800. } else if (Form != Load && Form != LoadCopy) {
  2801. if (ValType.isConstQualified()) {
  2802. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
  2803. << Ptr->getType() << Ptr->getSourceRange();
  2804. return ExprError();
  2805. }
  2806. }
  2807. // For an arithmetic operation, the implied arithmetic must be well-formed.
  2808. if (Form == Arithmetic) {
  2809. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  2810. if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
  2811. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  2812. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  2813. return ExprError();
  2814. }
  2815. if (!IsAddSub && !ValType->isIntegerType()) {
  2816. Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
  2817. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  2818. return ExprError();
  2819. }
  2820. if (IsC11 && ValType->isPointerType() &&
  2821. RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
  2822. diag::err_incomplete_type)) {
  2823. return ExprError();
  2824. }
  2825. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  2826. // For __atomic_*_n operations, the value type must be a scalar integral or
  2827. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  2828. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  2829. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  2830. return ExprError();
  2831. }
  2832. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  2833. !AtomTy->isScalarType()) {
  2834. // For GNU atomics, require a trivially-copyable type. This is not part of
  2835. // the GNU atomics specification, but we enforce it for sanity.
  2836. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
  2837. << Ptr->getType() << Ptr->getSourceRange();
  2838. return ExprError();
  2839. }
  2840. switch (ValType.getObjCLifetime()) {
  2841. case Qualifiers::OCL_None:
  2842. case Qualifiers::OCL_ExplicitNone:
  2843. // okay
  2844. break;
  2845. case Qualifiers::OCL_Weak:
  2846. case Qualifiers::OCL_Strong:
  2847. case Qualifiers::OCL_Autoreleasing:
  2848. // FIXME: Can this happen? By this point, ValType should be known
  2849. // to be trivially copyable.
  2850. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  2851. << ValType << Ptr->getSourceRange();
  2852. return ExprError();
  2853. }
  2854. // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
  2855. // volatile-ness of the pointee-type inject itself into the result or the
  2856. // other operands. Similarly atomic_load can take a pointer to a const 'A'.
  2857. ValType.removeLocalVolatile();
  2858. ValType.removeLocalConst();
  2859. QualType ResultType = ValType;
  2860. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  2861. Form == Init)
  2862. ResultType = Context.VoidTy;
  2863. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  2864. ResultType = Context.BoolTy;
  2865. // The type of a parameter passed 'by value'. In the GNU atomics, such
  2866. // arguments are actually passed as pointers.
  2867. QualType ByValType = ValType; // 'CP'
  2868. if (!IsC11 && !IsN)
  2869. ByValType = Ptr->getType();
  2870. // The first argument --- the pointer --- has a fixed type; we
  2871. // deduce the types of the rest of the arguments accordingly. Walk
  2872. // the remaining arguments, converting them to the deduced value type.
  2873. for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
  2874. QualType Ty;
  2875. if (i < NumVals[Form] + 1) {
  2876. switch (i) {
  2877. case 1:
  2878. // The second argument is the non-atomic operand. For arithmetic, this
  2879. // is always passed by value, and for a compare_exchange it is always
  2880. // passed by address. For the rest, GNU uses by-address and C11 uses
  2881. // by-value.
  2882. assert(Form != Load);
  2883. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  2884. Ty = ValType;
  2885. else if (Form == Copy || Form == Xchg)
  2886. Ty = ByValType;
  2887. else if (Form == Arithmetic)
  2888. Ty = Context.getPointerDiffType();
  2889. else {
  2890. Expr *ValArg = TheCall->getArg(i);
  2891. // Treat this argument as _Nonnull as we want to show a warning if
  2892. // NULL is passed into it.
  2893. CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
  2894. LangAS AS = LangAS::Default;
  2895. // Keep address space of non-atomic pointer type.
  2896. if (const PointerType *PtrTy =
  2897. ValArg->getType()->getAs<PointerType>()) {
  2898. AS = PtrTy->getPointeeType().getAddressSpace();
  2899. }
  2900. Ty = Context.getPointerType(
  2901. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  2902. }
  2903. break;
  2904. case 2:
  2905. // The third argument to compare_exchange / GNU exchange is a
  2906. // (pointer to a) desired value.
  2907. Ty = ByValType;
  2908. break;
  2909. case 3:
  2910. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  2911. Ty = Context.BoolTy;
  2912. break;
  2913. }
  2914. } else {
  2915. // The order(s) and scope are always converted to int.
  2916. Ty = Context.IntTy;
  2917. }
  2918. InitializedEntity Entity =
  2919. InitializedEntity::InitializeParameter(Context, Ty, false);
  2920. ExprResult Arg = TheCall->getArg(i);
  2921. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  2922. if (Arg.isInvalid())
  2923. return true;
  2924. TheCall->setArg(i, Arg.get());
  2925. }
  2926. // Permute the arguments into a 'consistent' order.
  2927. SmallVector<Expr*, 5> SubExprs;
  2928. SubExprs.push_back(Ptr);
  2929. switch (Form) {
  2930. case Init:
  2931. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  2932. SubExprs.push_back(TheCall->getArg(1)); // Val1
  2933. break;
  2934. case Load:
  2935. SubExprs.push_back(TheCall->getArg(1)); // Order
  2936. break;
  2937. case LoadCopy:
  2938. case Copy:
  2939. case Arithmetic:
  2940. case Xchg:
  2941. SubExprs.push_back(TheCall->getArg(2)); // Order
  2942. SubExprs.push_back(TheCall->getArg(1)); // Val1
  2943. break;
  2944. case GNUXchg:
  2945. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  2946. SubExprs.push_back(TheCall->getArg(3)); // Order
  2947. SubExprs.push_back(TheCall->getArg(1)); // Val1
  2948. SubExprs.push_back(TheCall->getArg(2)); // Val2
  2949. break;
  2950. case C11CmpXchg:
  2951. SubExprs.push_back(TheCall->getArg(3)); // Order
  2952. SubExprs.push_back(TheCall->getArg(1)); // Val1
  2953. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  2954. SubExprs.push_back(TheCall->getArg(2)); // Val2
  2955. break;
  2956. case GNUCmpXchg:
  2957. SubExprs.push_back(TheCall->getArg(4)); // Order
  2958. SubExprs.push_back(TheCall->getArg(1)); // Val1
  2959. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  2960. SubExprs.push_back(TheCall->getArg(2)); // Val2
  2961. SubExprs.push_back(TheCall->getArg(3)); // Weak
  2962. break;
  2963. }
  2964. if (SubExprs.size() >= 2 && Form != Init) {
  2965. llvm::APSInt Result(32);
  2966. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  2967. !isValidOrderingForOp(Result.getSExtValue(), Op))
  2968. Diag(SubExprs[1]->getLocStart(),
  2969. diag::warn_atomic_op_has_invalid_memory_order)
  2970. << SubExprs[1]->getSourceRange();
  2971. }
  2972. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  2973. auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
  2974. llvm::APSInt Result(32);
  2975. if (Scope->isIntegerConstantExpr(Result, Context) &&
  2976. !ScopeModel->isValid(Result.getZExtValue())) {
  2977. Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
  2978. << Scope->getSourceRange();
  2979. }
  2980. SubExprs.push_back(Scope);
  2981. }
  2982. AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  2983. SubExprs, ResultType, Op,
  2984. TheCall->getRParenLoc());
  2985. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  2986. Op == AtomicExpr::AO__c11_atomic_store ||
  2987. Op == AtomicExpr::AO__opencl_atomic_load ||
  2988. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  2989. Context.AtomicUsesUnsupportedLibcall(AE))
  2990. Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
  2991. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  2992. Op == AtomicExpr::AO__opencl_atomic_load)
  2993. ? 0 : 1);
  2994. return AE;
  2995. }
  2996. /// checkBuiltinArgument - Given a call to a builtin function, perform
  2997. /// normal type-checking on the given argument, updating the call in
  2998. /// place. This is useful when a builtin function requires custom
  2999. /// type-checking for some of its arguments but not necessarily all of
  3000. /// them.
  3001. ///
  3002. /// Returns true on error.
  3003. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  3004. FunctionDecl *Fn = E->getDirectCallee();
  3005. assert(Fn && "builtin call without direct callee!");
  3006. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  3007. InitializedEntity Entity =
  3008. InitializedEntity::InitializeParameter(S.Context, Param);
  3009. ExprResult Arg = E->getArg(0);
  3010. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  3011. if (Arg.isInvalid())
  3012. return true;
  3013. E->setArg(ArgIndex, Arg.get());
  3014. return false;
  3015. }
  3016. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  3017. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  3018. /// type of its first argument. The main ActOnCallExpr routines have already
  3019. /// promoted the types of arguments because all of these calls are prototyped as
  3020. /// void(...).
  3021. ///
  3022. /// This function goes through and does final semantic checking for these
  3023. /// builtins,
  3024. ExprResult
  3025. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  3026. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  3027. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  3028. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  3029. // Ensure that we have at least one argument to do type inference from.
  3030. if (TheCall->getNumArgs() < 1) {
  3031. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  3032. << 0 << 1 << TheCall->getNumArgs()
  3033. << TheCall->getCallee()->getSourceRange();
  3034. return ExprError();
  3035. }
  3036. // Inspect the first argument of the atomic builtin. This should always be
  3037. // a pointer type, whose element is an integral scalar or pointer type.
  3038. // Because it is a pointer type, we don't have to worry about any implicit
  3039. // casts here.
  3040. // FIXME: We don't allow floating point scalars as input.
  3041. Expr *FirstArg = TheCall->getArg(0);
  3042. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  3043. if (FirstArgResult.isInvalid())
  3044. return ExprError();
  3045. FirstArg = FirstArgResult.get();
  3046. TheCall->setArg(0, FirstArg);
  3047. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  3048. if (!pointerType) {
  3049. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  3050. << FirstArg->getType() << FirstArg->getSourceRange();
  3051. return ExprError();
  3052. }
  3053. QualType ValType = pointerType->getPointeeType();
  3054. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  3055. !ValType->isBlockPointerType()) {
  3056. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  3057. << FirstArg->getType() << FirstArg->getSourceRange();
  3058. return ExprError();
  3059. }
  3060. switch (ValType.getObjCLifetime()) {
  3061. case Qualifiers::OCL_None:
  3062. case Qualifiers::OCL_ExplicitNone:
  3063. // okay
  3064. break;
  3065. case Qualifiers::OCL_Weak:
  3066. case Qualifiers::OCL_Strong:
  3067. case Qualifiers::OCL_Autoreleasing:
  3068. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  3069. << ValType << FirstArg->getSourceRange();
  3070. return ExprError();
  3071. }
  3072. // Strip any qualifiers off ValType.
  3073. ValType = ValType.getUnqualifiedType();
  3074. // The majority of builtins return a value, but a few have special return
  3075. // types, so allow them to override appropriately below.
  3076. QualType ResultType = ValType;
  3077. // We need to figure out which concrete builtin this maps onto. For example,
  3078. // __sync_fetch_and_add with a 2 byte object turns into
  3079. // __sync_fetch_and_add_2.
  3080. #define BUILTIN_ROW(x) \
  3081. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  3082. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  3083. static const unsigned BuiltinIndices[][5] = {
  3084. BUILTIN_ROW(__sync_fetch_and_add),
  3085. BUILTIN_ROW(__sync_fetch_and_sub),
  3086. BUILTIN_ROW(__sync_fetch_and_or),
  3087. BUILTIN_ROW(__sync_fetch_and_and),
  3088. BUILTIN_ROW(__sync_fetch_and_xor),
  3089. BUILTIN_ROW(__sync_fetch_and_nand),
  3090. BUILTIN_ROW(__sync_add_and_fetch),
  3091. BUILTIN_ROW(__sync_sub_and_fetch),
  3092. BUILTIN_ROW(__sync_and_and_fetch),
  3093. BUILTIN_ROW(__sync_or_and_fetch),
  3094. BUILTIN_ROW(__sync_xor_and_fetch),
  3095. BUILTIN_ROW(__sync_nand_and_fetch),
  3096. BUILTIN_ROW(__sync_val_compare_and_swap),
  3097. BUILTIN_ROW(__sync_bool_compare_and_swap),
  3098. BUILTIN_ROW(__sync_lock_test_and_set),
  3099. BUILTIN_ROW(__sync_lock_release),
  3100. BUILTIN_ROW(__sync_swap)
  3101. };
  3102. #undef BUILTIN_ROW
  3103. // Determine the index of the size.
  3104. unsigned SizeIndex;
  3105. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  3106. case 1: SizeIndex = 0; break;
  3107. case 2: SizeIndex = 1; break;
  3108. case 4: SizeIndex = 2; break;
  3109. case 8: SizeIndex = 3; break;
  3110. case 16: SizeIndex = 4; break;
  3111. default:
  3112. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  3113. << FirstArg->getType() << FirstArg->getSourceRange();
  3114. return ExprError();
  3115. }
  3116. // Each of these builtins has one pointer argument, followed by some number of
  3117. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  3118. // that we ignore. Find out which row of BuiltinIndices to read from as well
  3119. // as the number of fixed args.
  3120. unsigned BuiltinID = FDecl->getBuiltinID();
  3121. unsigned BuiltinIndex, NumFixed = 1;
  3122. bool WarnAboutSemanticsChange = false;
  3123. switch (BuiltinID) {
  3124. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  3125. case Builtin::BI__sync_fetch_and_add:
  3126. case Builtin::BI__sync_fetch_and_add_1:
  3127. case Builtin::BI__sync_fetch_and_add_2:
  3128. case Builtin::BI__sync_fetch_and_add_4:
  3129. case Builtin::BI__sync_fetch_and_add_8:
  3130. case Builtin::BI__sync_fetch_and_add_16:
  3131. BuiltinIndex = 0;
  3132. break;
  3133. case Builtin::BI__sync_fetch_and_sub:
  3134. case Builtin::BI__sync_fetch_and_sub_1:
  3135. case Builtin::BI__sync_fetch_and_sub_2:
  3136. case Builtin::BI__sync_fetch_and_sub_4:
  3137. case Builtin::BI__sync_fetch_and_sub_8:
  3138. case Builtin::BI__sync_fetch_and_sub_16:
  3139. BuiltinIndex = 1;
  3140. break;
  3141. case Builtin::BI__sync_fetch_and_or:
  3142. case Builtin::BI__sync_fetch_and_or_1:
  3143. case Builtin::BI__sync_fetch_and_or_2:
  3144. case Builtin::BI__sync_fetch_and_or_4:
  3145. case Builtin::BI__sync_fetch_and_or_8:
  3146. case Builtin::BI__sync_fetch_and_or_16:
  3147. BuiltinIndex = 2;
  3148. break;
  3149. case Builtin::BI__sync_fetch_and_and:
  3150. case Builtin::BI__sync_fetch_and_and_1:
  3151. case Builtin::BI__sync_fetch_and_and_2:
  3152. case Builtin::BI__sync_fetch_and_and_4:
  3153. case Builtin::BI__sync_fetch_and_and_8:
  3154. case Builtin::BI__sync_fetch_and_and_16:
  3155. BuiltinIndex = 3;
  3156. break;
  3157. case Builtin::BI__sync_fetch_and_xor:
  3158. case Builtin::BI__sync_fetch_and_xor_1:
  3159. case Builtin::BI__sync_fetch_and_xor_2:
  3160. case Builtin::BI__sync_fetch_and_xor_4:
  3161. case Builtin::BI__sync_fetch_and_xor_8:
  3162. case Builtin::BI__sync_fetch_and_xor_16:
  3163. BuiltinIndex = 4;
  3164. break;
  3165. case Builtin::BI__sync_fetch_and_nand:
  3166. case Builtin::BI__sync_fetch_and_nand_1:
  3167. case Builtin::BI__sync_fetch_and_nand_2:
  3168. case Builtin::BI__sync_fetch_and_nand_4:
  3169. case Builtin::BI__sync_fetch_and_nand_8:
  3170. case Builtin::BI__sync_fetch_and_nand_16:
  3171. BuiltinIndex = 5;
  3172. WarnAboutSemanticsChange = true;
  3173. break;
  3174. case Builtin::BI__sync_add_and_fetch:
  3175. case Builtin::BI__sync_add_and_fetch_1:
  3176. case Builtin::BI__sync_add_and_fetch_2:
  3177. case Builtin::BI__sync_add_and_fetch_4:
  3178. case Builtin::BI__sync_add_and_fetch_8:
  3179. case Builtin::BI__sync_add_and_fetch_16:
  3180. BuiltinIndex = 6;
  3181. break;
  3182. case Builtin::BI__sync_sub_and_fetch:
  3183. case Builtin::BI__sync_sub_and_fetch_1:
  3184. case Builtin::BI__sync_sub_and_fetch_2:
  3185. case Builtin::BI__sync_sub_and_fetch_4:
  3186. case Builtin::BI__sync_sub_and_fetch_8:
  3187. case Builtin::BI__sync_sub_and_fetch_16:
  3188. BuiltinIndex = 7;
  3189. break;
  3190. case Builtin::BI__sync_and_and_fetch:
  3191. case Builtin::BI__sync_and_and_fetch_1:
  3192. case Builtin::BI__sync_and_and_fetch_2:
  3193. case Builtin::BI__sync_and_and_fetch_4:
  3194. case Builtin::BI__sync_and_and_fetch_8:
  3195. case Builtin::BI__sync_and_and_fetch_16:
  3196. BuiltinIndex = 8;
  3197. break;
  3198. case Builtin::BI__sync_or_and_fetch:
  3199. case Builtin::BI__sync_or_and_fetch_1:
  3200. case Builtin::BI__sync_or_and_fetch_2:
  3201. case Builtin::BI__sync_or_and_fetch_4:
  3202. case Builtin::BI__sync_or_and_fetch_8:
  3203. case Builtin::BI__sync_or_and_fetch_16:
  3204. BuiltinIndex = 9;
  3205. break;
  3206. case Builtin::BI__sync_xor_and_fetch:
  3207. case Builtin::BI__sync_xor_and_fetch_1:
  3208. case Builtin::BI__sync_xor_and_fetch_2:
  3209. case Builtin::BI__sync_xor_and_fetch_4:
  3210. case Builtin::BI__sync_xor_and_fetch_8:
  3211. case Builtin::BI__sync_xor_and_fetch_16:
  3212. BuiltinIndex = 10;
  3213. break;
  3214. case Builtin::BI__sync_nand_and_fetch:
  3215. case Builtin::BI__sync_nand_and_fetch_1:
  3216. case Builtin::BI__sync_nand_and_fetch_2:
  3217. case Builtin::BI__sync_nand_and_fetch_4:
  3218. case Builtin::BI__sync_nand_and_fetch_8:
  3219. case Builtin::BI__sync_nand_and_fetch_16:
  3220. BuiltinIndex = 11;
  3221. WarnAboutSemanticsChange = true;
  3222. break;
  3223. case Builtin::BI__sync_val_compare_and_swap:
  3224. case Builtin::BI__sync_val_compare_and_swap_1:
  3225. case Builtin::BI__sync_val_compare_and_swap_2:
  3226. case Builtin::BI__sync_val_compare_and_swap_4:
  3227. case Builtin::BI__sync_val_compare_and_swap_8:
  3228. case Builtin::BI__sync_val_compare_and_swap_16:
  3229. BuiltinIndex = 12;
  3230. NumFixed = 2;
  3231. break;
  3232. case Builtin::BI__sync_bool_compare_and_swap:
  3233. case Builtin::BI__sync_bool_compare_and_swap_1:
  3234. case Builtin::BI__sync_bool_compare_and_swap_2:
  3235. case Builtin::BI__sync_bool_compare_and_swap_4:
  3236. case Builtin::BI__sync_bool_compare_and_swap_8:
  3237. case Builtin::BI__sync_bool_compare_and_swap_16:
  3238. BuiltinIndex = 13;
  3239. NumFixed = 2;
  3240. ResultType = Context.BoolTy;
  3241. break;
  3242. case Builtin::BI__sync_lock_test_and_set:
  3243. case Builtin::BI__sync_lock_test_and_set_1:
  3244. case Builtin::BI__sync_lock_test_and_set_2:
  3245. case Builtin::BI__sync_lock_test_and_set_4:
  3246. case Builtin::BI__sync_lock_test_and_set_8:
  3247. case Builtin::BI__sync_lock_test_and_set_16:
  3248. BuiltinIndex = 14;
  3249. break;
  3250. case Builtin::BI__sync_lock_release:
  3251. case Builtin::BI__sync_lock_release_1:
  3252. case Builtin::BI__sync_lock_release_2:
  3253. case Builtin::BI__sync_lock_release_4:
  3254. case Builtin::BI__sync_lock_release_8:
  3255. case Builtin::BI__sync_lock_release_16:
  3256. BuiltinIndex = 15;
  3257. NumFixed = 0;
  3258. ResultType = Context.VoidTy;
  3259. break;
  3260. case Builtin::BI__sync_swap:
  3261. case Builtin::BI__sync_swap_1:
  3262. case Builtin::BI__sync_swap_2:
  3263. case Builtin::BI__sync_swap_4:
  3264. case Builtin::BI__sync_swap_8:
  3265. case Builtin::BI__sync_swap_16:
  3266. BuiltinIndex = 16;
  3267. break;
  3268. }
  3269. // Now that we know how many fixed arguments we expect, first check that we
  3270. // have at least that many.
  3271. if (TheCall->getNumArgs() < 1+NumFixed) {
  3272. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  3273. << 0 << 1+NumFixed << TheCall->getNumArgs()
  3274. << TheCall->getCallee()->getSourceRange();
  3275. return ExprError();
  3276. }
  3277. if (WarnAboutSemanticsChange) {
  3278. Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
  3279. << TheCall->getCallee()->getSourceRange();
  3280. }
  3281. // Get the decl for the concrete builtin from this, we can tell what the
  3282. // concrete integer type we should convert to is.
  3283. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  3284. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  3285. FunctionDecl *NewBuiltinDecl;
  3286. if (NewBuiltinID == BuiltinID)
  3287. NewBuiltinDecl = FDecl;
  3288. else {
  3289. // Perform builtin lookup to avoid redeclaring it.
  3290. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  3291. LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
  3292. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  3293. assert(Res.getFoundDecl());
  3294. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  3295. if (!NewBuiltinDecl)
  3296. return ExprError();
  3297. }
  3298. // The first argument --- the pointer --- has a fixed type; we
  3299. // deduce the types of the rest of the arguments accordingly. Walk
  3300. // the remaining arguments, converting them to the deduced value type.
  3301. for (unsigned i = 0; i != NumFixed; ++i) {
  3302. ExprResult Arg = TheCall->getArg(i+1);
  3303. // GCC does an implicit conversion to the pointer or integer ValType. This
  3304. // can fail in some cases (1i -> int**), check for this error case now.
  3305. // Initialize the argument.
  3306. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  3307. ValType, /*consume*/ false);
  3308. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  3309. if (Arg.isInvalid())
  3310. return ExprError();
  3311. // Okay, we have something that *can* be converted to the right type. Check
  3312. // to see if there is a potentially weird extension going on here. This can
  3313. // happen when you do an atomic operation on something like an char* and
  3314. // pass in 42. The 42 gets converted to char. This is even more strange
  3315. // for things like 45.123 -> char, etc.
  3316. // FIXME: Do this check.
  3317. TheCall->setArg(i+1, Arg.get());
  3318. }
  3319. ASTContext& Context = this->getASTContext();
  3320. // Create a new DeclRefExpr to refer to the new decl.
  3321. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  3322. Context,
  3323. DRE->getQualifierLoc(),
  3324. SourceLocation(),
  3325. NewBuiltinDecl,
  3326. /*enclosing*/ false,
  3327. DRE->getLocation(),
  3328. Context.BuiltinFnTy,
  3329. DRE->getValueKind());
  3330. // Set the callee in the CallExpr.
  3331. // FIXME: This loses syntactic information.
  3332. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  3333. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  3334. CK_BuiltinFnToFnPtr);
  3335. TheCall->setCallee(PromotedCall.get());
  3336. // Change the result type of the call to match the original value type. This
  3337. // is arbitrary, but the codegen for these builtins ins design to handle it
  3338. // gracefully.
  3339. TheCall->setType(ResultType);
  3340. return TheCallResult;
  3341. }
  3342. /// SemaBuiltinNontemporalOverloaded - We have a call to
  3343. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  3344. /// overloaded function based on the pointer type of its last argument.
  3345. ///
  3346. /// This function goes through and does final semantic checking for these
  3347. /// builtins.
  3348. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  3349. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  3350. DeclRefExpr *DRE =
  3351. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  3352. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  3353. unsigned BuiltinID = FDecl->getBuiltinID();
  3354. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  3355. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  3356. "Unexpected nontemporal load/store builtin!");
  3357. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  3358. unsigned numArgs = isStore ? 2 : 1;
  3359. // Ensure that we have the proper number of arguments.
  3360. if (checkArgCount(*this, TheCall, numArgs))
  3361. return ExprError();
  3362. // Inspect the last argument of the nontemporal builtin. This should always
  3363. // be a pointer type, from which we imply the type of the memory access.
  3364. // Because it is a pointer type, we don't have to worry about any implicit
  3365. // casts here.
  3366. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  3367. ExprResult PointerArgResult =
  3368. DefaultFunctionArrayLvalueConversion(PointerArg);
  3369. if (PointerArgResult.isInvalid())
  3370. return ExprError();
  3371. PointerArg = PointerArgResult.get();
  3372. TheCall->setArg(numArgs - 1, PointerArg);
  3373. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  3374. if (!pointerType) {
  3375. Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
  3376. << PointerArg->getType() << PointerArg->getSourceRange();
  3377. return ExprError();
  3378. }
  3379. QualType ValType = pointerType->getPointeeType();
  3380. // Strip any qualifiers off ValType.
  3381. ValType = ValType.getUnqualifiedType();
  3382. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  3383. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  3384. !ValType->isVectorType()) {
  3385. Diag(DRE->getLocStart(),
  3386. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  3387. << PointerArg->getType() << PointerArg->getSourceRange();
  3388. return ExprError();
  3389. }
  3390. if (!isStore) {
  3391. TheCall->setType(ValType);
  3392. return TheCallResult;
  3393. }
  3394. ExprResult ValArg = TheCall->getArg(0);
  3395. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  3396. Context, ValType, /*consume*/ false);
  3397. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  3398. if (ValArg.isInvalid())
  3399. return ExprError();
  3400. TheCall->setArg(0, ValArg.get());
  3401. TheCall->setType(Context.VoidTy);
  3402. return TheCallResult;
  3403. }
  3404. /// CheckObjCString - Checks that the argument to the builtin
  3405. /// CFString constructor is correct
  3406. /// Note: It might also make sense to do the UTF-16 conversion here (would
  3407. /// simplify the backend).
  3408. bool Sema::CheckObjCString(Expr *Arg) {
  3409. Arg = Arg->IgnoreParenCasts();
  3410. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  3411. if (!Literal || !Literal->isAscii()) {
  3412. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  3413. << Arg->getSourceRange();
  3414. return true;
  3415. }
  3416. if (Literal->containsNonAsciiOrNull()) {
  3417. StringRef String = Literal->getString();
  3418. unsigned NumBytes = String.size();
  3419. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  3420. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  3421. llvm::UTF16 *ToPtr = &ToBuf[0];
  3422. llvm::ConversionResult Result =
  3423. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  3424. ToPtr + NumBytes, llvm::strictConversion);
  3425. // Check for conversion failure.
  3426. if (Result != llvm::conversionOK)
  3427. Diag(Arg->getLocStart(),
  3428. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  3429. }
  3430. return false;
  3431. }
  3432. /// CheckObjCString - Checks that the format string argument to the os_log()
  3433. /// and os_trace() functions is correct, and converts it to const char *.
  3434. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  3435. Arg = Arg->IgnoreParenCasts();
  3436. auto *Literal = dyn_cast<StringLiteral>(Arg);
  3437. if (!Literal) {
  3438. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  3439. Literal = ObjcLiteral->getString();
  3440. }
  3441. }
  3442. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  3443. return ExprError(
  3444. Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
  3445. << Arg->getSourceRange());
  3446. }
  3447. ExprResult Result(Literal);
  3448. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  3449. InitializedEntity Entity =
  3450. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  3451. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  3452. return Result;
  3453. }
  3454. /// Check that the user is calling the appropriate va_start builtin for the
  3455. /// target and calling convention.
  3456. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  3457. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  3458. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  3459. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  3460. bool IsWindows = TT.isOSWindows();
  3461. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  3462. if (IsX64 || IsAArch64) {
  3463. clang::CallingConv CC = CC_C;
  3464. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  3465. CC = FD->getType()->getAs<FunctionType>()->getCallConv();
  3466. if (IsMSVAStart) {
  3467. // Don't allow this in System V ABI functions.
  3468. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  3469. return S.Diag(Fn->getLocStart(),
  3470. diag::err_ms_va_start_used_in_sysv_function);
  3471. } else {
  3472. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  3473. // On x64 Windows, don't allow this in System V ABI functions.
  3474. // (Yes, that means there's no corresponding way to support variadic
  3475. // System V ABI functions on Windows.)
  3476. if ((IsWindows && CC == CC_X86_64SysV) ||
  3477. (!IsWindows && CC == CC_Win64))
  3478. return S.Diag(Fn->getLocStart(),
  3479. diag::err_va_start_used_in_wrong_abi_function)
  3480. << !IsWindows;
  3481. }
  3482. return false;
  3483. }
  3484. if (IsMSVAStart)
  3485. return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
  3486. return false;
  3487. }
  3488. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  3489. ParmVarDecl **LastParam = nullptr) {
  3490. // Determine whether the current function, block, or obj-c method is variadic
  3491. // and get its parameter list.
  3492. bool IsVariadic = false;
  3493. ArrayRef<ParmVarDecl *> Params;
  3494. DeclContext *Caller = S.CurContext;
  3495. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  3496. IsVariadic = Block->isVariadic();
  3497. Params = Block->parameters();
  3498. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  3499. IsVariadic = FD->isVariadic();
  3500. Params = FD->parameters();
  3501. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  3502. IsVariadic = MD->isVariadic();
  3503. // FIXME: This isn't correct for methods (results in bogus warning).
  3504. Params = MD->parameters();
  3505. } else if (isa<CapturedDecl>(Caller)) {
  3506. // We don't support va_start in a CapturedDecl.
  3507. S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
  3508. return true;
  3509. } else {
  3510. // This must be some other declcontext that parses exprs.
  3511. S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
  3512. return true;
  3513. }
  3514. if (!IsVariadic) {
  3515. S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
  3516. return true;
  3517. }
  3518. if (LastParam)
  3519. *LastParam = Params.empty() ? nullptr : Params.back();
  3520. return false;
  3521. }
  3522. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  3523. /// for validity. Emit an error and return true on failure; return false
  3524. /// on success.
  3525. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  3526. Expr *Fn = TheCall->getCallee();
  3527. if (checkVAStartABI(*this, BuiltinID, Fn))
  3528. return true;
  3529. if (TheCall->getNumArgs() > 2) {
  3530. Diag(TheCall->getArg(2)->getLocStart(),
  3531. diag::err_typecheck_call_too_many_args)
  3532. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  3533. << Fn->getSourceRange()
  3534. << SourceRange(TheCall->getArg(2)->getLocStart(),
  3535. (*(TheCall->arg_end()-1))->getLocEnd());
  3536. return true;
  3537. }
  3538. if (TheCall->getNumArgs() < 2) {
  3539. return Diag(TheCall->getLocEnd(),
  3540. diag::err_typecheck_call_too_few_args_at_least)
  3541. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  3542. }
  3543. // Type-check the first argument normally.
  3544. if (checkBuiltinArgument(*this, TheCall, 0))
  3545. return true;
  3546. // Check that the current function is variadic, and get its last parameter.
  3547. ParmVarDecl *LastParam;
  3548. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  3549. return true;
  3550. // Verify that the second argument to the builtin is the last argument of the
  3551. // current function or method.
  3552. bool SecondArgIsLastNamedArgument = false;
  3553. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  3554. // These are valid if SecondArgIsLastNamedArgument is false after the next
  3555. // block.
  3556. QualType Type;
  3557. SourceLocation ParamLoc;
  3558. bool IsCRegister = false;
  3559. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  3560. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  3561. SecondArgIsLastNamedArgument = PV == LastParam;
  3562. Type = PV->getType();
  3563. ParamLoc = PV->getLocation();
  3564. IsCRegister =
  3565. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  3566. }
  3567. }
  3568. if (!SecondArgIsLastNamedArgument)
  3569. Diag(TheCall->getArg(1)->getLocStart(),
  3570. diag::warn_second_arg_of_va_start_not_last_named_param);
  3571. else if (IsCRegister || Type->isReferenceType() ||
  3572. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  3573. // Promotable integers are UB, but enumerations need a bit of
  3574. // extra checking to see what their promotable type actually is.
  3575. if (!Type->isPromotableIntegerType())
  3576. return false;
  3577. if (!Type->isEnumeralType())
  3578. return true;
  3579. const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
  3580. return !(ED &&
  3581. Context.typesAreCompatible(ED->getPromotionType(), Type));
  3582. }()) {
  3583. unsigned Reason = 0;
  3584. if (Type->isReferenceType()) Reason = 1;
  3585. else if (IsCRegister) Reason = 2;
  3586. Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
  3587. Diag(ParamLoc, diag::note_parameter_type) << Type;
  3588. }
  3589. TheCall->setType(Context.VoidTy);
  3590. return false;
  3591. }
  3592. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  3593. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  3594. // const char *named_addr);
  3595. Expr *Func = Call->getCallee();
  3596. if (Call->getNumArgs() < 3)
  3597. return Diag(Call->getLocEnd(),
  3598. diag::err_typecheck_call_too_few_args_at_least)
  3599. << 0 /*function call*/ << 3 << Call->getNumArgs();
  3600. // Type-check the first argument normally.
  3601. if (checkBuiltinArgument(*this, Call, 0))
  3602. return true;
  3603. // Check that the current function is variadic.
  3604. if (checkVAStartIsInVariadicFunction(*this, Func))
  3605. return true;
  3606. // __va_start on Windows does not validate the parameter qualifiers
  3607. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  3608. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  3609. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  3610. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  3611. const QualType &ConstCharPtrTy =
  3612. Context.getPointerType(Context.CharTy.withConst());
  3613. if (!Arg1Ty->isPointerType() ||
  3614. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  3615. Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
  3616. << Arg1->getType() << ConstCharPtrTy
  3617. << 1 /* different class */
  3618. << 0 /* qualifier difference */
  3619. << 3 /* parameter mismatch */
  3620. << 2 << Arg1->getType() << ConstCharPtrTy;
  3621. const QualType SizeTy = Context.getSizeType();
  3622. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  3623. Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
  3624. << Arg2->getType() << SizeTy
  3625. << 1 /* different class */
  3626. << 0 /* qualifier difference */
  3627. << 3 /* parameter mismatch */
  3628. << 3 << Arg2->getType() << SizeTy;
  3629. return false;
  3630. }
  3631. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  3632. /// friends. This is declared to take (...), so we have to check everything.
  3633. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  3634. if (TheCall->getNumArgs() < 2)
  3635. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  3636. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  3637. if (TheCall->getNumArgs() > 2)
  3638. return Diag(TheCall->getArg(2)->getLocStart(),
  3639. diag::err_typecheck_call_too_many_args)
  3640. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  3641. << SourceRange(TheCall->getArg(2)->getLocStart(),
  3642. (*(TheCall->arg_end()-1))->getLocEnd());
  3643. ExprResult OrigArg0 = TheCall->getArg(0);
  3644. ExprResult OrigArg1 = TheCall->getArg(1);
  3645. // Do standard promotions between the two arguments, returning their common
  3646. // type.
  3647. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  3648. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  3649. return true;
  3650. // Make sure any conversions are pushed back into the call; this is
  3651. // type safe since unordered compare builtins are declared as "_Bool
  3652. // foo(...)".
  3653. TheCall->setArg(0, OrigArg0.get());
  3654. TheCall->setArg(1, OrigArg1.get());
  3655. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  3656. return false;
  3657. // If the common type isn't a real floating type, then the arguments were
  3658. // invalid for this operation.
  3659. if (Res.isNull() || !Res->isRealFloatingType())
  3660. return Diag(OrigArg0.get()->getLocStart(),
  3661. diag::err_typecheck_call_invalid_ordered_compare)
  3662. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  3663. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  3664. return false;
  3665. }
  3666. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  3667. /// __builtin_isnan and friends. This is declared to take (...), so we have
  3668. /// to check everything. We expect the last argument to be a floating point
  3669. /// value.
  3670. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  3671. if (TheCall->getNumArgs() < NumArgs)
  3672. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  3673. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  3674. if (TheCall->getNumArgs() > NumArgs)
  3675. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  3676. diag::err_typecheck_call_too_many_args)
  3677. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  3678. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  3679. (*(TheCall->arg_end()-1))->getLocEnd());
  3680. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  3681. if (OrigArg->isTypeDependent())
  3682. return false;
  3683. // This operation requires a non-_Complex floating-point number.
  3684. if (!OrigArg->getType()->isRealFloatingType())
  3685. return Diag(OrigArg->getLocStart(),
  3686. diag::err_typecheck_call_invalid_unary_fp)
  3687. << OrigArg->getType() << OrigArg->getSourceRange();
  3688. // If this is an implicit conversion from float -> float or double, remove it.
  3689. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  3690. // Only remove standard FloatCasts, leaving other casts inplace
  3691. if (Cast->getCastKind() == CK_FloatingCast) {
  3692. Expr *CastArg = Cast->getSubExpr();
  3693. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  3694. assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  3695. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
  3696. "promotion from float to either float or double is the only expected cast here");
  3697. Cast->setSubExpr(nullptr);
  3698. TheCall->setArg(NumArgs-1, CastArg);
  3699. }
  3700. }
  3701. }
  3702. return false;
  3703. }
  3704. // Customized Sema Checking for VSX builtins that have the following signature:
  3705. // vector [...] builtinName(vector [...], vector [...], const int);
  3706. // Which takes the same type of vectors (any legal vector type) for the first
  3707. // two arguments and takes compile time constant for the third argument.
  3708. // Example builtins are :
  3709. // vector double vec_xxpermdi(vector double, vector double, int);
  3710. // vector short vec_xxsldwi(vector short, vector short, int);
  3711. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  3712. unsigned ExpectedNumArgs = 3;
  3713. if (TheCall->getNumArgs() < ExpectedNumArgs)
  3714. return Diag(TheCall->getLocEnd(),
  3715. diag::err_typecheck_call_too_few_args_at_least)
  3716. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  3717. << TheCall->getSourceRange();
  3718. if (TheCall->getNumArgs() > ExpectedNumArgs)
  3719. return Diag(TheCall->getLocEnd(),
  3720. diag::err_typecheck_call_too_many_args_at_most)
  3721. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  3722. << TheCall->getSourceRange();
  3723. // Check the third argument is a compile time constant
  3724. llvm::APSInt Value;
  3725. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  3726. return Diag(TheCall->getLocStart(),
  3727. diag::err_vsx_builtin_nonconstant_argument)
  3728. << 3 /* argument index */ << TheCall->getDirectCallee()
  3729. << SourceRange(TheCall->getArg(2)->getLocStart(),
  3730. TheCall->getArg(2)->getLocEnd());
  3731. QualType Arg1Ty = TheCall->getArg(0)->getType();
  3732. QualType Arg2Ty = TheCall->getArg(1)->getType();
  3733. // Check the type of argument 1 and argument 2 are vectors.
  3734. SourceLocation BuiltinLoc = TheCall->getLocStart();
  3735. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  3736. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  3737. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  3738. << TheCall->getDirectCallee()
  3739. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3740. TheCall->getArg(1)->getLocEnd());
  3741. }
  3742. // Check the first two arguments are the same type.
  3743. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  3744. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  3745. << TheCall->getDirectCallee()
  3746. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3747. TheCall->getArg(1)->getLocEnd());
  3748. }
  3749. // When default clang type checking is turned off and the customized type
  3750. // checking is used, the returning type of the function must be explicitly
  3751. // set. Otherwise it is _Bool by default.
  3752. TheCall->setType(Arg1Ty);
  3753. return false;
  3754. }
  3755. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  3756. // This is declared to take (...), so we have to check everything.
  3757. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  3758. if (TheCall->getNumArgs() < 2)
  3759. return ExprError(Diag(TheCall->getLocEnd(),
  3760. diag::err_typecheck_call_too_few_args_at_least)
  3761. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  3762. << TheCall->getSourceRange());
  3763. // Determine which of the following types of shufflevector we're checking:
  3764. // 1) unary, vector mask: (lhs, mask)
  3765. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  3766. QualType resType = TheCall->getArg(0)->getType();
  3767. unsigned numElements = 0;
  3768. if (!TheCall->getArg(0)->isTypeDependent() &&
  3769. !TheCall->getArg(1)->isTypeDependent()) {
  3770. QualType LHSType = TheCall->getArg(0)->getType();
  3771. QualType RHSType = TheCall->getArg(1)->getType();
  3772. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  3773. return ExprError(Diag(TheCall->getLocStart(),
  3774. diag::err_vec_builtin_non_vector)
  3775. << TheCall->getDirectCallee()
  3776. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3777. TheCall->getArg(1)->getLocEnd()));
  3778. numElements = LHSType->getAs<VectorType>()->getNumElements();
  3779. unsigned numResElements = TheCall->getNumArgs() - 2;
  3780. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  3781. // with mask. If so, verify that RHS is an integer vector type with the
  3782. // same number of elts as lhs.
  3783. if (TheCall->getNumArgs() == 2) {
  3784. if (!RHSType->hasIntegerRepresentation() ||
  3785. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  3786. return ExprError(Diag(TheCall->getLocStart(),
  3787. diag::err_vec_builtin_incompatible_vector)
  3788. << TheCall->getDirectCallee()
  3789. << SourceRange(TheCall->getArg(1)->getLocStart(),
  3790. TheCall->getArg(1)->getLocEnd()));
  3791. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  3792. return ExprError(Diag(TheCall->getLocStart(),
  3793. diag::err_vec_builtin_incompatible_vector)
  3794. << TheCall->getDirectCallee()
  3795. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3796. TheCall->getArg(1)->getLocEnd()));
  3797. } else if (numElements != numResElements) {
  3798. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  3799. resType = Context.getVectorType(eltType, numResElements,
  3800. VectorType::GenericVector);
  3801. }
  3802. }
  3803. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  3804. if (TheCall->getArg(i)->isTypeDependent() ||
  3805. TheCall->getArg(i)->isValueDependent())
  3806. continue;
  3807. llvm::APSInt Result(32);
  3808. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  3809. return ExprError(Diag(TheCall->getLocStart(),
  3810. diag::err_shufflevector_nonconstant_argument)
  3811. << TheCall->getArg(i)->getSourceRange());
  3812. // Allow -1 which will be translated to undef in the IR.
  3813. if (Result.isSigned() && Result.isAllOnesValue())
  3814. continue;
  3815. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  3816. return ExprError(Diag(TheCall->getLocStart(),
  3817. diag::err_shufflevector_argument_too_large)
  3818. << TheCall->getArg(i)->getSourceRange());
  3819. }
  3820. SmallVector<Expr*, 32> exprs;
  3821. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  3822. exprs.push_back(TheCall->getArg(i));
  3823. TheCall->setArg(i, nullptr);
  3824. }
  3825. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  3826. TheCall->getCallee()->getLocStart(),
  3827. TheCall->getRParenLoc());
  3828. }
  3829. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  3830. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  3831. SourceLocation BuiltinLoc,
  3832. SourceLocation RParenLoc) {
  3833. ExprValueKind VK = VK_RValue;
  3834. ExprObjectKind OK = OK_Ordinary;
  3835. QualType DstTy = TInfo->getType();
  3836. QualType SrcTy = E->getType();
  3837. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  3838. return ExprError(Diag(BuiltinLoc,
  3839. diag::err_convertvector_non_vector)
  3840. << E->getSourceRange());
  3841. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  3842. return ExprError(Diag(BuiltinLoc,
  3843. diag::err_convertvector_non_vector_type));
  3844. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  3845. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  3846. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  3847. if (SrcElts != DstElts)
  3848. return ExprError(Diag(BuiltinLoc,
  3849. diag::err_convertvector_incompatible_vector)
  3850. << E->getSourceRange());
  3851. }
  3852. return new (Context)
  3853. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  3854. }
  3855. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  3856. // This is declared to take (const void*, ...) and can take two
  3857. // optional constant int args.
  3858. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  3859. unsigned NumArgs = TheCall->getNumArgs();
  3860. if (NumArgs > 3)
  3861. return Diag(TheCall->getLocEnd(),
  3862. diag::err_typecheck_call_too_many_args_at_most)
  3863. << 0 /*function call*/ << 3 << NumArgs
  3864. << TheCall->getSourceRange();
  3865. // Argument 0 is checked for us and the remaining arguments must be
  3866. // constant integers.
  3867. for (unsigned i = 1; i != NumArgs; ++i)
  3868. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  3869. return true;
  3870. return false;
  3871. }
  3872. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  3873. // __assume does not evaluate its arguments, and should warn if its argument
  3874. // has side effects.
  3875. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  3876. Expr *Arg = TheCall->getArg(0);
  3877. if (Arg->isInstantiationDependent()) return false;
  3878. if (Arg->HasSideEffects(Context))
  3879. Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
  3880. << Arg->getSourceRange()
  3881. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  3882. return false;
  3883. }
  3884. /// Handle __builtin_alloca_with_align. This is declared
  3885. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  3886. /// than 8.
  3887. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  3888. // The alignment must be a constant integer.
  3889. Expr *Arg = TheCall->getArg(1);
  3890. // We can't check the value of a dependent argument.
  3891. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  3892. if (const auto *UE =
  3893. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  3894. if (UE->getKind() == UETT_AlignOf)
  3895. Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
  3896. << Arg->getSourceRange();
  3897. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  3898. if (!Result.isPowerOf2())
  3899. return Diag(TheCall->getLocStart(),
  3900. diag::err_alignment_not_power_of_two)
  3901. << Arg->getSourceRange();
  3902. if (Result < Context.getCharWidth())
  3903. return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
  3904. << (unsigned)Context.getCharWidth()
  3905. << Arg->getSourceRange();
  3906. if (Result > INT32_MAX)
  3907. return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
  3908. << INT32_MAX
  3909. << Arg->getSourceRange();
  3910. }
  3911. return false;
  3912. }
  3913. /// Handle __builtin_assume_aligned. This is declared
  3914. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  3915. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  3916. unsigned NumArgs = TheCall->getNumArgs();
  3917. if (NumArgs > 3)
  3918. return Diag(TheCall->getLocEnd(),
  3919. diag::err_typecheck_call_too_many_args_at_most)
  3920. << 0 /*function call*/ << 3 << NumArgs
  3921. << TheCall->getSourceRange();
  3922. // The alignment must be a constant integer.
  3923. Expr *Arg = TheCall->getArg(1);
  3924. // We can't check the value of a dependent argument.
  3925. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  3926. llvm::APSInt Result;
  3927. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  3928. return true;
  3929. if (!Result.isPowerOf2())
  3930. return Diag(TheCall->getLocStart(),
  3931. diag::err_alignment_not_power_of_two)
  3932. << Arg->getSourceRange();
  3933. }
  3934. if (NumArgs > 2) {
  3935. ExprResult Arg(TheCall->getArg(2));
  3936. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  3937. Context.getSizeType(), false);
  3938. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  3939. if (Arg.isInvalid()) return true;
  3940. TheCall->setArg(2, Arg.get());
  3941. }
  3942. return false;
  3943. }
  3944. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  3945. unsigned BuiltinID =
  3946. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  3947. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  3948. unsigned NumArgs = TheCall->getNumArgs();
  3949. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  3950. if (NumArgs < NumRequiredArgs) {
  3951. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  3952. << 0 /* function call */ << NumRequiredArgs << NumArgs
  3953. << TheCall->getSourceRange();
  3954. }
  3955. if (NumArgs >= NumRequiredArgs + 0x100) {
  3956. return Diag(TheCall->getLocEnd(),
  3957. diag::err_typecheck_call_too_many_args_at_most)
  3958. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  3959. << TheCall->getSourceRange();
  3960. }
  3961. unsigned i = 0;
  3962. // For formatting call, check buffer arg.
  3963. if (!IsSizeCall) {
  3964. ExprResult Arg(TheCall->getArg(i));
  3965. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  3966. Context, Context.VoidPtrTy, false);
  3967. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  3968. if (Arg.isInvalid())
  3969. return true;
  3970. TheCall->setArg(i, Arg.get());
  3971. i++;
  3972. }
  3973. // Check string literal arg.
  3974. unsigned FormatIdx = i;
  3975. {
  3976. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  3977. if (Arg.isInvalid())
  3978. return true;
  3979. TheCall->setArg(i, Arg.get());
  3980. i++;
  3981. }
  3982. // Make sure variadic args are scalar.
  3983. unsigned FirstDataArg = i;
  3984. while (i < NumArgs) {
  3985. ExprResult Arg = DefaultVariadicArgumentPromotion(
  3986. TheCall->getArg(i), VariadicFunction, nullptr);
  3987. if (Arg.isInvalid())
  3988. return true;
  3989. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  3990. if (ArgSize.getQuantity() >= 0x100) {
  3991. return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
  3992. << i << (int)ArgSize.getQuantity() << 0xff
  3993. << TheCall->getSourceRange();
  3994. }
  3995. TheCall->setArg(i, Arg.get());
  3996. i++;
  3997. }
  3998. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  3999. // call to avoid duplicate diagnostics.
  4000. if (!IsSizeCall) {
  4001. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  4002. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  4003. bool Success = CheckFormatArguments(
  4004. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  4005. VariadicFunction, TheCall->getLocStart(), SourceRange(),
  4006. CheckedVarArgs);
  4007. if (!Success)
  4008. return true;
  4009. }
  4010. if (IsSizeCall) {
  4011. TheCall->setType(Context.getSizeType());
  4012. } else {
  4013. TheCall->setType(Context.VoidPtrTy);
  4014. }
  4015. return false;
  4016. }
  4017. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  4018. /// TheCall is a constant expression.
  4019. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  4020. llvm::APSInt &Result) {
  4021. Expr *Arg = TheCall->getArg(ArgNum);
  4022. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4023. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4024. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  4025. if (!Arg->isIntegerConstantExpr(Result, Context))
  4026. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  4027. << FDecl->getDeclName() << Arg->getSourceRange();
  4028. return false;
  4029. }
  4030. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  4031. /// TheCall is a constant expression in the range [Low, High].
  4032. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  4033. int Low, int High) {
  4034. llvm::APSInt Result;
  4035. // We can't check the value of a dependent argument.
  4036. Expr *Arg = TheCall->getArg(ArgNum);
  4037. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4038. return false;
  4039. // Check constant-ness first.
  4040. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4041. return true;
  4042. if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
  4043. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  4044. << Low << High << Arg->getSourceRange();
  4045. return false;
  4046. }
  4047. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  4048. /// TheCall is a constant expression is a multiple of Num..
  4049. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  4050. unsigned Num) {
  4051. llvm::APSInt Result;
  4052. // We can't check the value of a dependent argument.
  4053. Expr *Arg = TheCall->getArg(ArgNum);
  4054. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4055. return false;
  4056. // Check constant-ness first.
  4057. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4058. return true;
  4059. if (Result.getSExtValue() % Num != 0)
  4060. return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
  4061. << Num << Arg->getSourceRange();
  4062. return false;
  4063. }
  4064. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  4065. /// TheCall is an ARM/AArch64 special register string literal.
  4066. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  4067. int ArgNum, unsigned ExpectedFieldNum,
  4068. bool AllowName) {
  4069. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  4070. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  4071. BuiltinID == ARM::BI__builtin_arm_rsr ||
  4072. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  4073. BuiltinID == ARM::BI__builtin_arm_wsr ||
  4074. BuiltinID == ARM::BI__builtin_arm_wsrp;
  4075. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  4076. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  4077. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  4078. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  4079. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  4080. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  4081. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  4082. // We can't check the value of a dependent argument.
  4083. Expr *Arg = TheCall->getArg(ArgNum);
  4084. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4085. return false;
  4086. // Check if the argument is a string literal.
  4087. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  4088. return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  4089. << Arg->getSourceRange();
  4090. // Check the type of special register given.
  4091. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  4092. SmallVector<StringRef, 6> Fields;
  4093. Reg.split(Fields, ":");
  4094. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  4095. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  4096. << Arg->getSourceRange();
  4097. // If the string is the name of a register then we cannot check that it is
  4098. // valid here but if the string is of one the forms described in ACLE then we
  4099. // can check that the supplied fields are integers and within the valid
  4100. // ranges.
  4101. if (Fields.size() > 1) {
  4102. bool FiveFields = Fields.size() == 5;
  4103. bool ValidString = true;
  4104. if (IsARMBuiltin) {
  4105. ValidString &= Fields[0].startswith_lower("cp") ||
  4106. Fields[0].startswith_lower("p");
  4107. if (ValidString)
  4108. Fields[0] =
  4109. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  4110. ValidString &= Fields[2].startswith_lower("c");
  4111. if (ValidString)
  4112. Fields[2] = Fields[2].drop_front(1);
  4113. if (FiveFields) {
  4114. ValidString &= Fields[3].startswith_lower("c");
  4115. if (ValidString)
  4116. Fields[3] = Fields[3].drop_front(1);
  4117. }
  4118. }
  4119. SmallVector<int, 5> Ranges;
  4120. if (FiveFields)
  4121. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  4122. else
  4123. Ranges.append({15, 7, 15});
  4124. for (unsigned i=0; i<Fields.size(); ++i) {
  4125. int IntField;
  4126. ValidString &= !Fields[i].getAsInteger(10, IntField);
  4127. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  4128. }
  4129. if (!ValidString)
  4130. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  4131. << Arg->getSourceRange();
  4132. } else if (IsAArch64Builtin && Fields.size() == 1) {
  4133. // If the register name is one of those that appear in the condition below
  4134. // and the special register builtin being used is one of the write builtins,
  4135. // then we require that the argument provided for writing to the register
  4136. // is an integer constant expression. This is because it will be lowered to
  4137. // an MSR (immediate) instruction, so we need to know the immediate at
  4138. // compile time.
  4139. if (TheCall->getNumArgs() != 2)
  4140. return false;
  4141. std::string RegLower = Reg.lower();
  4142. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  4143. RegLower != "pan" && RegLower != "uao")
  4144. return false;
  4145. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  4146. }
  4147. return false;
  4148. }
  4149. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  4150. /// This checks that the target supports __builtin_longjmp and
  4151. /// that val is a constant 1.
  4152. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  4153. if (!Context.getTargetInfo().hasSjLjLowering())
  4154. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
  4155. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  4156. Expr *Arg = TheCall->getArg(1);
  4157. llvm::APSInt Result;
  4158. // TODO: This is less than ideal. Overload this to take a value.
  4159. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  4160. return true;
  4161. if (Result != 1)
  4162. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  4163. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  4164. return false;
  4165. }
  4166. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  4167. /// This checks that the target supports __builtin_setjmp.
  4168. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  4169. if (!Context.getTargetInfo().hasSjLjLowering())
  4170. return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
  4171. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  4172. return false;
  4173. }
  4174. namespace {
  4175. class UncoveredArgHandler {
  4176. enum { Unknown = -1, AllCovered = -2 };
  4177. signed FirstUncoveredArg;
  4178. SmallVector<const Expr *, 4> DiagnosticExprs;
  4179. public:
  4180. UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
  4181. bool hasUncoveredArg() const {
  4182. return (FirstUncoveredArg >= 0);
  4183. }
  4184. unsigned getUncoveredArg() const {
  4185. assert(hasUncoveredArg() && "no uncovered argument");
  4186. return FirstUncoveredArg;
  4187. }
  4188. void setAllCovered() {
  4189. // A string has been found with all arguments covered, so clear out
  4190. // the diagnostics.
  4191. DiagnosticExprs.clear();
  4192. FirstUncoveredArg = AllCovered;
  4193. }
  4194. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  4195. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  4196. // Don't update if a previous string covers all arguments.
  4197. if (FirstUncoveredArg == AllCovered)
  4198. return;
  4199. // UncoveredArgHandler tracks the highest uncovered argument index
  4200. // and with it all the strings that match this index.
  4201. if (NewFirstUncoveredArg == FirstUncoveredArg)
  4202. DiagnosticExprs.push_back(StrExpr);
  4203. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  4204. DiagnosticExprs.clear();
  4205. DiagnosticExprs.push_back(StrExpr);
  4206. FirstUncoveredArg = NewFirstUncoveredArg;
  4207. }
  4208. }
  4209. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  4210. };
  4211. enum StringLiteralCheckType {
  4212. SLCT_NotALiteral,
  4213. SLCT_UncheckedLiteral,
  4214. SLCT_CheckedLiteral
  4215. };
  4216. } // end anonymous namespace
  4217. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  4218. BinaryOperatorKind BinOpKind,
  4219. bool AddendIsRight) {
  4220. unsigned BitWidth = Offset.getBitWidth();
  4221. unsigned AddendBitWidth = Addend.getBitWidth();
  4222. // There might be negative interim results.
  4223. if (Addend.isUnsigned()) {
  4224. Addend = Addend.zext(++AddendBitWidth);
  4225. Addend.setIsSigned(true);
  4226. }
  4227. // Adjust the bit width of the APSInts.
  4228. if (AddendBitWidth > BitWidth) {
  4229. Offset = Offset.sext(AddendBitWidth);
  4230. BitWidth = AddendBitWidth;
  4231. } else if (BitWidth > AddendBitWidth) {
  4232. Addend = Addend.sext(BitWidth);
  4233. }
  4234. bool Ov = false;
  4235. llvm::APSInt ResOffset = Offset;
  4236. if (BinOpKind == BO_Add)
  4237. ResOffset = Offset.sadd_ov(Addend, Ov);
  4238. else {
  4239. assert(AddendIsRight && BinOpKind == BO_Sub &&
  4240. "operator must be add or sub with addend on the right");
  4241. ResOffset = Offset.ssub_ov(Addend, Ov);
  4242. }
  4243. // We add an offset to a pointer here so we should support an offset as big as
  4244. // possible.
  4245. if (Ov) {
  4246. assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
  4247. Offset = Offset.sext(2 * BitWidth);
  4248. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  4249. return;
  4250. }
  4251. Offset = ResOffset;
  4252. }
  4253. namespace {
  4254. // This is a wrapper class around StringLiteral to support offsetted string
  4255. // literals as format strings. It takes the offset into account when returning
  4256. // the string and its length or the source locations to display notes correctly.
  4257. class FormatStringLiteral {
  4258. const StringLiteral *FExpr;
  4259. int64_t Offset;
  4260. public:
  4261. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  4262. : FExpr(fexpr), Offset(Offset) {}
  4263. StringRef getString() const {
  4264. return FExpr->getString().drop_front(Offset);
  4265. }
  4266. unsigned getByteLength() const {
  4267. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  4268. }
  4269. unsigned getLength() const { return FExpr->getLength() - Offset; }
  4270. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  4271. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  4272. QualType getType() const { return FExpr->getType(); }
  4273. bool isAscii() const { return FExpr->isAscii(); }
  4274. bool isWide() const { return FExpr->isWide(); }
  4275. bool isUTF8() const { return FExpr->isUTF8(); }
  4276. bool isUTF16() const { return FExpr->isUTF16(); }
  4277. bool isUTF32() const { return FExpr->isUTF32(); }
  4278. bool isPascal() const { return FExpr->isPascal(); }
  4279. SourceLocation getLocationOfByte(
  4280. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  4281. const TargetInfo &Target, unsigned *StartToken = nullptr,
  4282. unsigned *StartTokenByteOffset = nullptr) const {
  4283. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  4284. StartToken, StartTokenByteOffset);
  4285. }
  4286. SourceLocation getLocStart() const LLVM_READONLY {
  4287. return FExpr->getLocStart().getLocWithOffset(Offset);
  4288. }
  4289. SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
  4290. };
  4291. } // end anonymous namespace
  4292. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  4293. const Expr *OrigFormatExpr,
  4294. ArrayRef<const Expr *> Args,
  4295. bool HasVAListArg, unsigned format_idx,
  4296. unsigned firstDataArg,
  4297. Sema::FormatStringType Type,
  4298. bool inFunctionCall,
  4299. Sema::VariadicCallType CallType,
  4300. llvm::SmallBitVector &CheckedVarArgs,
  4301. UncoveredArgHandler &UncoveredArg);
  4302. // Determine if an expression is a string literal or constant string.
  4303. // If this function returns false on the arguments to a function expecting a
  4304. // format string, we will usually need to emit a warning.
  4305. // True string literals are then checked by CheckFormatString.
  4306. static StringLiteralCheckType
  4307. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  4308. bool HasVAListArg, unsigned format_idx,
  4309. unsigned firstDataArg, Sema::FormatStringType Type,
  4310. Sema::VariadicCallType CallType, bool InFunctionCall,
  4311. llvm::SmallBitVector &CheckedVarArgs,
  4312. UncoveredArgHandler &UncoveredArg,
  4313. llvm::APSInt Offset) {
  4314. tryAgain:
  4315. assert(Offset.isSigned() && "invalid offset");
  4316. if (E->isTypeDependent() || E->isValueDependent())
  4317. return SLCT_NotALiteral;
  4318. E = E->IgnoreParenCasts();
  4319. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  4320. // Technically -Wformat-nonliteral does not warn about this case.
  4321. // The behavior of printf and friends in this case is implementation
  4322. // dependent. Ideally if the format string cannot be null then
  4323. // it should have a 'nonnull' attribute in the function prototype.
  4324. return SLCT_UncheckedLiteral;
  4325. switch (E->getStmtClass()) {
  4326. case Stmt::BinaryConditionalOperatorClass:
  4327. case Stmt::ConditionalOperatorClass: {
  4328. // The expression is a literal if both sub-expressions were, and it was
  4329. // completely checked only if both sub-expressions were checked.
  4330. const AbstractConditionalOperator *C =
  4331. cast<AbstractConditionalOperator>(E);
  4332. // Determine whether it is necessary to check both sub-expressions, for
  4333. // example, because the condition expression is a constant that can be
  4334. // evaluated at compile time.
  4335. bool CheckLeft = true, CheckRight = true;
  4336. bool Cond;
  4337. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
  4338. if (Cond)
  4339. CheckRight = false;
  4340. else
  4341. CheckLeft = false;
  4342. }
  4343. // We need to maintain the offsets for the right and the left hand side
  4344. // separately to check if every possible indexed expression is a valid
  4345. // string literal. They might have different offsets for different string
  4346. // literals in the end.
  4347. StringLiteralCheckType Left;
  4348. if (!CheckLeft)
  4349. Left = SLCT_UncheckedLiteral;
  4350. else {
  4351. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  4352. HasVAListArg, format_idx, firstDataArg,
  4353. Type, CallType, InFunctionCall,
  4354. CheckedVarArgs, UncoveredArg, Offset);
  4355. if (Left == SLCT_NotALiteral || !CheckRight) {
  4356. return Left;
  4357. }
  4358. }
  4359. StringLiteralCheckType Right =
  4360. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  4361. HasVAListArg, format_idx, firstDataArg,
  4362. Type, CallType, InFunctionCall, CheckedVarArgs,
  4363. UncoveredArg, Offset);
  4364. return (CheckLeft && Left < Right) ? Left : Right;
  4365. }
  4366. case Stmt::ImplicitCastExprClass: {
  4367. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  4368. goto tryAgain;
  4369. }
  4370. case Stmt::OpaqueValueExprClass:
  4371. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  4372. E = src;
  4373. goto tryAgain;
  4374. }
  4375. return SLCT_NotALiteral;
  4376. case Stmt::PredefinedExprClass:
  4377. // While __func__, etc., are technically not string literals, they
  4378. // cannot contain format specifiers and thus are not a security
  4379. // liability.
  4380. return SLCT_UncheckedLiteral;
  4381. case Stmt::DeclRefExprClass: {
  4382. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  4383. // As an exception, do not flag errors for variables binding to
  4384. // const string literals.
  4385. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  4386. bool isConstant = false;
  4387. QualType T = DR->getType();
  4388. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  4389. isConstant = AT->getElementType().isConstant(S.Context);
  4390. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  4391. isConstant = T.isConstant(S.Context) &&
  4392. PT->getPointeeType().isConstant(S.Context);
  4393. } else if (T->isObjCObjectPointerType()) {
  4394. // In ObjC, there is usually no "const ObjectPointer" type,
  4395. // so don't check if the pointee type is constant.
  4396. isConstant = T.isConstant(S.Context);
  4397. }
  4398. if (isConstant) {
  4399. if (const Expr *Init = VD->getAnyInitializer()) {
  4400. // Look through initializers like const char c[] = { "foo" }
  4401. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  4402. if (InitList->isStringLiteralInit())
  4403. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  4404. }
  4405. return checkFormatStringExpr(S, Init, Args,
  4406. HasVAListArg, format_idx,
  4407. firstDataArg, Type, CallType,
  4408. /*InFunctionCall*/ false, CheckedVarArgs,
  4409. UncoveredArg, Offset);
  4410. }
  4411. }
  4412. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  4413. // special check to see if the format string is a function parameter
  4414. // of the function calling the printf function. If the function
  4415. // has an attribute indicating it is a printf-like function, then we
  4416. // should suppress warnings concerning non-literals being used in a call
  4417. // to a vprintf function. For example:
  4418. //
  4419. // void
  4420. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  4421. // va_list ap;
  4422. // va_start(ap, fmt);
  4423. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  4424. // ...
  4425. // }
  4426. if (HasVAListArg) {
  4427. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  4428. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  4429. int PVIndex = PV->getFunctionScopeIndex() + 1;
  4430. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  4431. // adjust for implicit parameter
  4432. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  4433. if (MD->isInstance())
  4434. ++PVIndex;
  4435. // We also check if the formats are compatible.
  4436. // We can't pass a 'scanf' string to a 'printf' function.
  4437. if (PVIndex == PVFormat->getFormatIdx() &&
  4438. Type == S.GetFormatStringType(PVFormat))
  4439. return SLCT_UncheckedLiteral;
  4440. }
  4441. }
  4442. }
  4443. }
  4444. }
  4445. return SLCT_NotALiteral;
  4446. }
  4447. case Stmt::CallExprClass:
  4448. case Stmt::CXXMemberCallExprClass: {
  4449. const CallExpr *CE = cast<CallExpr>(E);
  4450. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  4451. if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
  4452. unsigned ArgIndex = FA->getFormatIdx();
  4453. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  4454. if (MD->isInstance())
  4455. --ArgIndex;
  4456. const Expr *Arg = CE->getArg(ArgIndex - 1);
  4457. return checkFormatStringExpr(S, Arg, Args,
  4458. HasVAListArg, format_idx, firstDataArg,
  4459. Type, CallType, InFunctionCall,
  4460. CheckedVarArgs, UncoveredArg, Offset);
  4461. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  4462. unsigned BuiltinID = FD->getBuiltinID();
  4463. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  4464. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  4465. const Expr *Arg = CE->getArg(0);
  4466. return checkFormatStringExpr(S, Arg, Args,
  4467. HasVAListArg, format_idx,
  4468. firstDataArg, Type, CallType,
  4469. InFunctionCall, CheckedVarArgs,
  4470. UncoveredArg, Offset);
  4471. }
  4472. }
  4473. }
  4474. return SLCT_NotALiteral;
  4475. }
  4476. case Stmt::ObjCMessageExprClass: {
  4477. const auto *ME = cast<ObjCMessageExpr>(E);
  4478. if (const auto *ND = ME->getMethodDecl()) {
  4479. if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
  4480. unsigned ArgIndex = FA->getFormatIdx();
  4481. const Expr *Arg = ME->getArg(ArgIndex - 1);
  4482. return checkFormatStringExpr(
  4483. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  4484. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  4485. }
  4486. }
  4487. return SLCT_NotALiteral;
  4488. }
  4489. case Stmt::ObjCStringLiteralClass:
  4490. case Stmt::StringLiteralClass: {
  4491. const StringLiteral *StrE = nullptr;
  4492. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  4493. StrE = ObjCFExpr->getString();
  4494. else
  4495. StrE = cast<StringLiteral>(E);
  4496. if (StrE) {
  4497. if (Offset.isNegative() || Offset > StrE->getLength()) {
  4498. // TODO: It would be better to have an explicit warning for out of
  4499. // bounds literals.
  4500. return SLCT_NotALiteral;
  4501. }
  4502. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  4503. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  4504. firstDataArg, Type, InFunctionCall, CallType,
  4505. CheckedVarArgs, UncoveredArg);
  4506. return SLCT_CheckedLiteral;
  4507. }
  4508. return SLCT_NotALiteral;
  4509. }
  4510. case Stmt::BinaryOperatorClass: {
  4511. llvm::APSInt LResult;
  4512. llvm::APSInt RResult;
  4513. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  4514. // A string literal + an int offset is still a string literal.
  4515. if (BinOp->isAdditiveOp()) {
  4516. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
  4517. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
  4518. if (LIsInt != RIsInt) {
  4519. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  4520. if (LIsInt) {
  4521. if (BinOpKind == BO_Add) {
  4522. sumOffsets(Offset, LResult, BinOpKind, RIsInt);
  4523. E = BinOp->getRHS();
  4524. goto tryAgain;
  4525. }
  4526. } else {
  4527. sumOffsets(Offset, RResult, BinOpKind, RIsInt);
  4528. E = BinOp->getLHS();
  4529. goto tryAgain;
  4530. }
  4531. }
  4532. }
  4533. return SLCT_NotALiteral;
  4534. }
  4535. case Stmt::UnaryOperatorClass: {
  4536. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  4537. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  4538. if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
  4539. llvm::APSInt IndexResult;
  4540. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
  4541. sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
  4542. E = ASE->getBase();
  4543. goto tryAgain;
  4544. }
  4545. }
  4546. return SLCT_NotALiteral;
  4547. }
  4548. default:
  4549. return SLCT_NotALiteral;
  4550. }
  4551. }
  4552. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  4553. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  4554. .Case("scanf", FST_Scanf)
  4555. .Cases("printf", "printf0", FST_Printf)
  4556. .Cases("NSString", "CFString", FST_NSString)
  4557. .Case("strftime", FST_Strftime)
  4558. .Case("strfmon", FST_Strfmon)
  4559. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  4560. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  4561. .Case("os_trace", FST_OSLog)
  4562. .Case("os_log", FST_OSLog)
  4563. .Default(FST_Unknown);
  4564. }
  4565. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  4566. /// functions) for correct use of format strings.
  4567. /// Returns true if a format string has been fully checked.
  4568. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  4569. ArrayRef<const Expr *> Args,
  4570. bool IsCXXMember,
  4571. VariadicCallType CallType,
  4572. SourceLocation Loc, SourceRange Range,
  4573. llvm::SmallBitVector &CheckedVarArgs) {
  4574. FormatStringInfo FSI;
  4575. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  4576. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  4577. FSI.FirstDataArg, GetFormatStringType(Format),
  4578. CallType, Loc, Range, CheckedVarArgs);
  4579. return false;
  4580. }
  4581. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  4582. bool HasVAListArg, unsigned format_idx,
  4583. unsigned firstDataArg, FormatStringType Type,
  4584. VariadicCallType CallType,
  4585. SourceLocation Loc, SourceRange Range,
  4586. llvm::SmallBitVector &CheckedVarArgs) {
  4587. // CHECK: printf/scanf-like function is called with no format string.
  4588. if (format_idx >= Args.size()) {
  4589. Diag(Loc, diag::warn_missing_format_string) << Range;
  4590. return false;
  4591. }
  4592. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  4593. // CHECK: format string is not a string literal.
  4594. //
  4595. // Dynamically generated format strings are difficult to
  4596. // automatically vet at compile time. Requiring that format strings
  4597. // are string literals: (1) permits the checking of format strings by
  4598. // the compiler and thereby (2) can practically remove the source of
  4599. // many format string exploits.
  4600. // Format string can be either ObjC string (e.g. @"%d") or
  4601. // C string (e.g. "%d")
  4602. // ObjC string uses the same format specifiers as C string, so we can use
  4603. // the same format string checking logic for both ObjC and C strings.
  4604. UncoveredArgHandler UncoveredArg;
  4605. StringLiteralCheckType CT =
  4606. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  4607. format_idx, firstDataArg, Type, CallType,
  4608. /*IsFunctionCall*/ true, CheckedVarArgs,
  4609. UncoveredArg,
  4610. /*no string offset*/ llvm::APSInt(64, false) = 0);
  4611. // Generate a diagnostic where an uncovered argument is detected.
  4612. if (UncoveredArg.hasUncoveredArg()) {
  4613. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  4614. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  4615. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  4616. }
  4617. if (CT != SLCT_NotALiteral)
  4618. // Literal format string found, check done!
  4619. return CT == SLCT_CheckedLiteral;
  4620. // Strftime is particular as it always uses a single 'time' argument,
  4621. // so it is safe to pass a non-literal string.
  4622. if (Type == FST_Strftime)
  4623. return false;
  4624. // Do not emit diag when the string param is a macro expansion and the
  4625. // format is either NSString or CFString. This is a hack to prevent
  4626. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  4627. // which are usually used in place of NS and CF string literals.
  4628. SourceLocation FormatLoc = Args[format_idx]->getLocStart();
  4629. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  4630. return false;
  4631. // If there are no arguments specified, warn with -Wformat-security, otherwise
  4632. // warn only with -Wformat-nonliteral.
  4633. if (Args.size() == firstDataArg) {
  4634. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  4635. << OrigFormatExpr->getSourceRange();
  4636. switch (Type) {
  4637. default:
  4638. break;
  4639. case FST_Kprintf:
  4640. case FST_FreeBSDKPrintf:
  4641. case FST_Printf:
  4642. Diag(FormatLoc, diag::note_format_security_fixit)
  4643. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  4644. break;
  4645. case FST_NSString:
  4646. Diag(FormatLoc, diag::note_format_security_fixit)
  4647. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  4648. break;
  4649. }
  4650. } else {
  4651. Diag(FormatLoc, diag::warn_format_nonliteral)
  4652. << OrigFormatExpr->getSourceRange();
  4653. }
  4654. return false;
  4655. }
  4656. namespace {
  4657. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  4658. protected:
  4659. Sema &S;
  4660. const FormatStringLiteral *FExpr;
  4661. const Expr *OrigFormatExpr;
  4662. const Sema::FormatStringType FSType;
  4663. const unsigned FirstDataArg;
  4664. const unsigned NumDataArgs;
  4665. const char *Beg; // Start of format string.
  4666. const bool HasVAListArg;
  4667. ArrayRef<const Expr *> Args;
  4668. unsigned FormatIdx;
  4669. llvm::SmallBitVector CoveredArgs;
  4670. bool usesPositionalArgs;
  4671. bool atFirstArg;
  4672. bool inFunctionCall;
  4673. Sema::VariadicCallType CallType;
  4674. llvm::SmallBitVector &CheckedVarArgs;
  4675. UncoveredArgHandler &UncoveredArg;
  4676. public:
  4677. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  4678. const Expr *origFormatExpr,
  4679. const Sema::FormatStringType type, unsigned firstDataArg,
  4680. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  4681. ArrayRef<const Expr *> Args, unsigned formatIdx,
  4682. bool inFunctionCall, Sema::VariadicCallType callType,
  4683. llvm::SmallBitVector &CheckedVarArgs,
  4684. UncoveredArgHandler &UncoveredArg)
  4685. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  4686. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  4687. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  4688. usesPositionalArgs(false), atFirstArg(true),
  4689. inFunctionCall(inFunctionCall), CallType(callType),
  4690. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  4691. CoveredArgs.resize(numDataArgs);
  4692. CoveredArgs.reset();
  4693. }
  4694. void DoneProcessing();
  4695. void HandleIncompleteSpecifier(const char *startSpecifier,
  4696. unsigned specifierLen) override;
  4697. void HandleInvalidLengthModifier(
  4698. const analyze_format_string::FormatSpecifier &FS,
  4699. const analyze_format_string::ConversionSpecifier &CS,
  4700. const char *startSpecifier, unsigned specifierLen,
  4701. unsigned DiagID);
  4702. void HandleNonStandardLengthModifier(
  4703. const analyze_format_string::FormatSpecifier &FS,
  4704. const char *startSpecifier, unsigned specifierLen);
  4705. void HandleNonStandardConversionSpecifier(
  4706. const analyze_format_string::ConversionSpecifier &CS,
  4707. const char *startSpecifier, unsigned specifierLen);
  4708. void HandlePosition(const char *startPos, unsigned posLen) override;
  4709. void HandleInvalidPosition(const char *startSpecifier,
  4710. unsigned specifierLen,
  4711. analyze_format_string::PositionContext p) override;
  4712. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  4713. void HandleNullChar(const char *nullCharacter) override;
  4714. template <typename Range>
  4715. static void
  4716. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  4717. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  4718. bool IsStringLocation, Range StringRange,
  4719. ArrayRef<FixItHint> Fixit = None);
  4720. protected:
  4721. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  4722. const char *startSpec,
  4723. unsigned specifierLen,
  4724. const char *csStart, unsigned csLen);
  4725. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  4726. const char *startSpec,
  4727. unsigned specifierLen);
  4728. SourceRange getFormatStringRange();
  4729. CharSourceRange getSpecifierRange(const char *startSpecifier,
  4730. unsigned specifierLen);
  4731. SourceLocation getLocationOfByte(const char *x);
  4732. const Expr *getDataArg(unsigned i) const;
  4733. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  4734. const analyze_format_string::ConversionSpecifier &CS,
  4735. const char *startSpecifier, unsigned specifierLen,
  4736. unsigned argIndex);
  4737. template <typename Range>
  4738. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  4739. bool IsStringLocation, Range StringRange,
  4740. ArrayRef<FixItHint> Fixit = None);
  4741. };
  4742. } // end anonymous namespace
  4743. SourceRange CheckFormatHandler::getFormatStringRange() {
  4744. return OrigFormatExpr->getSourceRange();
  4745. }
  4746. CharSourceRange CheckFormatHandler::
  4747. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  4748. SourceLocation Start = getLocationOfByte(startSpecifier);
  4749. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  4750. // Advance the end SourceLocation by one due to half-open ranges.
  4751. End = End.getLocWithOffset(1);
  4752. return CharSourceRange::getCharRange(Start, End);
  4753. }
  4754. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  4755. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  4756. S.getLangOpts(), S.Context.getTargetInfo());
  4757. }
  4758. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  4759. unsigned specifierLen){
  4760. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  4761. getLocationOfByte(startSpecifier),
  4762. /*IsStringLocation*/true,
  4763. getSpecifierRange(startSpecifier, specifierLen));
  4764. }
  4765. void CheckFormatHandler::HandleInvalidLengthModifier(
  4766. const analyze_format_string::FormatSpecifier &FS,
  4767. const analyze_format_string::ConversionSpecifier &CS,
  4768. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  4769. using namespace analyze_format_string;
  4770. const LengthModifier &LM = FS.getLengthModifier();
  4771. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  4772. // See if we know how to fix this length modifier.
  4773. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  4774. if (FixedLM) {
  4775. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  4776. getLocationOfByte(LM.getStart()),
  4777. /*IsStringLocation*/true,
  4778. getSpecifierRange(startSpecifier, specifierLen));
  4779. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  4780. << FixedLM->toString()
  4781. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  4782. } else {
  4783. FixItHint Hint;
  4784. if (DiagID == diag::warn_format_nonsensical_length)
  4785. Hint = FixItHint::CreateRemoval(LMRange);
  4786. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  4787. getLocationOfByte(LM.getStart()),
  4788. /*IsStringLocation*/true,
  4789. getSpecifierRange(startSpecifier, specifierLen),
  4790. Hint);
  4791. }
  4792. }
  4793. void CheckFormatHandler::HandleNonStandardLengthModifier(
  4794. const analyze_format_string::FormatSpecifier &FS,
  4795. const char *startSpecifier, unsigned specifierLen) {
  4796. using namespace analyze_format_string;
  4797. const LengthModifier &LM = FS.getLengthModifier();
  4798. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  4799. // See if we know how to fix this length modifier.
  4800. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  4801. if (FixedLM) {
  4802. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4803. << LM.toString() << 0,
  4804. getLocationOfByte(LM.getStart()),
  4805. /*IsStringLocation*/true,
  4806. getSpecifierRange(startSpecifier, specifierLen));
  4807. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  4808. << FixedLM->toString()
  4809. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  4810. } else {
  4811. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4812. << LM.toString() << 0,
  4813. getLocationOfByte(LM.getStart()),
  4814. /*IsStringLocation*/true,
  4815. getSpecifierRange(startSpecifier, specifierLen));
  4816. }
  4817. }
  4818. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  4819. const analyze_format_string::ConversionSpecifier &CS,
  4820. const char *startSpecifier, unsigned specifierLen) {
  4821. using namespace analyze_format_string;
  4822. // See if we know how to fix this conversion specifier.
  4823. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  4824. if (FixedCS) {
  4825. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4826. << CS.toString() << /*conversion specifier*/1,
  4827. getLocationOfByte(CS.getStart()),
  4828. /*IsStringLocation*/true,
  4829. getSpecifierRange(startSpecifier, specifierLen));
  4830. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  4831. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  4832. << FixedCS->toString()
  4833. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  4834. } else {
  4835. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4836. << CS.toString() << /*conversion specifier*/1,
  4837. getLocationOfByte(CS.getStart()),
  4838. /*IsStringLocation*/true,
  4839. getSpecifierRange(startSpecifier, specifierLen));
  4840. }
  4841. }
  4842. void CheckFormatHandler::HandlePosition(const char *startPos,
  4843. unsigned posLen) {
  4844. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  4845. getLocationOfByte(startPos),
  4846. /*IsStringLocation*/true,
  4847. getSpecifierRange(startPos, posLen));
  4848. }
  4849. void
  4850. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  4851. analyze_format_string::PositionContext p) {
  4852. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  4853. << (unsigned) p,
  4854. getLocationOfByte(startPos), /*IsStringLocation*/true,
  4855. getSpecifierRange(startPos, posLen));
  4856. }
  4857. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  4858. unsigned posLen) {
  4859. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  4860. getLocationOfByte(startPos),
  4861. /*IsStringLocation*/true,
  4862. getSpecifierRange(startPos, posLen));
  4863. }
  4864. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  4865. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  4866. // The presence of a null character is likely an error.
  4867. EmitFormatDiagnostic(
  4868. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  4869. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  4870. getFormatStringRange());
  4871. }
  4872. }
  4873. // Note that this may return NULL if there was an error parsing or building
  4874. // one of the argument expressions.
  4875. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  4876. return Args[FirstDataArg + i];
  4877. }
  4878. void CheckFormatHandler::DoneProcessing() {
  4879. // Does the number of data arguments exceed the number of
  4880. // format conversions in the format string?
  4881. if (!HasVAListArg) {
  4882. // Find any arguments that weren't covered.
  4883. CoveredArgs.flip();
  4884. signed notCoveredArg = CoveredArgs.find_first();
  4885. if (notCoveredArg >= 0) {
  4886. assert((unsigned)notCoveredArg < NumDataArgs);
  4887. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  4888. } else {
  4889. UncoveredArg.setAllCovered();
  4890. }
  4891. }
  4892. }
  4893. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  4894. const Expr *ArgExpr) {
  4895. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  4896. "Invalid state");
  4897. if (!ArgExpr)
  4898. return;
  4899. SourceLocation Loc = ArgExpr->getLocStart();
  4900. if (S.getSourceManager().isInSystemMacro(Loc))
  4901. return;
  4902. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  4903. for (auto E : DiagnosticExprs)
  4904. PDiag << E->getSourceRange();
  4905. CheckFormatHandler::EmitFormatDiagnostic(
  4906. S, IsFunctionCall, DiagnosticExprs[0],
  4907. PDiag, Loc, /*IsStringLocation*/false,
  4908. DiagnosticExprs[0]->getSourceRange());
  4909. }
  4910. bool
  4911. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  4912. SourceLocation Loc,
  4913. const char *startSpec,
  4914. unsigned specifierLen,
  4915. const char *csStart,
  4916. unsigned csLen) {
  4917. bool keepGoing = true;
  4918. if (argIndex < NumDataArgs) {
  4919. // Consider the argument coverered, even though the specifier doesn't
  4920. // make sense.
  4921. CoveredArgs.set(argIndex);
  4922. }
  4923. else {
  4924. // If argIndex exceeds the number of data arguments we
  4925. // don't issue a warning because that is just a cascade of warnings (and
  4926. // they may have intended '%%' anyway). We don't want to continue processing
  4927. // the format string after this point, however, as we will like just get
  4928. // gibberish when trying to match arguments.
  4929. keepGoing = false;
  4930. }
  4931. StringRef Specifier(csStart, csLen);
  4932. // If the specifier in non-printable, it could be the first byte of a UTF-8
  4933. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  4934. // hex value.
  4935. std::string CodePointStr;
  4936. if (!llvm::sys::locale::isPrint(*csStart)) {
  4937. llvm::UTF32 CodePoint;
  4938. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  4939. const llvm::UTF8 *E =
  4940. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  4941. llvm::ConversionResult Result =
  4942. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  4943. if (Result != llvm::conversionOK) {
  4944. unsigned char FirstChar = *csStart;
  4945. CodePoint = (llvm::UTF32)FirstChar;
  4946. }
  4947. llvm::raw_string_ostream OS(CodePointStr);
  4948. if (CodePoint < 256)
  4949. OS << "\\x" << llvm::format("%02x", CodePoint);
  4950. else if (CodePoint <= 0xFFFF)
  4951. OS << "\\u" << llvm::format("%04x", CodePoint);
  4952. else
  4953. OS << "\\U" << llvm::format("%08x", CodePoint);
  4954. OS.flush();
  4955. Specifier = CodePointStr;
  4956. }
  4957. EmitFormatDiagnostic(
  4958. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  4959. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  4960. return keepGoing;
  4961. }
  4962. void
  4963. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  4964. const char *startSpec,
  4965. unsigned specifierLen) {
  4966. EmitFormatDiagnostic(
  4967. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  4968. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  4969. }
  4970. bool
  4971. CheckFormatHandler::CheckNumArgs(
  4972. const analyze_format_string::FormatSpecifier &FS,
  4973. const analyze_format_string::ConversionSpecifier &CS,
  4974. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  4975. if (argIndex >= NumDataArgs) {
  4976. PartialDiagnostic PDiag = FS.usesPositionalArg()
  4977. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  4978. << (argIndex+1) << NumDataArgs)
  4979. : S.PDiag(diag::warn_printf_insufficient_data_args);
  4980. EmitFormatDiagnostic(
  4981. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  4982. getSpecifierRange(startSpecifier, specifierLen));
  4983. // Since more arguments than conversion tokens are given, by extension
  4984. // all arguments are covered, so mark this as so.
  4985. UncoveredArg.setAllCovered();
  4986. return false;
  4987. }
  4988. return true;
  4989. }
  4990. template<typename Range>
  4991. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  4992. SourceLocation Loc,
  4993. bool IsStringLocation,
  4994. Range StringRange,
  4995. ArrayRef<FixItHint> FixIt) {
  4996. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  4997. Loc, IsStringLocation, StringRange, FixIt);
  4998. }
  4999. /// \brief If the format string is not within the funcion call, emit a note
  5000. /// so that the function call and string are in diagnostic messages.
  5001. ///
  5002. /// \param InFunctionCall if true, the format string is within the function
  5003. /// call and only one diagnostic message will be produced. Otherwise, an
  5004. /// extra note will be emitted pointing to location of the format string.
  5005. ///
  5006. /// \param ArgumentExpr the expression that is passed as the format string
  5007. /// argument in the function call. Used for getting locations when two
  5008. /// diagnostics are emitted.
  5009. ///
  5010. /// \param PDiag the callee should already have provided any strings for the
  5011. /// diagnostic message. This function only adds locations and fixits
  5012. /// to diagnostics.
  5013. ///
  5014. /// \param Loc primary location for diagnostic. If two diagnostics are
  5015. /// required, one will be at Loc and a new SourceLocation will be created for
  5016. /// the other one.
  5017. ///
  5018. /// \param IsStringLocation if true, Loc points to the format string should be
  5019. /// used for the note. Otherwise, Loc points to the argument list and will
  5020. /// be used with PDiag.
  5021. ///
  5022. /// \param StringRange some or all of the string to highlight. This is
  5023. /// templated so it can accept either a CharSourceRange or a SourceRange.
  5024. ///
  5025. /// \param FixIt optional fix it hint for the format string.
  5026. template <typename Range>
  5027. void CheckFormatHandler::EmitFormatDiagnostic(
  5028. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  5029. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  5030. Range StringRange, ArrayRef<FixItHint> FixIt) {
  5031. if (InFunctionCall) {
  5032. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  5033. D << StringRange;
  5034. D << FixIt;
  5035. } else {
  5036. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  5037. << ArgumentExpr->getSourceRange();
  5038. const Sema::SemaDiagnosticBuilder &Note =
  5039. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  5040. diag::note_format_string_defined);
  5041. Note << StringRange;
  5042. Note << FixIt;
  5043. }
  5044. }
  5045. //===--- CHECK: Printf format string checking ------------------------------===//
  5046. namespace {
  5047. class CheckPrintfHandler : public CheckFormatHandler {
  5048. public:
  5049. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  5050. const Expr *origFormatExpr,
  5051. const Sema::FormatStringType type, unsigned firstDataArg,
  5052. unsigned numDataArgs, bool isObjC, const char *beg,
  5053. bool hasVAListArg, ArrayRef<const Expr *> Args,
  5054. unsigned formatIdx, bool inFunctionCall,
  5055. Sema::VariadicCallType CallType,
  5056. llvm::SmallBitVector &CheckedVarArgs,
  5057. UncoveredArgHandler &UncoveredArg)
  5058. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  5059. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  5060. inFunctionCall, CallType, CheckedVarArgs,
  5061. UncoveredArg) {}
  5062. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  5063. /// Returns true if '%@' specifiers are allowed in the format string.
  5064. bool allowsObjCArg() const {
  5065. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  5066. FSType == Sema::FST_OSTrace;
  5067. }
  5068. bool HandleInvalidPrintfConversionSpecifier(
  5069. const analyze_printf::PrintfSpecifier &FS,
  5070. const char *startSpecifier,
  5071. unsigned specifierLen) override;
  5072. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  5073. const char *startSpecifier,
  5074. unsigned specifierLen) override;
  5075. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  5076. const char *StartSpecifier,
  5077. unsigned SpecifierLen,
  5078. const Expr *E);
  5079. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  5080. const char *startSpecifier, unsigned specifierLen);
  5081. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  5082. const analyze_printf::OptionalAmount &Amt,
  5083. unsigned type,
  5084. const char *startSpecifier, unsigned specifierLen);
  5085. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  5086. const analyze_printf::OptionalFlag &flag,
  5087. const char *startSpecifier, unsigned specifierLen);
  5088. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  5089. const analyze_printf::OptionalFlag &ignoredFlag,
  5090. const analyze_printf::OptionalFlag &flag,
  5091. const char *startSpecifier, unsigned specifierLen);
  5092. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  5093. const Expr *E);
  5094. void HandleEmptyObjCModifierFlag(const char *startFlag,
  5095. unsigned flagLen) override;
  5096. void HandleInvalidObjCModifierFlag(const char *startFlag,
  5097. unsigned flagLen) override;
  5098. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  5099. const char *flagsEnd,
  5100. const char *conversionPosition)
  5101. override;
  5102. };
  5103. } // end anonymous namespace
  5104. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  5105. const analyze_printf::PrintfSpecifier &FS,
  5106. const char *startSpecifier,
  5107. unsigned specifierLen) {
  5108. const analyze_printf::PrintfConversionSpecifier &CS =
  5109. FS.getConversionSpecifier();
  5110. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  5111. getLocationOfByte(CS.getStart()),
  5112. startSpecifier, specifierLen,
  5113. CS.getStart(), CS.getLength());
  5114. }
  5115. bool CheckPrintfHandler::HandleAmount(
  5116. const analyze_format_string::OptionalAmount &Amt,
  5117. unsigned k, const char *startSpecifier,
  5118. unsigned specifierLen) {
  5119. if (Amt.hasDataArgument()) {
  5120. if (!HasVAListArg) {
  5121. unsigned argIndex = Amt.getArgIndex();
  5122. if (argIndex >= NumDataArgs) {
  5123. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  5124. << k,
  5125. getLocationOfByte(Amt.getStart()),
  5126. /*IsStringLocation*/true,
  5127. getSpecifierRange(startSpecifier, specifierLen));
  5128. // Don't do any more checking. We will just emit
  5129. // spurious errors.
  5130. return false;
  5131. }
  5132. // Type check the data argument. It should be an 'int'.
  5133. // Although not in conformance with C99, we also allow the argument to be
  5134. // an 'unsigned int' as that is a reasonably safe case. GCC also
  5135. // doesn't emit a warning for that case.
  5136. CoveredArgs.set(argIndex);
  5137. const Expr *Arg = getDataArg(argIndex);
  5138. if (!Arg)
  5139. return false;
  5140. QualType T = Arg->getType();
  5141. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  5142. assert(AT.isValid());
  5143. if (!AT.matchesType(S.Context, T)) {
  5144. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  5145. << k << AT.getRepresentativeTypeName(S.Context)
  5146. << T << Arg->getSourceRange(),
  5147. getLocationOfByte(Amt.getStart()),
  5148. /*IsStringLocation*/true,
  5149. getSpecifierRange(startSpecifier, specifierLen));
  5150. // Don't do any more checking. We will just emit
  5151. // spurious errors.
  5152. return false;
  5153. }
  5154. }
  5155. }
  5156. return true;
  5157. }
  5158. void CheckPrintfHandler::HandleInvalidAmount(
  5159. const analyze_printf::PrintfSpecifier &FS,
  5160. const analyze_printf::OptionalAmount &Amt,
  5161. unsigned type,
  5162. const char *startSpecifier,
  5163. unsigned specifierLen) {
  5164. const analyze_printf::PrintfConversionSpecifier &CS =
  5165. FS.getConversionSpecifier();
  5166. FixItHint fixit =
  5167. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  5168. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  5169. Amt.getConstantLength()))
  5170. : FixItHint();
  5171. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  5172. << type << CS.toString(),
  5173. getLocationOfByte(Amt.getStart()),
  5174. /*IsStringLocation*/true,
  5175. getSpecifierRange(startSpecifier, specifierLen),
  5176. fixit);
  5177. }
  5178. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  5179. const analyze_printf::OptionalFlag &flag,
  5180. const char *startSpecifier,
  5181. unsigned specifierLen) {
  5182. // Warn about pointless flag with a fixit removal.
  5183. const analyze_printf::PrintfConversionSpecifier &CS =
  5184. FS.getConversionSpecifier();
  5185. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  5186. << flag.toString() << CS.toString(),
  5187. getLocationOfByte(flag.getPosition()),
  5188. /*IsStringLocation*/true,
  5189. getSpecifierRange(startSpecifier, specifierLen),
  5190. FixItHint::CreateRemoval(
  5191. getSpecifierRange(flag.getPosition(), 1)));
  5192. }
  5193. void CheckPrintfHandler::HandleIgnoredFlag(
  5194. const analyze_printf::PrintfSpecifier &FS,
  5195. const analyze_printf::OptionalFlag &ignoredFlag,
  5196. const analyze_printf::OptionalFlag &flag,
  5197. const char *startSpecifier,
  5198. unsigned specifierLen) {
  5199. // Warn about ignored flag with a fixit removal.
  5200. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  5201. << ignoredFlag.toString() << flag.toString(),
  5202. getLocationOfByte(ignoredFlag.getPosition()),
  5203. /*IsStringLocation*/true,
  5204. getSpecifierRange(startSpecifier, specifierLen),
  5205. FixItHint::CreateRemoval(
  5206. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  5207. }
  5208. // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  5209. // bool IsStringLocation, Range StringRange,
  5210. // ArrayRef<FixItHint> Fixit = None);
  5211. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  5212. unsigned flagLen) {
  5213. // Warn about an empty flag.
  5214. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  5215. getLocationOfByte(startFlag),
  5216. /*IsStringLocation*/true,
  5217. getSpecifierRange(startFlag, flagLen));
  5218. }
  5219. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  5220. unsigned flagLen) {
  5221. // Warn about an invalid flag.
  5222. auto Range = getSpecifierRange(startFlag, flagLen);
  5223. StringRef flag(startFlag, flagLen);
  5224. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  5225. getLocationOfByte(startFlag),
  5226. /*IsStringLocation*/true,
  5227. Range, FixItHint::CreateRemoval(Range));
  5228. }
  5229. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  5230. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  5231. // Warn about using '[...]' without a '@' conversion.
  5232. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  5233. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  5234. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  5235. getLocationOfByte(conversionPosition),
  5236. /*IsStringLocation*/true,
  5237. Range, FixItHint::CreateRemoval(Range));
  5238. }
  5239. // Determines if the specified is a C++ class or struct containing
  5240. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  5241. // "c_str()").
  5242. template<typename MemberKind>
  5243. static llvm::SmallPtrSet<MemberKind*, 1>
  5244. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  5245. const RecordType *RT = Ty->getAs<RecordType>();
  5246. llvm::SmallPtrSet<MemberKind*, 1> Results;
  5247. if (!RT)
  5248. return Results;
  5249. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  5250. if (!RD || !RD->getDefinition())
  5251. return Results;
  5252. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  5253. Sema::LookupMemberName);
  5254. R.suppressDiagnostics();
  5255. // We just need to include all members of the right kind turned up by the
  5256. // filter, at this point.
  5257. if (S.LookupQualifiedName(R, RT->getDecl()))
  5258. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  5259. NamedDecl *decl = (*I)->getUnderlyingDecl();
  5260. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  5261. Results.insert(FK);
  5262. }
  5263. return Results;
  5264. }
  5265. /// Check if we could call '.c_str()' on an object.
  5266. ///
  5267. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  5268. /// allow the call, or if it would be ambiguous).
  5269. bool Sema::hasCStrMethod(const Expr *E) {
  5270. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  5271. MethodSet Results =
  5272. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  5273. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  5274. MI != ME; ++MI)
  5275. if ((*MI)->getMinRequiredArguments() == 0)
  5276. return true;
  5277. return false;
  5278. }
  5279. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  5280. // better diagnostic if so. AT is assumed to be valid.
  5281. // Returns true when a c_str() conversion method is found.
  5282. bool CheckPrintfHandler::checkForCStrMembers(
  5283. const analyze_printf::ArgType &AT, const Expr *E) {
  5284. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  5285. MethodSet Results =
  5286. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  5287. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  5288. MI != ME; ++MI) {
  5289. const CXXMethodDecl *Method = *MI;
  5290. if (Method->getMinRequiredArguments() == 0 &&
  5291. AT.matchesType(S.Context, Method->getReturnType())) {
  5292. // FIXME: Suggest parens if the expression needs them.
  5293. SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
  5294. S.Diag(E->getLocStart(), diag::note_printf_c_str)
  5295. << "c_str()"
  5296. << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  5297. return true;
  5298. }
  5299. }
  5300. return false;
  5301. }
  5302. bool
  5303. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  5304. &FS,
  5305. const char *startSpecifier,
  5306. unsigned specifierLen) {
  5307. using namespace analyze_format_string;
  5308. using namespace analyze_printf;
  5309. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  5310. if (FS.consumesDataArgument()) {
  5311. if (atFirstArg) {
  5312. atFirstArg = false;
  5313. usesPositionalArgs = FS.usesPositionalArg();
  5314. }
  5315. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  5316. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  5317. startSpecifier, specifierLen);
  5318. return false;
  5319. }
  5320. }
  5321. // First check if the field width, precision, and conversion specifier
  5322. // have matching data arguments.
  5323. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  5324. startSpecifier, specifierLen)) {
  5325. return false;
  5326. }
  5327. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  5328. startSpecifier, specifierLen)) {
  5329. return false;
  5330. }
  5331. if (!CS.consumesDataArgument()) {
  5332. // FIXME: Technically specifying a precision or field width here
  5333. // makes no sense. Worth issuing a warning at some point.
  5334. return true;
  5335. }
  5336. // Consume the argument.
  5337. unsigned argIndex = FS.getArgIndex();
  5338. if (argIndex < NumDataArgs) {
  5339. // The check to see if the argIndex is valid will come later.
  5340. // We set the bit here because we may exit early from this
  5341. // function if we encounter some other error.
  5342. CoveredArgs.set(argIndex);
  5343. }
  5344. // FreeBSD kernel extensions.
  5345. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  5346. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  5347. // We need at least two arguments.
  5348. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  5349. return false;
  5350. // Claim the second argument.
  5351. CoveredArgs.set(argIndex + 1);
  5352. // Type check the first argument (int for %b, pointer for %D)
  5353. const Expr *Ex = getDataArg(argIndex);
  5354. const analyze_printf::ArgType &AT =
  5355. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  5356. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  5357. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  5358. EmitFormatDiagnostic(
  5359. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  5360. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  5361. << false << Ex->getSourceRange(),
  5362. Ex->getLocStart(), /*IsStringLocation*/false,
  5363. getSpecifierRange(startSpecifier, specifierLen));
  5364. // Type check the second argument (char * for both %b and %D)
  5365. Ex = getDataArg(argIndex + 1);
  5366. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  5367. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  5368. EmitFormatDiagnostic(
  5369. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  5370. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  5371. << false << Ex->getSourceRange(),
  5372. Ex->getLocStart(), /*IsStringLocation*/false,
  5373. getSpecifierRange(startSpecifier, specifierLen));
  5374. return true;
  5375. }
  5376. // Check for using an Objective-C specific conversion specifier
  5377. // in a non-ObjC literal.
  5378. if (!allowsObjCArg() && CS.isObjCArg()) {
  5379. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  5380. specifierLen);
  5381. }
  5382. // %P can only be used with os_log.
  5383. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  5384. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  5385. specifierLen);
  5386. }
  5387. // %n is not allowed with os_log.
  5388. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  5389. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  5390. getLocationOfByte(CS.getStart()),
  5391. /*IsStringLocation*/ false,
  5392. getSpecifierRange(startSpecifier, specifierLen));
  5393. return true;
  5394. }
  5395. // Only scalars are allowed for os_trace.
  5396. if (FSType == Sema::FST_OSTrace &&
  5397. (CS.getKind() == ConversionSpecifier::PArg ||
  5398. CS.getKind() == ConversionSpecifier::sArg ||
  5399. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  5400. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  5401. specifierLen);
  5402. }
  5403. // Check for use of public/private annotation outside of os_log().
  5404. if (FSType != Sema::FST_OSLog) {
  5405. if (FS.isPublic().isSet()) {
  5406. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  5407. << "public",
  5408. getLocationOfByte(FS.isPublic().getPosition()),
  5409. /*IsStringLocation*/ false,
  5410. getSpecifierRange(startSpecifier, specifierLen));
  5411. }
  5412. if (FS.isPrivate().isSet()) {
  5413. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  5414. << "private",
  5415. getLocationOfByte(FS.isPrivate().getPosition()),
  5416. /*IsStringLocation*/ false,
  5417. getSpecifierRange(startSpecifier, specifierLen));
  5418. }
  5419. }
  5420. // Check for invalid use of field width
  5421. if (!FS.hasValidFieldWidth()) {
  5422. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  5423. startSpecifier, specifierLen);
  5424. }
  5425. // Check for invalid use of precision
  5426. if (!FS.hasValidPrecision()) {
  5427. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  5428. startSpecifier, specifierLen);
  5429. }
  5430. // Precision is mandatory for %P specifier.
  5431. if (CS.getKind() == ConversionSpecifier::PArg &&
  5432. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  5433. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  5434. getLocationOfByte(startSpecifier),
  5435. /*IsStringLocation*/ false,
  5436. getSpecifierRange(startSpecifier, specifierLen));
  5437. }
  5438. // Check each flag does not conflict with any other component.
  5439. if (!FS.hasValidThousandsGroupingPrefix())
  5440. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  5441. if (!FS.hasValidLeadingZeros())
  5442. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  5443. if (!FS.hasValidPlusPrefix())
  5444. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  5445. if (!FS.hasValidSpacePrefix())
  5446. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  5447. if (!FS.hasValidAlternativeForm())
  5448. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  5449. if (!FS.hasValidLeftJustified())
  5450. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  5451. // Check that flags are not ignored by another flag
  5452. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  5453. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  5454. startSpecifier, specifierLen);
  5455. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  5456. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  5457. startSpecifier, specifierLen);
  5458. // Check the length modifier is valid with the given conversion specifier.
  5459. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  5460. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5461. diag::warn_format_nonsensical_length);
  5462. else if (!FS.hasStandardLengthModifier())
  5463. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  5464. else if (!FS.hasStandardLengthConversionCombination())
  5465. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5466. diag::warn_format_non_standard_conversion_spec);
  5467. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  5468. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  5469. // The remaining checks depend on the data arguments.
  5470. if (HasVAListArg)
  5471. return true;
  5472. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  5473. return false;
  5474. const Expr *Arg = getDataArg(argIndex);
  5475. if (!Arg)
  5476. return true;
  5477. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  5478. }
  5479. static bool requiresParensToAddCast(const Expr *E) {
  5480. // FIXME: We should have a general way to reason about operator
  5481. // precedence and whether parens are actually needed here.
  5482. // Take care of a few common cases where they aren't.
  5483. const Expr *Inside = E->IgnoreImpCasts();
  5484. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  5485. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  5486. switch (Inside->getStmtClass()) {
  5487. case Stmt::ArraySubscriptExprClass:
  5488. case Stmt::CallExprClass:
  5489. case Stmt::CharacterLiteralClass:
  5490. case Stmt::CXXBoolLiteralExprClass:
  5491. case Stmt::DeclRefExprClass:
  5492. case Stmt::FloatingLiteralClass:
  5493. case Stmt::IntegerLiteralClass:
  5494. case Stmt::MemberExprClass:
  5495. case Stmt::ObjCArrayLiteralClass:
  5496. case Stmt::ObjCBoolLiteralExprClass:
  5497. case Stmt::ObjCBoxedExprClass:
  5498. case Stmt::ObjCDictionaryLiteralClass:
  5499. case Stmt::ObjCEncodeExprClass:
  5500. case Stmt::ObjCIvarRefExprClass:
  5501. case Stmt::ObjCMessageExprClass:
  5502. case Stmt::ObjCPropertyRefExprClass:
  5503. case Stmt::ObjCStringLiteralClass:
  5504. case Stmt::ObjCSubscriptRefExprClass:
  5505. case Stmt::ParenExprClass:
  5506. case Stmt::StringLiteralClass:
  5507. case Stmt::UnaryOperatorClass:
  5508. return false;
  5509. default:
  5510. return true;
  5511. }
  5512. }
  5513. static std::pair<QualType, StringRef>
  5514. shouldNotPrintDirectly(const ASTContext &Context,
  5515. QualType IntendedTy,
  5516. const Expr *E) {
  5517. // Use a 'while' to peel off layers of typedefs.
  5518. QualType TyTy = IntendedTy;
  5519. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  5520. StringRef Name = UserTy->getDecl()->getName();
  5521. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  5522. .Case("CFIndex", Context.getNSIntegerType())
  5523. .Case("NSInteger", Context.getNSIntegerType())
  5524. .Case("NSUInteger", Context.getNSUIntegerType())
  5525. .Case("SInt32", Context.IntTy)
  5526. .Case("UInt32", Context.UnsignedIntTy)
  5527. .Default(QualType());
  5528. if (!CastTy.isNull())
  5529. return std::make_pair(CastTy, Name);
  5530. TyTy = UserTy->desugar();
  5531. }
  5532. // Strip parens if necessary.
  5533. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  5534. return shouldNotPrintDirectly(Context,
  5535. PE->getSubExpr()->getType(),
  5536. PE->getSubExpr());
  5537. // If this is a conditional expression, then its result type is constructed
  5538. // via usual arithmetic conversions and thus there might be no necessary
  5539. // typedef sugar there. Recurse to operands to check for NSInteger &
  5540. // Co. usage condition.
  5541. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  5542. QualType TrueTy, FalseTy;
  5543. StringRef TrueName, FalseName;
  5544. std::tie(TrueTy, TrueName) =
  5545. shouldNotPrintDirectly(Context,
  5546. CO->getTrueExpr()->getType(),
  5547. CO->getTrueExpr());
  5548. std::tie(FalseTy, FalseName) =
  5549. shouldNotPrintDirectly(Context,
  5550. CO->getFalseExpr()->getType(),
  5551. CO->getFalseExpr());
  5552. if (TrueTy == FalseTy)
  5553. return std::make_pair(TrueTy, TrueName);
  5554. else if (TrueTy.isNull())
  5555. return std::make_pair(FalseTy, FalseName);
  5556. else if (FalseTy.isNull())
  5557. return std::make_pair(TrueTy, TrueName);
  5558. }
  5559. return std::make_pair(QualType(), StringRef());
  5560. }
  5561. bool
  5562. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  5563. const char *StartSpecifier,
  5564. unsigned SpecifierLen,
  5565. const Expr *E) {
  5566. using namespace analyze_format_string;
  5567. using namespace analyze_printf;
  5568. // Now type check the data expression that matches the
  5569. // format specifier.
  5570. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  5571. if (!AT.isValid())
  5572. return true;
  5573. QualType ExprTy = E->getType();
  5574. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  5575. ExprTy = TET->getUnderlyingExpr()->getType();
  5576. }
  5577. analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
  5578. if (match == analyze_printf::ArgType::Match) {
  5579. return true;
  5580. }
  5581. // Look through argument promotions for our error message's reported type.
  5582. // This includes the integral and floating promotions, but excludes array
  5583. // and function pointer decay; seeing that an argument intended to be a
  5584. // string has type 'char [6]' is probably more confusing than 'char *'.
  5585. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  5586. if (ICE->getCastKind() == CK_IntegralCast ||
  5587. ICE->getCastKind() == CK_FloatingCast) {
  5588. E = ICE->getSubExpr();
  5589. ExprTy = E->getType();
  5590. // Check if we didn't match because of an implicit cast from a 'char'
  5591. // or 'short' to an 'int'. This is done because printf is a varargs
  5592. // function.
  5593. if (ICE->getType() == S.Context.IntTy ||
  5594. ICE->getType() == S.Context.UnsignedIntTy) {
  5595. // All further checking is done on the subexpression.
  5596. if (AT.matchesType(S.Context, ExprTy))
  5597. return true;
  5598. }
  5599. }
  5600. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  5601. // Special case for 'a', which has type 'int' in C.
  5602. // Note, however, that we do /not/ want to treat multibyte constants like
  5603. // 'MooV' as characters! This form is deprecated but still exists.
  5604. if (ExprTy == S.Context.IntTy)
  5605. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  5606. ExprTy = S.Context.CharTy;
  5607. }
  5608. // Look through enums to their underlying type.
  5609. bool IsEnum = false;
  5610. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  5611. ExprTy = EnumTy->getDecl()->getIntegerType();
  5612. IsEnum = true;
  5613. }
  5614. // %C in an Objective-C context prints a unichar, not a wchar_t.
  5615. // If the argument is an integer of some kind, believe the %C and suggest
  5616. // a cast instead of changing the conversion specifier.
  5617. QualType IntendedTy = ExprTy;
  5618. if (isObjCContext() &&
  5619. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  5620. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  5621. !ExprTy->isCharType()) {
  5622. // 'unichar' is defined as a typedef of unsigned short, but we should
  5623. // prefer using the typedef if it is visible.
  5624. IntendedTy = S.Context.UnsignedShortTy;
  5625. // While we are here, check if the value is an IntegerLiteral that happens
  5626. // to be within the valid range.
  5627. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  5628. const llvm::APInt &V = IL->getValue();
  5629. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  5630. return true;
  5631. }
  5632. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
  5633. Sema::LookupOrdinaryName);
  5634. if (S.LookupName(Result, S.getCurScope())) {
  5635. NamedDecl *ND = Result.getFoundDecl();
  5636. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  5637. if (TD->getUnderlyingType() == IntendedTy)
  5638. IntendedTy = S.Context.getTypedefType(TD);
  5639. }
  5640. }
  5641. }
  5642. // Special-case some of Darwin's platform-independence types by suggesting
  5643. // casts to primitive types that are known to be large enough.
  5644. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  5645. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  5646. QualType CastTy;
  5647. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  5648. if (!CastTy.isNull()) {
  5649. IntendedTy = CastTy;
  5650. ShouldNotPrintDirectly = true;
  5651. }
  5652. }
  5653. // We may be able to offer a FixItHint if it is a supported type.
  5654. PrintfSpecifier fixedFS = FS;
  5655. bool success =
  5656. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  5657. if (success) {
  5658. // Get the fix string from the fixed format specifier
  5659. SmallString<16> buf;
  5660. llvm::raw_svector_ostream os(buf);
  5661. fixedFS.toString(os);
  5662. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  5663. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  5664. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  5665. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  5666. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  5667. }
  5668. // In this case, the specifier is wrong and should be changed to match
  5669. // the argument.
  5670. EmitFormatDiagnostic(S.PDiag(diag)
  5671. << AT.getRepresentativeTypeName(S.Context)
  5672. << IntendedTy << IsEnum << E->getSourceRange(),
  5673. E->getLocStart(),
  5674. /*IsStringLocation*/ false, SpecRange,
  5675. FixItHint::CreateReplacement(SpecRange, os.str()));
  5676. } else {
  5677. // The canonical type for formatting this value is different from the
  5678. // actual type of the expression. (This occurs, for example, with Darwin's
  5679. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  5680. // should be printed as 'long' for 64-bit compatibility.)
  5681. // Rather than emitting a normal format/argument mismatch, we want to
  5682. // add a cast to the recommended type (and correct the format string
  5683. // if necessary).
  5684. SmallString<16> CastBuf;
  5685. llvm::raw_svector_ostream CastFix(CastBuf);
  5686. CastFix << "(";
  5687. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  5688. CastFix << ")";
  5689. SmallVector<FixItHint,4> Hints;
  5690. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  5691. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  5692. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  5693. // If there's already a cast present, just replace it.
  5694. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  5695. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  5696. } else if (!requiresParensToAddCast(E)) {
  5697. // If the expression has high enough precedence,
  5698. // just write the C-style cast.
  5699. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  5700. CastFix.str()));
  5701. } else {
  5702. // Otherwise, add parens around the expression as well as the cast.
  5703. CastFix << "(";
  5704. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  5705. CastFix.str()));
  5706. SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
  5707. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  5708. }
  5709. if (ShouldNotPrintDirectly) {
  5710. // The expression has a type that should not be printed directly.
  5711. // We extract the name from the typedef because we don't want to show
  5712. // the underlying type in the diagnostic.
  5713. StringRef Name;
  5714. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  5715. Name = TypedefTy->getDecl()->getName();
  5716. else
  5717. Name = CastTyName;
  5718. EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
  5719. << Name << IntendedTy << IsEnum
  5720. << E->getSourceRange(),
  5721. E->getLocStart(), /*IsStringLocation=*/false,
  5722. SpecRange, Hints);
  5723. } else {
  5724. // In this case, the expression could be printed using a different
  5725. // specifier, but we've decided that the specifier is probably correct
  5726. // and we should cast instead. Just use the normal warning message.
  5727. EmitFormatDiagnostic(
  5728. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  5729. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  5730. << E->getSourceRange(),
  5731. E->getLocStart(), /*IsStringLocation*/false,
  5732. SpecRange, Hints);
  5733. }
  5734. }
  5735. } else {
  5736. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  5737. SpecifierLen);
  5738. // Since the warning for passing non-POD types to variadic functions
  5739. // was deferred until now, we emit a warning for non-POD
  5740. // arguments here.
  5741. switch (S.isValidVarArgType(ExprTy)) {
  5742. case Sema::VAK_Valid:
  5743. case Sema::VAK_ValidInCXX11: {
  5744. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  5745. if (match == analyze_printf::ArgType::NoMatchPedantic) {
  5746. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  5747. }
  5748. EmitFormatDiagnostic(
  5749. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  5750. << IsEnum << CSR << E->getSourceRange(),
  5751. E->getLocStart(), /*IsStringLocation*/ false, CSR);
  5752. break;
  5753. }
  5754. case Sema::VAK_Undefined:
  5755. case Sema::VAK_MSVCUndefined:
  5756. EmitFormatDiagnostic(
  5757. S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  5758. << S.getLangOpts().CPlusPlus11
  5759. << ExprTy
  5760. << CallType
  5761. << AT.getRepresentativeTypeName(S.Context)
  5762. << CSR
  5763. << E->getSourceRange(),
  5764. E->getLocStart(), /*IsStringLocation*/false, CSR);
  5765. checkForCStrMembers(AT, E);
  5766. break;
  5767. case Sema::VAK_Invalid:
  5768. if (ExprTy->isObjCObjectType())
  5769. EmitFormatDiagnostic(
  5770. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  5771. << S.getLangOpts().CPlusPlus11
  5772. << ExprTy
  5773. << CallType
  5774. << AT.getRepresentativeTypeName(S.Context)
  5775. << CSR
  5776. << E->getSourceRange(),
  5777. E->getLocStart(), /*IsStringLocation*/false, CSR);
  5778. else
  5779. // FIXME: If this is an initializer list, suggest removing the braces
  5780. // or inserting a cast to the target type.
  5781. S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
  5782. << isa<InitListExpr>(E) << ExprTy << CallType
  5783. << AT.getRepresentativeTypeName(S.Context)
  5784. << E->getSourceRange();
  5785. break;
  5786. }
  5787. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  5788. "format string specifier index out of range");
  5789. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  5790. }
  5791. return true;
  5792. }
  5793. //===--- CHECK: Scanf format string checking ------------------------------===//
  5794. namespace {
  5795. class CheckScanfHandler : public CheckFormatHandler {
  5796. public:
  5797. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  5798. const Expr *origFormatExpr, Sema::FormatStringType type,
  5799. unsigned firstDataArg, unsigned numDataArgs,
  5800. const char *beg, bool hasVAListArg,
  5801. ArrayRef<const Expr *> Args, unsigned formatIdx,
  5802. bool inFunctionCall, Sema::VariadicCallType CallType,
  5803. llvm::SmallBitVector &CheckedVarArgs,
  5804. UncoveredArgHandler &UncoveredArg)
  5805. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  5806. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  5807. inFunctionCall, CallType, CheckedVarArgs,
  5808. UncoveredArg) {}
  5809. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  5810. const char *startSpecifier,
  5811. unsigned specifierLen) override;
  5812. bool HandleInvalidScanfConversionSpecifier(
  5813. const analyze_scanf::ScanfSpecifier &FS,
  5814. const char *startSpecifier,
  5815. unsigned specifierLen) override;
  5816. void HandleIncompleteScanList(const char *start, const char *end) override;
  5817. };
  5818. } // end anonymous namespace
  5819. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  5820. const char *end) {
  5821. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  5822. getLocationOfByte(end), /*IsStringLocation*/true,
  5823. getSpecifierRange(start, end - start));
  5824. }
  5825. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  5826. const analyze_scanf::ScanfSpecifier &FS,
  5827. const char *startSpecifier,
  5828. unsigned specifierLen) {
  5829. const analyze_scanf::ScanfConversionSpecifier &CS =
  5830. FS.getConversionSpecifier();
  5831. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  5832. getLocationOfByte(CS.getStart()),
  5833. startSpecifier, specifierLen,
  5834. CS.getStart(), CS.getLength());
  5835. }
  5836. bool CheckScanfHandler::HandleScanfSpecifier(
  5837. const analyze_scanf::ScanfSpecifier &FS,
  5838. const char *startSpecifier,
  5839. unsigned specifierLen) {
  5840. using namespace analyze_scanf;
  5841. using namespace analyze_format_string;
  5842. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  5843. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  5844. // be used to decide if we are using positional arguments consistently.
  5845. if (FS.consumesDataArgument()) {
  5846. if (atFirstArg) {
  5847. atFirstArg = false;
  5848. usesPositionalArgs = FS.usesPositionalArg();
  5849. }
  5850. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  5851. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  5852. startSpecifier, specifierLen);
  5853. return false;
  5854. }
  5855. }
  5856. // Check if the field with is non-zero.
  5857. const OptionalAmount &Amt = FS.getFieldWidth();
  5858. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  5859. if (Amt.getConstantAmount() == 0) {
  5860. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  5861. Amt.getConstantLength());
  5862. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  5863. getLocationOfByte(Amt.getStart()),
  5864. /*IsStringLocation*/true, R,
  5865. FixItHint::CreateRemoval(R));
  5866. }
  5867. }
  5868. if (!FS.consumesDataArgument()) {
  5869. // FIXME: Technically specifying a precision or field width here
  5870. // makes no sense. Worth issuing a warning at some point.
  5871. return true;
  5872. }
  5873. // Consume the argument.
  5874. unsigned argIndex = FS.getArgIndex();
  5875. if (argIndex < NumDataArgs) {
  5876. // The check to see if the argIndex is valid will come later.
  5877. // We set the bit here because we may exit early from this
  5878. // function if we encounter some other error.
  5879. CoveredArgs.set(argIndex);
  5880. }
  5881. // Check the length modifier is valid with the given conversion specifier.
  5882. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  5883. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5884. diag::warn_format_nonsensical_length);
  5885. else if (!FS.hasStandardLengthModifier())
  5886. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  5887. else if (!FS.hasStandardLengthConversionCombination())
  5888. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5889. diag::warn_format_non_standard_conversion_spec);
  5890. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  5891. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  5892. // The remaining checks depend on the data arguments.
  5893. if (HasVAListArg)
  5894. return true;
  5895. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  5896. return false;
  5897. // Check that the argument type matches the format specifier.
  5898. const Expr *Ex = getDataArg(argIndex);
  5899. if (!Ex)
  5900. return true;
  5901. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  5902. if (!AT.isValid()) {
  5903. return true;
  5904. }
  5905. analyze_format_string::ArgType::MatchKind match =
  5906. AT.matchesType(S.Context, Ex->getType());
  5907. if (match == analyze_format_string::ArgType::Match) {
  5908. return true;
  5909. }
  5910. ScanfSpecifier fixedFS = FS;
  5911. bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  5912. S.getLangOpts(), S.Context);
  5913. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  5914. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  5915. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  5916. }
  5917. if (success) {
  5918. // Get the fix string from the fixed format specifier.
  5919. SmallString<128> buf;
  5920. llvm::raw_svector_ostream os(buf);
  5921. fixedFS.toString(os);
  5922. EmitFormatDiagnostic(
  5923. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
  5924. << Ex->getType() << false << Ex->getSourceRange(),
  5925. Ex->getLocStart(),
  5926. /*IsStringLocation*/ false,
  5927. getSpecifierRange(startSpecifier, specifierLen),
  5928. FixItHint::CreateReplacement(
  5929. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  5930. } else {
  5931. EmitFormatDiagnostic(S.PDiag(diag)
  5932. << AT.getRepresentativeTypeName(S.Context)
  5933. << Ex->getType() << false << Ex->getSourceRange(),
  5934. Ex->getLocStart(),
  5935. /*IsStringLocation*/ false,
  5936. getSpecifierRange(startSpecifier, specifierLen));
  5937. }
  5938. return true;
  5939. }
  5940. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  5941. const Expr *OrigFormatExpr,
  5942. ArrayRef<const Expr *> Args,
  5943. bool HasVAListArg, unsigned format_idx,
  5944. unsigned firstDataArg,
  5945. Sema::FormatStringType Type,
  5946. bool inFunctionCall,
  5947. Sema::VariadicCallType CallType,
  5948. llvm::SmallBitVector &CheckedVarArgs,
  5949. UncoveredArgHandler &UncoveredArg) {
  5950. // CHECK: is the format string a wide literal?
  5951. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  5952. CheckFormatHandler::EmitFormatDiagnostic(
  5953. S, inFunctionCall, Args[format_idx],
  5954. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  5955. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  5956. return;
  5957. }
  5958. // Str - The format string. NOTE: this is NOT null-terminated!
  5959. StringRef StrRef = FExpr->getString();
  5960. const char *Str = StrRef.data();
  5961. // Account for cases where the string literal is truncated in a declaration.
  5962. const ConstantArrayType *T =
  5963. S.Context.getAsConstantArrayType(FExpr->getType());
  5964. assert(T && "String literal not of constant array type!");
  5965. size_t TypeSize = T->getSize().getZExtValue();
  5966. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  5967. const unsigned numDataArgs = Args.size() - firstDataArg;
  5968. // Emit a warning if the string literal is truncated and does not contain an
  5969. // embedded null character.
  5970. if (TypeSize <= StrRef.size() &&
  5971. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  5972. CheckFormatHandler::EmitFormatDiagnostic(
  5973. S, inFunctionCall, Args[format_idx],
  5974. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  5975. FExpr->getLocStart(),
  5976. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  5977. return;
  5978. }
  5979. // CHECK: empty format string?
  5980. if (StrLen == 0 && numDataArgs > 0) {
  5981. CheckFormatHandler::EmitFormatDiagnostic(
  5982. S, inFunctionCall, Args[format_idx],
  5983. S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  5984. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  5985. return;
  5986. }
  5987. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  5988. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  5989. Type == Sema::FST_OSTrace) {
  5990. CheckPrintfHandler H(
  5991. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  5992. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  5993. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  5994. CheckedVarArgs, UncoveredArg);
  5995. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  5996. S.getLangOpts(),
  5997. S.Context.getTargetInfo(),
  5998. Type == Sema::FST_FreeBSDKPrintf))
  5999. H.DoneProcessing();
  6000. } else if (Type == Sema::FST_Scanf) {
  6001. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  6002. numDataArgs, Str, HasVAListArg, Args, format_idx,
  6003. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  6004. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  6005. S.getLangOpts(),
  6006. S.Context.getTargetInfo()))
  6007. H.DoneProcessing();
  6008. } // TODO: handle other formats
  6009. }
  6010. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  6011. // Str - The format string. NOTE: this is NOT null-terminated!
  6012. StringRef StrRef = FExpr->getString();
  6013. const char *Str = StrRef.data();
  6014. // Account for cases where the string literal is truncated in a declaration.
  6015. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  6016. assert(T && "String literal not of constant array type!");
  6017. size_t TypeSize = T->getSize().getZExtValue();
  6018. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  6019. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  6020. getLangOpts(),
  6021. Context.getTargetInfo());
  6022. }
  6023. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  6024. // Returns the related absolute value function that is larger, of 0 if one
  6025. // does not exist.
  6026. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  6027. switch (AbsFunction) {
  6028. default:
  6029. return 0;
  6030. case Builtin::BI__builtin_abs:
  6031. return Builtin::BI__builtin_labs;
  6032. case Builtin::BI__builtin_labs:
  6033. return Builtin::BI__builtin_llabs;
  6034. case Builtin::BI__builtin_llabs:
  6035. return 0;
  6036. case Builtin::BI__builtin_fabsf:
  6037. return Builtin::BI__builtin_fabs;
  6038. case Builtin::BI__builtin_fabs:
  6039. return Builtin::BI__builtin_fabsl;
  6040. case Builtin::BI__builtin_fabsl:
  6041. return 0;
  6042. case Builtin::BI__builtin_cabsf:
  6043. return Builtin::BI__builtin_cabs;
  6044. case Builtin::BI__builtin_cabs:
  6045. return Builtin::BI__builtin_cabsl;
  6046. case Builtin::BI__builtin_cabsl:
  6047. return 0;
  6048. case Builtin::BIabs:
  6049. return Builtin::BIlabs;
  6050. case Builtin::BIlabs:
  6051. return Builtin::BIllabs;
  6052. case Builtin::BIllabs:
  6053. return 0;
  6054. case Builtin::BIfabsf:
  6055. return Builtin::BIfabs;
  6056. case Builtin::BIfabs:
  6057. return Builtin::BIfabsl;
  6058. case Builtin::BIfabsl:
  6059. return 0;
  6060. case Builtin::BIcabsf:
  6061. return Builtin::BIcabs;
  6062. case Builtin::BIcabs:
  6063. return Builtin::BIcabsl;
  6064. case Builtin::BIcabsl:
  6065. return 0;
  6066. }
  6067. }
  6068. // Returns the argument type of the absolute value function.
  6069. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  6070. unsigned AbsType) {
  6071. if (AbsType == 0)
  6072. return QualType();
  6073. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  6074. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  6075. if (Error != ASTContext::GE_None)
  6076. return QualType();
  6077. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  6078. if (!FT)
  6079. return QualType();
  6080. if (FT->getNumParams() != 1)
  6081. return QualType();
  6082. return FT->getParamType(0);
  6083. }
  6084. // Returns the best absolute value function, or zero, based on type and
  6085. // current absolute value function.
  6086. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  6087. unsigned AbsFunctionKind) {
  6088. unsigned BestKind = 0;
  6089. uint64_t ArgSize = Context.getTypeSize(ArgType);
  6090. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  6091. Kind = getLargerAbsoluteValueFunction(Kind)) {
  6092. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  6093. if (Context.getTypeSize(ParamType) >= ArgSize) {
  6094. if (BestKind == 0)
  6095. BestKind = Kind;
  6096. else if (Context.hasSameType(ParamType, ArgType)) {
  6097. BestKind = Kind;
  6098. break;
  6099. }
  6100. }
  6101. }
  6102. return BestKind;
  6103. }
  6104. enum AbsoluteValueKind {
  6105. AVK_Integer,
  6106. AVK_Floating,
  6107. AVK_Complex
  6108. };
  6109. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  6110. if (T->isIntegralOrEnumerationType())
  6111. return AVK_Integer;
  6112. if (T->isRealFloatingType())
  6113. return AVK_Floating;
  6114. if (T->isAnyComplexType())
  6115. return AVK_Complex;
  6116. llvm_unreachable("Type not integer, floating, or complex");
  6117. }
  6118. // Changes the absolute value function to a different type. Preserves whether
  6119. // the function is a builtin.
  6120. static unsigned changeAbsFunction(unsigned AbsKind,
  6121. AbsoluteValueKind ValueKind) {
  6122. switch (ValueKind) {
  6123. case AVK_Integer:
  6124. switch (AbsKind) {
  6125. default:
  6126. return 0;
  6127. case Builtin::BI__builtin_fabsf:
  6128. case Builtin::BI__builtin_fabs:
  6129. case Builtin::BI__builtin_fabsl:
  6130. case Builtin::BI__builtin_cabsf:
  6131. case Builtin::BI__builtin_cabs:
  6132. case Builtin::BI__builtin_cabsl:
  6133. return Builtin::BI__builtin_abs;
  6134. case Builtin::BIfabsf:
  6135. case Builtin::BIfabs:
  6136. case Builtin::BIfabsl:
  6137. case Builtin::BIcabsf:
  6138. case Builtin::BIcabs:
  6139. case Builtin::BIcabsl:
  6140. return Builtin::BIabs;
  6141. }
  6142. case AVK_Floating:
  6143. switch (AbsKind) {
  6144. default:
  6145. return 0;
  6146. case Builtin::BI__builtin_abs:
  6147. case Builtin::BI__builtin_labs:
  6148. case Builtin::BI__builtin_llabs:
  6149. case Builtin::BI__builtin_cabsf:
  6150. case Builtin::BI__builtin_cabs:
  6151. case Builtin::BI__builtin_cabsl:
  6152. return Builtin::BI__builtin_fabsf;
  6153. case Builtin::BIabs:
  6154. case Builtin::BIlabs:
  6155. case Builtin::BIllabs:
  6156. case Builtin::BIcabsf:
  6157. case Builtin::BIcabs:
  6158. case Builtin::BIcabsl:
  6159. return Builtin::BIfabsf;
  6160. }
  6161. case AVK_Complex:
  6162. switch (AbsKind) {
  6163. default:
  6164. return 0;
  6165. case Builtin::BI__builtin_abs:
  6166. case Builtin::BI__builtin_labs:
  6167. case Builtin::BI__builtin_llabs:
  6168. case Builtin::BI__builtin_fabsf:
  6169. case Builtin::BI__builtin_fabs:
  6170. case Builtin::BI__builtin_fabsl:
  6171. return Builtin::BI__builtin_cabsf;
  6172. case Builtin::BIabs:
  6173. case Builtin::BIlabs:
  6174. case Builtin::BIllabs:
  6175. case Builtin::BIfabsf:
  6176. case Builtin::BIfabs:
  6177. case Builtin::BIfabsl:
  6178. return Builtin::BIcabsf;
  6179. }
  6180. }
  6181. llvm_unreachable("Unable to convert function");
  6182. }
  6183. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  6184. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  6185. if (!FnInfo)
  6186. return 0;
  6187. switch (FDecl->getBuiltinID()) {
  6188. default:
  6189. return 0;
  6190. case Builtin::BI__builtin_abs:
  6191. case Builtin::BI__builtin_fabs:
  6192. case Builtin::BI__builtin_fabsf:
  6193. case Builtin::BI__builtin_fabsl:
  6194. case Builtin::BI__builtin_labs:
  6195. case Builtin::BI__builtin_llabs:
  6196. case Builtin::BI__builtin_cabs:
  6197. case Builtin::BI__builtin_cabsf:
  6198. case Builtin::BI__builtin_cabsl:
  6199. case Builtin::BIabs:
  6200. case Builtin::BIlabs:
  6201. case Builtin::BIllabs:
  6202. case Builtin::BIfabs:
  6203. case Builtin::BIfabsf:
  6204. case Builtin::BIfabsl:
  6205. case Builtin::BIcabs:
  6206. case Builtin::BIcabsf:
  6207. case Builtin::BIcabsl:
  6208. return FDecl->getBuiltinID();
  6209. }
  6210. llvm_unreachable("Unknown Builtin type");
  6211. }
  6212. // If the replacement is valid, emit a note with replacement function.
  6213. // Additionally, suggest including the proper header if not already included.
  6214. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  6215. unsigned AbsKind, QualType ArgType) {
  6216. bool EmitHeaderHint = true;
  6217. const char *HeaderName = nullptr;
  6218. const char *FunctionName = nullptr;
  6219. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  6220. FunctionName = "std::abs";
  6221. if (ArgType->isIntegralOrEnumerationType()) {
  6222. HeaderName = "cstdlib";
  6223. } else if (ArgType->isRealFloatingType()) {
  6224. HeaderName = "cmath";
  6225. } else {
  6226. llvm_unreachable("Invalid Type");
  6227. }
  6228. // Lookup all std::abs
  6229. if (NamespaceDecl *Std = S.getStdNamespace()) {
  6230. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  6231. R.suppressDiagnostics();
  6232. S.LookupQualifiedName(R, Std);
  6233. for (const auto *I : R) {
  6234. const FunctionDecl *FDecl = nullptr;
  6235. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  6236. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  6237. } else {
  6238. FDecl = dyn_cast<FunctionDecl>(I);
  6239. }
  6240. if (!FDecl)
  6241. continue;
  6242. // Found std::abs(), check that they are the right ones.
  6243. if (FDecl->getNumParams() != 1)
  6244. continue;
  6245. // Check that the parameter type can handle the argument.
  6246. QualType ParamType = FDecl->getParamDecl(0)->getType();
  6247. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  6248. S.Context.getTypeSize(ArgType) <=
  6249. S.Context.getTypeSize(ParamType)) {
  6250. // Found a function, don't need the header hint.
  6251. EmitHeaderHint = false;
  6252. break;
  6253. }
  6254. }
  6255. }
  6256. } else {
  6257. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  6258. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  6259. if (HeaderName) {
  6260. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  6261. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  6262. R.suppressDiagnostics();
  6263. S.LookupName(R, S.getCurScope());
  6264. if (R.isSingleResult()) {
  6265. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  6266. if (FD && FD->getBuiltinID() == AbsKind) {
  6267. EmitHeaderHint = false;
  6268. } else {
  6269. return;
  6270. }
  6271. } else if (!R.empty()) {
  6272. return;
  6273. }
  6274. }
  6275. }
  6276. S.Diag(Loc, diag::note_replace_abs_function)
  6277. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  6278. if (!HeaderName)
  6279. return;
  6280. if (!EmitHeaderHint)
  6281. return;
  6282. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  6283. << FunctionName;
  6284. }
  6285. template <std::size_t StrLen>
  6286. static bool IsStdFunction(const FunctionDecl *FDecl,
  6287. const char (&Str)[StrLen]) {
  6288. if (!FDecl)
  6289. return false;
  6290. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  6291. return false;
  6292. if (!FDecl->isInStdNamespace())
  6293. return false;
  6294. return true;
  6295. }
  6296. // Warn when using the wrong abs() function.
  6297. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  6298. const FunctionDecl *FDecl) {
  6299. if (Call->getNumArgs() != 1)
  6300. return;
  6301. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  6302. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  6303. if (AbsKind == 0 && !IsStdAbs)
  6304. return;
  6305. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  6306. QualType ParamType = Call->getArg(0)->getType();
  6307. // Unsigned types cannot be negative. Suggest removing the absolute value
  6308. // function call.
  6309. if (ArgType->isUnsignedIntegerType()) {
  6310. const char *FunctionName =
  6311. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  6312. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  6313. Diag(Call->getExprLoc(), diag::note_remove_abs)
  6314. << FunctionName
  6315. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  6316. return;
  6317. }
  6318. // Taking the absolute value of a pointer is very suspicious, they probably
  6319. // wanted to index into an array, dereference a pointer, call a function, etc.
  6320. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  6321. unsigned DiagType = 0;
  6322. if (ArgType->isFunctionType())
  6323. DiagType = 1;
  6324. else if (ArgType->isArrayType())
  6325. DiagType = 2;
  6326. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  6327. return;
  6328. }
  6329. // std::abs has overloads which prevent most of the absolute value problems
  6330. // from occurring.
  6331. if (IsStdAbs)
  6332. return;
  6333. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  6334. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  6335. // The argument and parameter are the same kind. Check if they are the right
  6336. // size.
  6337. if (ArgValueKind == ParamValueKind) {
  6338. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  6339. return;
  6340. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  6341. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  6342. << FDecl << ArgType << ParamType;
  6343. if (NewAbsKind == 0)
  6344. return;
  6345. emitReplacement(*this, Call->getExprLoc(),
  6346. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  6347. return;
  6348. }
  6349. // ArgValueKind != ParamValueKind
  6350. // The wrong type of absolute value function was used. Attempt to find the
  6351. // proper one.
  6352. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  6353. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  6354. if (NewAbsKind == 0)
  6355. return;
  6356. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  6357. << FDecl << ParamValueKind << ArgValueKind;
  6358. emitReplacement(*this, Call->getExprLoc(),
  6359. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  6360. }
  6361. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  6362. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  6363. const FunctionDecl *FDecl) {
  6364. if (!Call || !FDecl) return;
  6365. // Ignore template specializations and macros.
  6366. if (inTemplateInstantiation()) return;
  6367. if (Call->getExprLoc().isMacroID()) return;
  6368. // Only care about the one template argument, two function parameter std::max
  6369. if (Call->getNumArgs() != 2) return;
  6370. if (!IsStdFunction(FDecl, "max")) return;
  6371. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  6372. if (!ArgList) return;
  6373. if (ArgList->size() != 1) return;
  6374. // Check that template type argument is unsigned integer.
  6375. const auto& TA = ArgList->get(0);
  6376. if (TA.getKind() != TemplateArgument::Type) return;
  6377. QualType ArgType = TA.getAsType();
  6378. if (!ArgType->isUnsignedIntegerType()) return;
  6379. // See if either argument is a literal zero.
  6380. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  6381. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  6382. if (!MTE) return false;
  6383. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  6384. if (!Num) return false;
  6385. if (Num->getValue() != 0) return false;
  6386. return true;
  6387. };
  6388. const Expr *FirstArg = Call->getArg(0);
  6389. const Expr *SecondArg = Call->getArg(1);
  6390. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  6391. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  6392. // Only warn when exactly one argument is zero.
  6393. if (IsFirstArgZero == IsSecondArgZero) return;
  6394. SourceRange FirstRange = FirstArg->getSourceRange();
  6395. SourceRange SecondRange = SecondArg->getSourceRange();
  6396. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  6397. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  6398. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  6399. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  6400. SourceRange RemovalRange;
  6401. if (IsFirstArgZero) {
  6402. RemovalRange = SourceRange(FirstRange.getBegin(),
  6403. SecondRange.getBegin().getLocWithOffset(-1));
  6404. } else {
  6405. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  6406. SecondRange.getEnd());
  6407. }
  6408. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  6409. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  6410. << FixItHint::CreateRemoval(RemovalRange);
  6411. }
  6412. //===--- CHECK: Standard memory functions ---------------------------------===//
  6413. /// \brief Takes the expression passed to the size_t parameter of functions
  6414. /// such as memcmp, strncat, etc and warns if it's a comparison.
  6415. ///
  6416. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  6417. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  6418. IdentifierInfo *FnName,
  6419. SourceLocation FnLoc,
  6420. SourceLocation RParenLoc) {
  6421. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  6422. if (!Size)
  6423. return false;
  6424. // if E is binop and op is >, <, >=, <=, ==, &&, ||:
  6425. if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
  6426. return false;
  6427. SourceRange SizeRange = Size->getSourceRange();
  6428. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  6429. << SizeRange << FnName;
  6430. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  6431. << FnName << FixItHint::CreateInsertion(
  6432. S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
  6433. << FixItHint::CreateRemoval(RParenLoc);
  6434. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  6435. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  6436. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  6437. ")");
  6438. return true;
  6439. }
  6440. /// \brief Determine whether the given type is or contains a dynamic class type
  6441. /// (e.g., whether it has a vtable).
  6442. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  6443. bool &IsContained) {
  6444. // Look through array types while ignoring qualifiers.
  6445. const Type *Ty = T->getBaseElementTypeUnsafe();
  6446. IsContained = false;
  6447. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  6448. RD = RD ? RD->getDefinition() : nullptr;
  6449. if (!RD || RD->isInvalidDecl())
  6450. return nullptr;
  6451. if (RD->isDynamicClass())
  6452. return RD;
  6453. // Check all the fields. If any bases were dynamic, the class is dynamic.
  6454. // It's impossible for a class to transitively contain itself by value, so
  6455. // infinite recursion is impossible.
  6456. for (auto *FD : RD->fields()) {
  6457. bool SubContained;
  6458. if (const CXXRecordDecl *ContainedRD =
  6459. getContainedDynamicClass(FD->getType(), SubContained)) {
  6460. IsContained = true;
  6461. return ContainedRD;
  6462. }
  6463. }
  6464. return nullptr;
  6465. }
  6466. /// \brief If E is a sizeof expression, returns its argument expression,
  6467. /// otherwise returns NULL.
  6468. static const Expr *getSizeOfExprArg(const Expr *E) {
  6469. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  6470. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  6471. if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
  6472. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  6473. return nullptr;
  6474. }
  6475. /// \brief If E is a sizeof expression, returns its argument type.
  6476. static QualType getSizeOfArgType(const Expr *E) {
  6477. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  6478. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  6479. if (SizeOf->getKind() == clang::UETT_SizeOf)
  6480. return SizeOf->getTypeOfArgument();
  6481. return QualType();
  6482. }
  6483. /// \brief Check for dangerous or invalid arguments to memset().
  6484. ///
  6485. /// This issues warnings on known problematic, dangerous or unspecified
  6486. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  6487. /// function calls.
  6488. ///
  6489. /// \param Call The call expression to diagnose.
  6490. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  6491. unsigned BId,
  6492. IdentifierInfo *FnName) {
  6493. assert(BId != 0);
  6494. // It is possible to have a non-standard definition of memset. Validate
  6495. // we have enough arguments, and if not, abort further checking.
  6496. unsigned ExpectedNumArgs =
  6497. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  6498. if (Call->getNumArgs() < ExpectedNumArgs)
  6499. return;
  6500. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  6501. BId == Builtin::BIstrndup ? 1 : 2);
  6502. unsigned LenArg =
  6503. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  6504. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  6505. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  6506. Call->getLocStart(), Call->getRParenLoc()))
  6507. return;
  6508. // We have special checking when the length is a sizeof expression.
  6509. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  6510. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  6511. llvm::FoldingSetNodeID SizeOfArgID;
  6512. // Although widely used, 'bzero' is not a standard function. Be more strict
  6513. // with the argument types before allowing diagnostics and only allow the
  6514. // form bzero(ptr, sizeof(...)).
  6515. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  6516. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  6517. return;
  6518. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  6519. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  6520. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  6521. QualType DestTy = Dest->getType();
  6522. QualType PointeeTy;
  6523. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  6524. PointeeTy = DestPtrTy->getPointeeType();
  6525. // Never warn about void type pointers. This can be used to suppress
  6526. // false positives.
  6527. if (PointeeTy->isVoidType())
  6528. continue;
  6529. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  6530. // actually comparing the expressions for equality. Because computing the
  6531. // expression IDs can be expensive, we only do this if the diagnostic is
  6532. // enabled.
  6533. if (SizeOfArg &&
  6534. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  6535. SizeOfArg->getExprLoc())) {
  6536. // We only compute IDs for expressions if the warning is enabled, and
  6537. // cache the sizeof arg's ID.
  6538. if (SizeOfArgID == llvm::FoldingSetNodeID())
  6539. SizeOfArg->Profile(SizeOfArgID, Context, true);
  6540. llvm::FoldingSetNodeID DestID;
  6541. Dest->Profile(DestID, Context, true);
  6542. if (DestID == SizeOfArgID) {
  6543. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  6544. // over sizeof(src) as well.
  6545. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  6546. StringRef ReadableName = FnName->getName();
  6547. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  6548. if (UnaryOp->getOpcode() == UO_AddrOf)
  6549. ActionIdx = 1; // If its an address-of operator, just remove it.
  6550. if (!PointeeTy->isIncompleteType() &&
  6551. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  6552. ActionIdx = 2; // If the pointee's size is sizeof(char),
  6553. // suggest an explicit length.
  6554. // If the function is defined as a builtin macro, do not show macro
  6555. // expansion.
  6556. SourceLocation SL = SizeOfArg->getExprLoc();
  6557. SourceRange DSR = Dest->getSourceRange();
  6558. SourceRange SSR = SizeOfArg->getSourceRange();
  6559. SourceManager &SM = getSourceManager();
  6560. if (SM.isMacroArgExpansion(SL)) {
  6561. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  6562. SL = SM.getSpellingLoc(SL);
  6563. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  6564. SM.getSpellingLoc(DSR.getEnd()));
  6565. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  6566. SM.getSpellingLoc(SSR.getEnd()));
  6567. }
  6568. DiagRuntimeBehavior(SL, SizeOfArg,
  6569. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  6570. << ReadableName
  6571. << PointeeTy
  6572. << DestTy
  6573. << DSR
  6574. << SSR);
  6575. DiagRuntimeBehavior(SL, SizeOfArg,
  6576. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  6577. << ActionIdx
  6578. << SSR);
  6579. break;
  6580. }
  6581. }
  6582. // Also check for cases where the sizeof argument is the exact same
  6583. // type as the memory argument, and where it points to a user-defined
  6584. // record type.
  6585. if (SizeOfArgTy != QualType()) {
  6586. if (PointeeTy->isRecordType() &&
  6587. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  6588. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  6589. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  6590. << FnName << SizeOfArgTy << ArgIdx
  6591. << PointeeTy << Dest->getSourceRange()
  6592. << LenExpr->getSourceRange());
  6593. break;
  6594. }
  6595. }
  6596. } else if (DestTy->isArrayType()) {
  6597. PointeeTy = DestTy;
  6598. }
  6599. if (PointeeTy == QualType())
  6600. continue;
  6601. // Always complain about dynamic classes.
  6602. bool IsContained;
  6603. if (const CXXRecordDecl *ContainedRD =
  6604. getContainedDynamicClass(PointeeTy, IsContained)) {
  6605. unsigned OperationType = 0;
  6606. // "overwritten" if we're warning about the destination for any call
  6607. // but memcmp; otherwise a verb appropriate to the call.
  6608. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  6609. if (BId == Builtin::BImemcpy)
  6610. OperationType = 1;
  6611. else if(BId == Builtin::BImemmove)
  6612. OperationType = 2;
  6613. else if (BId == Builtin::BImemcmp)
  6614. OperationType = 3;
  6615. }
  6616. DiagRuntimeBehavior(
  6617. Dest->getExprLoc(), Dest,
  6618. PDiag(diag::warn_dyn_class_memaccess)
  6619. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  6620. << FnName << IsContained << ContainedRD << OperationType
  6621. << Call->getCallee()->getSourceRange());
  6622. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  6623. BId != Builtin::BImemset)
  6624. DiagRuntimeBehavior(
  6625. Dest->getExprLoc(), Dest,
  6626. PDiag(diag::warn_arc_object_memaccess)
  6627. << ArgIdx << FnName << PointeeTy
  6628. << Call->getCallee()->getSourceRange());
  6629. else
  6630. continue;
  6631. DiagRuntimeBehavior(
  6632. Dest->getExprLoc(), Dest,
  6633. PDiag(diag::note_bad_memaccess_silence)
  6634. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  6635. break;
  6636. }
  6637. }
  6638. // A little helper routine: ignore addition and subtraction of integer literals.
  6639. // This intentionally does not ignore all integer constant expressions because
  6640. // we don't want to remove sizeof().
  6641. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  6642. Ex = Ex->IgnoreParenCasts();
  6643. for (;;) {
  6644. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  6645. if (!BO || !BO->isAdditiveOp())
  6646. break;
  6647. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  6648. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  6649. if (isa<IntegerLiteral>(RHS))
  6650. Ex = LHS;
  6651. else if (isa<IntegerLiteral>(LHS))
  6652. Ex = RHS;
  6653. else
  6654. break;
  6655. }
  6656. return Ex;
  6657. }
  6658. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  6659. ASTContext &Context) {
  6660. // Only handle constant-sized or VLAs, but not flexible members.
  6661. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  6662. // Only issue the FIXIT for arrays of size > 1.
  6663. if (CAT->getSize().getSExtValue() <= 1)
  6664. return false;
  6665. } else if (!Ty->isVariableArrayType()) {
  6666. return false;
  6667. }
  6668. return true;
  6669. }
  6670. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  6671. // be the size of the source, instead of the destination.
  6672. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  6673. IdentifierInfo *FnName) {
  6674. // Don't crash if the user has the wrong number of arguments
  6675. unsigned NumArgs = Call->getNumArgs();
  6676. if ((NumArgs != 3) && (NumArgs != 4))
  6677. return;
  6678. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  6679. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  6680. const Expr *CompareWithSrc = nullptr;
  6681. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  6682. Call->getLocStart(), Call->getRParenLoc()))
  6683. return;
  6684. // Look for 'strlcpy(dst, x, sizeof(x))'
  6685. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  6686. CompareWithSrc = Ex;
  6687. else {
  6688. // Look for 'strlcpy(dst, x, strlen(x))'
  6689. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  6690. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  6691. SizeCall->getNumArgs() == 1)
  6692. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  6693. }
  6694. }
  6695. if (!CompareWithSrc)
  6696. return;
  6697. // Determine if the argument to sizeof/strlen is equal to the source
  6698. // argument. In principle there's all kinds of things you could do
  6699. // here, for instance creating an == expression and evaluating it with
  6700. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  6701. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  6702. if (!SrcArgDRE)
  6703. return;
  6704. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  6705. if (!CompareWithSrcDRE ||
  6706. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  6707. return;
  6708. const Expr *OriginalSizeArg = Call->getArg(2);
  6709. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  6710. << OriginalSizeArg->getSourceRange() << FnName;
  6711. // Output a FIXIT hint if the destination is an array (rather than a
  6712. // pointer to an array). This could be enhanced to handle some
  6713. // pointers if we know the actual size, like if DstArg is 'array+2'
  6714. // we could say 'sizeof(array)-2'.
  6715. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  6716. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  6717. return;
  6718. SmallString<128> sizeString;
  6719. llvm::raw_svector_ostream OS(sizeString);
  6720. OS << "sizeof(";
  6721. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  6722. OS << ")";
  6723. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  6724. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  6725. OS.str());
  6726. }
  6727. /// Check if two expressions refer to the same declaration.
  6728. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  6729. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  6730. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  6731. return D1->getDecl() == D2->getDecl();
  6732. return false;
  6733. }
  6734. static const Expr *getStrlenExprArg(const Expr *E) {
  6735. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  6736. const FunctionDecl *FD = CE->getDirectCallee();
  6737. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  6738. return nullptr;
  6739. return CE->getArg(0)->IgnoreParenCasts();
  6740. }
  6741. return nullptr;
  6742. }
  6743. // Warn on anti-patterns as the 'size' argument to strncat.
  6744. // The correct size argument should look like following:
  6745. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  6746. void Sema::CheckStrncatArguments(const CallExpr *CE,
  6747. IdentifierInfo *FnName) {
  6748. // Don't crash if the user has the wrong number of arguments.
  6749. if (CE->getNumArgs() < 3)
  6750. return;
  6751. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  6752. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  6753. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  6754. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
  6755. CE->getRParenLoc()))
  6756. return;
  6757. // Identify common expressions, which are wrongly used as the size argument
  6758. // to strncat and may lead to buffer overflows.
  6759. unsigned PatternType = 0;
  6760. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  6761. // - sizeof(dst)
  6762. if (referToTheSameDecl(SizeOfArg, DstArg))
  6763. PatternType = 1;
  6764. // - sizeof(src)
  6765. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  6766. PatternType = 2;
  6767. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  6768. if (BE->getOpcode() == BO_Sub) {
  6769. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  6770. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  6771. // - sizeof(dst) - strlen(dst)
  6772. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  6773. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  6774. PatternType = 1;
  6775. // - sizeof(src) - (anything)
  6776. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  6777. PatternType = 2;
  6778. }
  6779. }
  6780. if (PatternType == 0)
  6781. return;
  6782. // Generate the diagnostic.
  6783. SourceLocation SL = LenArg->getLocStart();
  6784. SourceRange SR = LenArg->getSourceRange();
  6785. SourceManager &SM = getSourceManager();
  6786. // If the function is defined as a builtin macro, do not show macro expansion.
  6787. if (SM.isMacroArgExpansion(SL)) {
  6788. SL = SM.getSpellingLoc(SL);
  6789. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  6790. SM.getSpellingLoc(SR.getEnd()));
  6791. }
  6792. // Check if the destination is an array (rather than a pointer to an array).
  6793. QualType DstTy = DstArg->getType();
  6794. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  6795. Context);
  6796. if (!isKnownSizeArray) {
  6797. if (PatternType == 1)
  6798. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  6799. else
  6800. Diag(SL, diag::warn_strncat_src_size) << SR;
  6801. return;
  6802. }
  6803. if (PatternType == 1)
  6804. Diag(SL, diag::warn_strncat_large_size) << SR;
  6805. else
  6806. Diag(SL, diag::warn_strncat_src_size) << SR;
  6807. SmallString<128> sizeString;
  6808. llvm::raw_svector_ostream OS(sizeString);
  6809. OS << "sizeof(";
  6810. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  6811. OS << ") - ";
  6812. OS << "strlen(";
  6813. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  6814. OS << ") - 1";
  6815. Diag(SL, diag::note_strncat_wrong_size)
  6816. << FixItHint::CreateReplacement(SR, OS.str());
  6817. }
  6818. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  6819. static const Expr *EvalVal(const Expr *E,
  6820. SmallVectorImpl<const DeclRefExpr *> &refVars,
  6821. const Decl *ParentDecl);
  6822. static const Expr *EvalAddr(const Expr *E,
  6823. SmallVectorImpl<const DeclRefExpr *> &refVars,
  6824. const Decl *ParentDecl);
  6825. /// CheckReturnStackAddr - Check if a return statement returns the address
  6826. /// of a stack variable.
  6827. static void
  6828. CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
  6829. SourceLocation ReturnLoc) {
  6830. const Expr *stackE = nullptr;
  6831. SmallVector<const DeclRefExpr *, 8> refVars;
  6832. // Perform checking for returned stack addresses, local blocks,
  6833. // label addresses or references to temporaries.
  6834. if (lhsType->isPointerType() ||
  6835. (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  6836. stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
  6837. } else if (lhsType->isReferenceType()) {
  6838. stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
  6839. }
  6840. if (!stackE)
  6841. return; // Nothing suspicious was found.
  6842. // Parameters are initialized in the calling scope, so taking the address
  6843. // of a parameter reference doesn't need a warning.
  6844. for (auto *DRE : refVars)
  6845. if (isa<ParmVarDecl>(DRE->getDecl()))
  6846. return;
  6847. SourceLocation diagLoc;
  6848. SourceRange diagRange;
  6849. if (refVars.empty()) {
  6850. diagLoc = stackE->getLocStart();
  6851. diagRange = stackE->getSourceRange();
  6852. } else {
  6853. // We followed through a reference variable. 'stackE' contains the
  6854. // problematic expression but we will warn at the return statement pointing
  6855. // at the reference variable. We will later display the "trail" of
  6856. // reference variables using notes.
  6857. diagLoc = refVars[0]->getLocStart();
  6858. diagRange = refVars[0]->getSourceRange();
  6859. }
  6860. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
  6861. // address of local var
  6862. S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
  6863. << DR->getDecl()->getDeclName() << diagRange;
  6864. } else if (isa<BlockExpr>(stackE)) { // local block.
  6865. S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  6866. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  6867. S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  6868. } else { // local temporary.
  6869. // If there is an LValue->RValue conversion, then the value of the
  6870. // reference type is used, not the reference.
  6871. if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
  6872. if (ICE->getCastKind() == CK_LValueToRValue) {
  6873. return;
  6874. }
  6875. }
  6876. S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
  6877. << lhsType->isReferenceType() << diagRange;
  6878. }
  6879. // Display the "trail" of reference variables that we followed until we
  6880. // found the problematic expression using notes.
  6881. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  6882. const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  6883. // If this var binds to another reference var, show the range of the next
  6884. // var, otherwise the var binds to the problematic expression, in which case
  6885. // show the range of the expression.
  6886. SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
  6887. : stackE->getSourceRange();
  6888. S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  6889. << VD->getDeclName() << range;
  6890. }
  6891. }
  6892. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  6893. /// check if the expression in a return statement evaluates to an address
  6894. /// to a location on the stack, a local block, an address of a label, or a
  6895. /// reference to local temporary. The recursion is used to traverse the
  6896. /// AST of the return expression, with recursion backtracking when we
  6897. /// encounter a subexpression that (1) clearly does not lead to one of the
  6898. /// above problematic expressions (2) is something we cannot determine leads to
  6899. /// a problematic expression based on such local checking.
  6900. ///
  6901. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  6902. /// the expression that they point to. Such variables are added to the
  6903. /// 'refVars' vector so that we know what the reference variable "trail" was.
  6904. ///
  6905. /// EvalAddr processes expressions that are pointers that are used as
  6906. /// references (and not L-values). EvalVal handles all other values.
  6907. /// At the base case of the recursion is a check for the above problematic
  6908. /// expressions.
  6909. ///
  6910. /// This implementation handles:
  6911. ///
  6912. /// * pointer-to-pointer casts
  6913. /// * implicit conversions from array references to pointers
  6914. /// * taking the address of fields
  6915. /// * arbitrary interplay between "&" and "*" operators
  6916. /// * pointer arithmetic from an address of a stack variable
  6917. /// * taking the address of an array element where the array is on the stack
  6918. static const Expr *EvalAddr(const Expr *E,
  6919. SmallVectorImpl<const DeclRefExpr *> &refVars,
  6920. const Decl *ParentDecl) {
  6921. if (E->isTypeDependent())
  6922. return nullptr;
  6923. // We should only be called for evaluating pointer expressions.
  6924. assert((E->getType()->isAnyPointerType() ||
  6925. E->getType()->isBlockPointerType() ||
  6926. E->getType()->isObjCQualifiedIdType()) &&
  6927. "EvalAddr only works on pointers");
  6928. E = E->IgnoreParens();
  6929. // Our "symbolic interpreter" is just a dispatch off the currently
  6930. // viewed AST node. We then recursively traverse the AST by calling
  6931. // EvalAddr and EvalVal appropriately.
  6932. switch (E->getStmtClass()) {
  6933. case Stmt::DeclRefExprClass: {
  6934. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  6935. // If we leave the immediate function, the lifetime isn't about to end.
  6936. if (DR->refersToEnclosingVariableOrCapture())
  6937. return nullptr;
  6938. if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  6939. // If this is a reference variable, follow through to the expression that
  6940. // it points to.
  6941. if (V->hasLocalStorage() &&
  6942. V->getType()->isReferenceType() && V->hasInit()) {
  6943. // Add the reference variable to the "trail".
  6944. refVars.push_back(DR);
  6945. return EvalAddr(V->getInit(), refVars, ParentDecl);
  6946. }
  6947. return nullptr;
  6948. }
  6949. case Stmt::UnaryOperatorClass: {
  6950. // The only unary operator that make sense to handle here
  6951. // is AddrOf. All others don't make sense as pointers.
  6952. const UnaryOperator *U = cast<UnaryOperator>(E);
  6953. if (U->getOpcode() == UO_AddrOf)
  6954. return EvalVal(U->getSubExpr(), refVars, ParentDecl);
  6955. return nullptr;
  6956. }
  6957. case Stmt::BinaryOperatorClass: {
  6958. // Handle pointer arithmetic. All other binary operators are not valid
  6959. // in this context.
  6960. const BinaryOperator *B = cast<BinaryOperator>(E);
  6961. BinaryOperatorKind op = B->getOpcode();
  6962. if (op != BO_Add && op != BO_Sub)
  6963. return nullptr;
  6964. const Expr *Base = B->getLHS();
  6965. // Determine which argument is the real pointer base. It could be
  6966. // the RHS argument instead of the LHS.
  6967. if (!Base->getType()->isPointerType())
  6968. Base = B->getRHS();
  6969. assert(Base->getType()->isPointerType());
  6970. return EvalAddr(Base, refVars, ParentDecl);
  6971. }
  6972. // For conditional operators we need to see if either the LHS or RHS are
  6973. // valid DeclRefExpr*s. If one of them is valid, we return it.
  6974. case Stmt::ConditionalOperatorClass: {
  6975. const ConditionalOperator *C = cast<ConditionalOperator>(E);
  6976. // Handle the GNU extension for missing LHS.
  6977. // FIXME: That isn't a ConditionalOperator, so doesn't get here.
  6978. if (const Expr *LHSExpr = C->getLHS()) {
  6979. // In C++, we can have a throw-expression, which has 'void' type.
  6980. if (!LHSExpr->getType()->isVoidType())
  6981. if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
  6982. return LHS;
  6983. }
  6984. // In C++, we can have a throw-expression, which has 'void' type.
  6985. if (C->getRHS()->getType()->isVoidType())
  6986. return nullptr;
  6987. return EvalAddr(C->getRHS(), refVars, ParentDecl);
  6988. }
  6989. case Stmt::BlockExprClass:
  6990. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  6991. return E; // local block.
  6992. return nullptr;
  6993. case Stmt::AddrLabelExprClass:
  6994. return E; // address of label.
  6995. case Stmt::ExprWithCleanupsClass:
  6996. return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  6997. ParentDecl);
  6998. // For casts, we need to handle conversions from arrays to
  6999. // pointer values, and pointer-to-pointer conversions.
  7000. case Stmt::ImplicitCastExprClass:
  7001. case Stmt::CStyleCastExprClass:
  7002. case Stmt::CXXFunctionalCastExprClass:
  7003. case Stmt::ObjCBridgedCastExprClass:
  7004. case Stmt::CXXStaticCastExprClass:
  7005. case Stmt::CXXDynamicCastExprClass:
  7006. case Stmt::CXXConstCastExprClass:
  7007. case Stmt::CXXReinterpretCastExprClass: {
  7008. const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  7009. switch (cast<CastExpr>(E)->getCastKind()) {
  7010. case CK_LValueToRValue:
  7011. case CK_NoOp:
  7012. case CK_BaseToDerived:
  7013. case CK_DerivedToBase:
  7014. case CK_UncheckedDerivedToBase:
  7015. case CK_Dynamic:
  7016. case CK_CPointerToObjCPointerCast:
  7017. case CK_BlockPointerToObjCPointerCast:
  7018. case CK_AnyPointerToBlockPointerCast:
  7019. return EvalAddr(SubExpr, refVars, ParentDecl);
  7020. case CK_ArrayToPointerDecay:
  7021. return EvalVal(SubExpr, refVars, ParentDecl);
  7022. case CK_BitCast:
  7023. if (SubExpr->getType()->isAnyPointerType() ||
  7024. SubExpr->getType()->isBlockPointerType() ||
  7025. SubExpr->getType()->isObjCQualifiedIdType())
  7026. return EvalAddr(SubExpr, refVars, ParentDecl);
  7027. else
  7028. return nullptr;
  7029. default:
  7030. return nullptr;
  7031. }
  7032. }
  7033. case Stmt::MaterializeTemporaryExprClass:
  7034. if (const Expr *Result =
  7035. EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  7036. refVars, ParentDecl))
  7037. return Result;
  7038. return E;
  7039. // Everything else: we simply don't reason about them.
  7040. default:
  7041. return nullptr;
  7042. }
  7043. }
  7044. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  7045. /// See the comments for EvalAddr for more details.
  7046. static const Expr *EvalVal(const Expr *E,
  7047. SmallVectorImpl<const DeclRefExpr *> &refVars,
  7048. const Decl *ParentDecl) {
  7049. do {
  7050. // We should only be called for evaluating non-pointer expressions, or
  7051. // expressions with a pointer type that are not used as references but
  7052. // instead
  7053. // are l-values (e.g., DeclRefExpr with a pointer type).
  7054. // Our "symbolic interpreter" is just a dispatch off the currently
  7055. // viewed AST node. We then recursively traverse the AST by calling
  7056. // EvalAddr and EvalVal appropriately.
  7057. E = E->IgnoreParens();
  7058. switch (E->getStmtClass()) {
  7059. case Stmt::ImplicitCastExprClass: {
  7060. const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  7061. if (IE->getValueKind() == VK_LValue) {
  7062. E = IE->getSubExpr();
  7063. continue;
  7064. }
  7065. return nullptr;
  7066. }
  7067. case Stmt::ExprWithCleanupsClass:
  7068. return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  7069. ParentDecl);
  7070. case Stmt::DeclRefExprClass: {
  7071. // When we hit a DeclRefExpr we are looking at code that refers to a
  7072. // variable's name. If it's not a reference variable we check if it has
  7073. // local storage within the function, and if so, return the expression.
  7074. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  7075. // If we leave the immediate function, the lifetime isn't about to end.
  7076. if (DR->refersToEnclosingVariableOrCapture())
  7077. return nullptr;
  7078. if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
  7079. // Check if it refers to itself, e.g. "int& i = i;".
  7080. if (V == ParentDecl)
  7081. return DR;
  7082. if (V->hasLocalStorage()) {
  7083. if (!V->getType()->isReferenceType())
  7084. return DR;
  7085. // Reference variable, follow through to the expression that
  7086. // it points to.
  7087. if (V->hasInit()) {
  7088. // Add the reference variable to the "trail".
  7089. refVars.push_back(DR);
  7090. return EvalVal(V->getInit(), refVars, V);
  7091. }
  7092. }
  7093. }
  7094. return nullptr;
  7095. }
  7096. case Stmt::UnaryOperatorClass: {
  7097. // The only unary operator that make sense to handle here
  7098. // is Deref. All others don't resolve to a "name." This includes
  7099. // handling all sorts of rvalues passed to a unary operator.
  7100. const UnaryOperator *U = cast<UnaryOperator>(E);
  7101. if (U->getOpcode() == UO_Deref)
  7102. return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
  7103. return nullptr;
  7104. }
  7105. case Stmt::ArraySubscriptExprClass: {
  7106. // Array subscripts are potential references to data on the stack. We
  7107. // retrieve the DeclRefExpr* for the array variable if it indeed
  7108. // has local storage.
  7109. const auto *ASE = cast<ArraySubscriptExpr>(E);
  7110. if (ASE->isTypeDependent())
  7111. return nullptr;
  7112. return EvalAddr(ASE->getBase(), refVars, ParentDecl);
  7113. }
  7114. case Stmt::OMPArraySectionExprClass: {
  7115. return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
  7116. ParentDecl);
  7117. }
  7118. case Stmt::ConditionalOperatorClass: {
  7119. // For conditional operators we need to see if either the LHS or RHS are
  7120. // non-NULL Expr's. If one is non-NULL, we return it.
  7121. const ConditionalOperator *C = cast<ConditionalOperator>(E);
  7122. // Handle the GNU extension for missing LHS.
  7123. if (const Expr *LHSExpr = C->getLHS()) {
  7124. // In C++, we can have a throw-expression, which has 'void' type.
  7125. if (!LHSExpr->getType()->isVoidType())
  7126. if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
  7127. return LHS;
  7128. }
  7129. // In C++, we can have a throw-expression, which has 'void' type.
  7130. if (C->getRHS()->getType()->isVoidType())
  7131. return nullptr;
  7132. return EvalVal(C->getRHS(), refVars, ParentDecl);
  7133. }
  7134. // Accesses to members are potential references to data on the stack.
  7135. case Stmt::MemberExprClass: {
  7136. const MemberExpr *M = cast<MemberExpr>(E);
  7137. // Check for indirect access. We only want direct field accesses.
  7138. if (M->isArrow())
  7139. return nullptr;
  7140. // Check whether the member type is itself a reference, in which case
  7141. // we're not going to refer to the member, but to what the member refers
  7142. // to.
  7143. if (M->getMemberDecl()->getType()->isReferenceType())
  7144. return nullptr;
  7145. return EvalVal(M->getBase(), refVars, ParentDecl);
  7146. }
  7147. case Stmt::MaterializeTemporaryExprClass:
  7148. if (const Expr *Result =
  7149. EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  7150. refVars, ParentDecl))
  7151. return Result;
  7152. return E;
  7153. default:
  7154. // Check that we don't return or take the address of a reference to a
  7155. // temporary. This is only useful in C++.
  7156. if (!E->isTypeDependent() && E->isRValue())
  7157. return E;
  7158. // Everything else: we simply don't reason about them.
  7159. return nullptr;
  7160. }
  7161. } while (true);
  7162. }
  7163. void
  7164. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  7165. SourceLocation ReturnLoc,
  7166. bool isObjCMethod,
  7167. const AttrVec *Attrs,
  7168. const FunctionDecl *FD) {
  7169. CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
  7170. // Check if the return value is null but should not be.
  7171. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  7172. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  7173. CheckNonNullExpr(*this, RetValExp))
  7174. Diag(ReturnLoc, diag::warn_null_ret)
  7175. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  7176. // C++11 [basic.stc.dynamic.allocation]p4:
  7177. // If an allocation function declared with a non-throwing
  7178. // exception-specification fails to allocate storage, it shall return
  7179. // a null pointer. Any other allocation function that fails to allocate
  7180. // storage shall indicate failure only by throwing an exception [...]
  7181. if (FD) {
  7182. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  7183. if (Op == OO_New || Op == OO_Array_New) {
  7184. const FunctionProtoType *Proto
  7185. = FD->getType()->castAs<FunctionProtoType>();
  7186. if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
  7187. CheckNonNullExpr(*this, RetValExp))
  7188. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  7189. << FD << getLangOpts().CPlusPlus11;
  7190. }
  7191. }
  7192. }
  7193. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  7194. /// Check for comparisons of floating point operands using != and ==.
  7195. /// Issue a warning if these are no self-comparisons, as they are not likely
  7196. /// to do what the programmer intended.
  7197. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  7198. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  7199. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  7200. // Special case: check for x == x (which is OK).
  7201. // Do not emit warnings for such cases.
  7202. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  7203. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  7204. if (DRL->getDecl() == DRR->getDecl())
  7205. return;
  7206. // Special case: check for comparisons against literals that can be exactly
  7207. // represented by APFloat. In such cases, do not emit a warning. This
  7208. // is a heuristic: often comparison against such literals are used to
  7209. // detect if a value in a variable has not changed. This clearly can
  7210. // lead to false negatives.
  7211. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  7212. if (FLL->isExact())
  7213. return;
  7214. } else
  7215. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  7216. if (FLR->isExact())
  7217. return;
  7218. // Check for comparisons with builtin types.
  7219. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  7220. if (CL->getBuiltinCallee())
  7221. return;
  7222. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  7223. if (CR->getBuiltinCallee())
  7224. return;
  7225. // Emit the diagnostic.
  7226. Diag(Loc, diag::warn_floatingpoint_eq)
  7227. << LHS->getSourceRange() << RHS->getSourceRange();
  7228. }
  7229. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  7230. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  7231. namespace {
  7232. /// Structure recording the 'active' range of an integer-valued
  7233. /// expression.
  7234. struct IntRange {
  7235. /// The number of bits active in the int.
  7236. unsigned Width;
  7237. /// True if the int is known not to have negative values.
  7238. bool NonNegative;
  7239. IntRange(unsigned Width, bool NonNegative)
  7240. : Width(Width), NonNegative(NonNegative)
  7241. {}
  7242. /// Returns the range of the bool type.
  7243. static IntRange forBoolType() {
  7244. return IntRange(1, true);
  7245. }
  7246. /// Returns the range of an opaque value of the given integral type.
  7247. static IntRange forValueOfType(ASTContext &C, QualType T) {
  7248. return forValueOfCanonicalType(C,
  7249. T->getCanonicalTypeInternal().getTypePtr());
  7250. }
  7251. /// Returns the range of an opaque value of a canonical integral type.
  7252. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  7253. assert(T->isCanonicalUnqualified());
  7254. if (const VectorType *VT = dyn_cast<VectorType>(T))
  7255. T = VT->getElementType().getTypePtr();
  7256. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  7257. T = CT->getElementType().getTypePtr();
  7258. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  7259. T = AT->getValueType().getTypePtr();
  7260. if (!C.getLangOpts().CPlusPlus) {
  7261. // For enum types in C code, use the underlying datatype.
  7262. if (const EnumType *ET = dyn_cast<EnumType>(T))
  7263. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  7264. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  7265. // For enum types in C++, use the known bit width of the enumerators.
  7266. EnumDecl *Enum = ET->getDecl();
  7267. // In C++11, enums without definitions can have an explicitly specified
  7268. // underlying type. Use this type to compute the range.
  7269. if (!Enum->isCompleteDefinition())
  7270. return IntRange(C.getIntWidth(QualType(T, 0)),
  7271. !ET->isSignedIntegerOrEnumerationType());
  7272. unsigned NumPositive = Enum->getNumPositiveBits();
  7273. unsigned NumNegative = Enum->getNumNegativeBits();
  7274. if (NumNegative == 0)
  7275. return IntRange(NumPositive, true/*NonNegative*/);
  7276. else
  7277. return IntRange(std::max(NumPositive + 1, NumNegative),
  7278. false/*NonNegative*/);
  7279. }
  7280. const BuiltinType *BT = cast<BuiltinType>(T);
  7281. assert(BT->isInteger());
  7282. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  7283. }
  7284. /// Returns the "target" range of a canonical integral type, i.e.
  7285. /// the range of values expressible in the type.
  7286. ///
  7287. /// This matches forValueOfCanonicalType except that enums have the
  7288. /// full range of their type, not the range of their enumerators.
  7289. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  7290. assert(T->isCanonicalUnqualified());
  7291. if (const VectorType *VT = dyn_cast<VectorType>(T))
  7292. T = VT->getElementType().getTypePtr();
  7293. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  7294. T = CT->getElementType().getTypePtr();
  7295. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  7296. T = AT->getValueType().getTypePtr();
  7297. if (const EnumType *ET = dyn_cast<EnumType>(T))
  7298. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  7299. const BuiltinType *BT = cast<BuiltinType>(T);
  7300. assert(BT->isInteger());
  7301. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  7302. }
  7303. /// Returns the supremum of two ranges: i.e. their conservative merge.
  7304. static IntRange join(IntRange L, IntRange R) {
  7305. return IntRange(std::max(L.Width, R.Width),
  7306. L.NonNegative && R.NonNegative);
  7307. }
  7308. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  7309. static IntRange meet(IntRange L, IntRange R) {
  7310. return IntRange(std::min(L.Width, R.Width),
  7311. L.NonNegative || R.NonNegative);
  7312. }
  7313. };
  7314. IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
  7315. if (value.isSigned() && value.isNegative())
  7316. return IntRange(value.getMinSignedBits(), false);
  7317. if (value.getBitWidth() > MaxWidth)
  7318. value = value.trunc(MaxWidth);
  7319. // isNonNegative() just checks the sign bit without considering
  7320. // signedness.
  7321. return IntRange(value.getActiveBits(), true);
  7322. }
  7323. IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  7324. unsigned MaxWidth) {
  7325. if (result.isInt())
  7326. return GetValueRange(C, result.getInt(), MaxWidth);
  7327. if (result.isVector()) {
  7328. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  7329. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  7330. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  7331. R = IntRange::join(R, El);
  7332. }
  7333. return R;
  7334. }
  7335. if (result.isComplexInt()) {
  7336. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  7337. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  7338. return IntRange::join(R, I);
  7339. }
  7340. // This can happen with lossless casts to intptr_t of "based" lvalues.
  7341. // Assume it might use arbitrary bits.
  7342. // FIXME: The only reason we need to pass the type in here is to get
  7343. // the sign right on this one case. It would be nice if APValue
  7344. // preserved this.
  7345. assert(result.isLValue() || result.isAddrLabelDiff());
  7346. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  7347. }
  7348. QualType GetExprType(const Expr *E) {
  7349. QualType Ty = E->getType();
  7350. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  7351. Ty = AtomicRHS->getValueType();
  7352. return Ty;
  7353. }
  7354. /// Pseudo-evaluate the given integer expression, estimating the
  7355. /// range of values it might take.
  7356. ///
  7357. /// \param MaxWidth - the width to which the value will be truncated
  7358. IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
  7359. E = E->IgnoreParens();
  7360. // Try a full evaluation first.
  7361. Expr::EvalResult result;
  7362. if (E->EvaluateAsRValue(result, C))
  7363. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  7364. // I think we only want to look through implicit casts here; if the
  7365. // user has an explicit widening cast, we should treat the value as
  7366. // being of the new, wider type.
  7367. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  7368. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  7369. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  7370. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  7371. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  7372. CE->getCastKind() == CK_BooleanToSignedIntegral;
  7373. // Assume that non-integer casts can span the full range of the type.
  7374. if (!isIntegerCast)
  7375. return OutputTypeRange;
  7376. IntRange SubRange
  7377. = GetExprRange(C, CE->getSubExpr(),
  7378. std::min(MaxWidth, OutputTypeRange.Width));
  7379. // Bail out if the subexpr's range is as wide as the cast type.
  7380. if (SubRange.Width >= OutputTypeRange.Width)
  7381. return OutputTypeRange;
  7382. // Otherwise, we take the smaller width, and we're non-negative if
  7383. // either the output type or the subexpr is.
  7384. return IntRange(SubRange.Width,
  7385. SubRange.NonNegative || OutputTypeRange.NonNegative);
  7386. }
  7387. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  7388. // If we can fold the condition, just take that operand.
  7389. bool CondResult;
  7390. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  7391. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  7392. : CO->getFalseExpr(),
  7393. MaxWidth);
  7394. // Otherwise, conservatively merge.
  7395. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  7396. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  7397. return IntRange::join(L, R);
  7398. }
  7399. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  7400. switch (BO->getOpcode()) {
  7401. // Boolean-valued operations are single-bit and positive.
  7402. case BO_LAnd:
  7403. case BO_LOr:
  7404. case BO_LT:
  7405. case BO_GT:
  7406. case BO_LE:
  7407. case BO_GE:
  7408. case BO_EQ:
  7409. case BO_NE:
  7410. return IntRange::forBoolType();
  7411. // The type of the assignments is the type of the LHS, so the RHS
  7412. // is not necessarily the same type.
  7413. case BO_MulAssign:
  7414. case BO_DivAssign:
  7415. case BO_RemAssign:
  7416. case BO_AddAssign:
  7417. case BO_SubAssign:
  7418. case BO_XorAssign:
  7419. case BO_OrAssign:
  7420. // TODO: bitfields?
  7421. return IntRange::forValueOfType(C, GetExprType(E));
  7422. // Simple assignments just pass through the RHS, which will have
  7423. // been coerced to the LHS type.
  7424. case BO_Assign:
  7425. // TODO: bitfields?
  7426. return GetExprRange(C, BO->getRHS(), MaxWidth);
  7427. // Operations with opaque sources are black-listed.
  7428. case BO_PtrMemD:
  7429. case BO_PtrMemI:
  7430. return IntRange::forValueOfType(C, GetExprType(E));
  7431. // Bitwise-and uses the *infinum* of the two source ranges.
  7432. case BO_And:
  7433. case BO_AndAssign:
  7434. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  7435. GetExprRange(C, BO->getRHS(), MaxWidth));
  7436. // Left shift gets black-listed based on a judgement call.
  7437. case BO_Shl:
  7438. // ...except that we want to treat '1 << (blah)' as logically
  7439. // positive. It's an important idiom.
  7440. if (IntegerLiteral *I
  7441. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  7442. if (I->getValue() == 1) {
  7443. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  7444. return IntRange(R.Width, /*NonNegative*/ true);
  7445. }
  7446. }
  7447. // fallthrough
  7448. case BO_ShlAssign:
  7449. return IntRange::forValueOfType(C, GetExprType(E));
  7450. // Right shift by a constant can narrow its left argument.
  7451. case BO_Shr:
  7452. case BO_ShrAssign: {
  7453. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  7454. // If the shift amount is a positive constant, drop the width by
  7455. // that much.
  7456. llvm::APSInt shift;
  7457. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  7458. shift.isNonNegative()) {
  7459. unsigned zext = shift.getZExtValue();
  7460. if (zext >= L.Width)
  7461. L.Width = (L.NonNegative ? 0 : 1);
  7462. else
  7463. L.Width -= zext;
  7464. }
  7465. return L;
  7466. }
  7467. // Comma acts as its right operand.
  7468. case BO_Comma:
  7469. return GetExprRange(C, BO->getRHS(), MaxWidth);
  7470. // Black-list pointer subtractions.
  7471. case BO_Sub:
  7472. if (BO->getLHS()->getType()->isPointerType())
  7473. return IntRange::forValueOfType(C, GetExprType(E));
  7474. break;
  7475. // The width of a division result is mostly determined by the size
  7476. // of the LHS.
  7477. case BO_Div: {
  7478. // Don't 'pre-truncate' the operands.
  7479. unsigned opWidth = C.getIntWidth(GetExprType(E));
  7480. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  7481. // If the divisor is constant, use that.
  7482. llvm::APSInt divisor;
  7483. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  7484. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  7485. if (log2 >= L.Width)
  7486. L.Width = (L.NonNegative ? 0 : 1);
  7487. else
  7488. L.Width = std::min(L.Width - log2, MaxWidth);
  7489. return L;
  7490. }
  7491. // Otherwise, just use the LHS's width.
  7492. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  7493. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  7494. }
  7495. // The result of a remainder can't be larger than the result of
  7496. // either side.
  7497. case BO_Rem: {
  7498. // Don't 'pre-truncate' the operands.
  7499. unsigned opWidth = C.getIntWidth(GetExprType(E));
  7500. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  7501. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  7502. IntRange meet = IntRange::meet(L, R);
  7503. meet.Width = std::min(meet.Width, MaxWidth);
  7504. return meet;
  7505. }
  7506. // The default behavior is okay for these.
  7507. case BO_Mul:
  7508. case BO_Add:
  7509. case BO_Xor:
  7510. case BO_Or:
  7511. break;
  7512. }
  7513. // The default case is to treat the operation as if it were closed
  7514. // on the narrowest type that encompasses both operands.
  7515. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  7516. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  7517. return IntRange::join(L, R);
  7518. }
  7519. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  7520. switch (UO->getOpcode()) {
  7521. // Boolean-valued operations are white-listed.
  7522. case UO_LNot:
  7523. return IntRange::forBoolType();
  7524. // Operations with opaque sources are black-listed.
  7525. case UO_Deref:
  7526. case UO_AddrOf: // should be impossible
  7527. return IntRange::forValueOfType(C, GetExprType(E));
  7528. default:
  7529. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  7530. }
  7531. }
  7532. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  7533. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
  7534. if (const auto *BitField = E->getSourceBitField())
  7535. return IntRange(BitField->getBitWidthValue(C),
  7536. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  7537. return IntRange::forValueOfType(C, GetExprType(E));
  7538. }
  7539. IntRange GetExprRange(ASTContext &C, const Expr *E) {
  7540. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
  7541. }
  7542. /// Checks whether the given value, which currently has the given
  7543. /// source semantics, has the same value when coerced through the
  7544. /// target semantics.
  7545. bool IsSameFloatAfterCast(const llvm::APFloat &value,
  7546. const llvm::fltSemantics &Src,
  7547. const llvm::fltSemantics &Tgt) {
  7548. llvm::APFloat truncated = value;
  7549. bool ignored;
  7550. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  7551. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  7552. return truncated.bitwiseIsEqual(value);
  7553. }
  7554. /// Checks whether the given value, which currently has the given
  7555. /// source semantics, has the same value when coerced through the
  7556. /// target semantics.
  7557. ///
  7558. /// The value might be a vector of floats (or a complex number).
  7559. bool IsSameFloatAfterCast(const APValue &value,
  7560. const llvm::fltSemantics &Src,
  7561. const llvm::fltSemantics &Tgt) {
  7562. if (value.isFloat())
  7563. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  7564. if (value.isVector()) {
  7565. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  7566. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  7567. return false;
  7568. return true;
  7569. }
  7570. assert(value.isComplexFloat());
  7571. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  7572. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  7573. }
  7574. void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  7575. bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  7576. // Suppress cases where we are comparing against an enum constant.
  7577. if (const DeclRefExpr *DR =
  7578. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  7579. if (isa<EnumConstantDecl>(DR->getDecl()))
  7580. return true;
  7581. // Suppress cases where the '0' value is expanded from a macro.
  7582. if (E->getLocStart().isMacroID())
  7583. return true;
  7584. return false;
  7585. }
  7586. bool isNonBooleanIntegerValue(Expr *E) {
  7587. return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType();
  7588. }
  7589. bool isNonBooleanUnsignedValue(Expr *E) {
  7590. // We are checking that the expression is not known to have boolean value,
  7591. // is an integer type; and is either unsigned after implicit casts,
  7592. // or was unsigned before implicit casts.
  7593. return isNonBooleanIntegerValue(E) &&
  7594. (!E->getType()->isSignedIntegerType() ||
  7595. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  7596. }
  7597. enum class LimitType {
  7598. Max = 1U << 0U, // e.g. 32767 for short
  7599. Min = 1U << 1U, // e.g. -32768 for short
  7600. Both = Max | Min // When the value is both the Min and the Max limit at the
  7601. // same time; e.g. in C++, A::a in enum A { a = 0 };
  7602. };
  7603. /// Checks whether Expr 'Constant' may be the
  7604. /// std::numeric_limits<>::max() or std::numeric_limits<>::min()
  7605. /// of the Expr 'Other'. If true, then returns the limit type (min or max).
  7606. /// The Value is the evaluation of Constant
  7607. llvm::Optional<LimitType> IsTypeLimit(Sema &S, Expr *Constant, Expr *Other,
  7608. const llvm::APSInt &Value) {
  7609. if (IsEnumConstOrFromMacro(S, Constant))
  7610. return llvm::Optional<LimitType>();
  7611. if (isNonBooleanUnsignedValue(Other) && Value == 0)
  7612. return LimitType::Min;
  7613. // TODO: Investigate using GetExprRange() to get tighter bounds
  7614. // on the bit ranges.
  7615. QualType OtherT = Other->IgnoreParenImpCasts()->getType();
  7616. if (const auto *AT = OtherT->getAs<AtomicType>())
  7617. OtherT = AT->getValueType();
  7618. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  7619. // Special-case for C++ for enum with one enumerator with value of 0.
  7620. if (OtherRange.Width == 0)
  7621. return Value == 0 ? LimitType::Both : llvm::Optional<LimitType>();
  7622. if (llvm::APSInt::isSameValue(
  7623. llvm::APSInt::getMaxValue(OtherRange.Width,
  7624. OtherT->isUnsignedIntegerType()),
  7625. Value))
  7626. return LimitType::Max;
  7627. if (llvm::APSInt::isSameValue(
  7628. llvm::APSInt::getMinValue(OtherRange.Width,
  7629. OtherT->isUnsignedIntegerType()),
  7630. Value))
  7631. return LimitType::Min;
  7632. return llvm::None;
  7633. }
  7634. bool HasEnumType(Expr *E) {
  7635. // Strip off implicit integral promotions.
  7636. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  7637. if (ICE->getCastKind() != CK_IntegralCast &&
  7638. ICE->getCastKind() != CK_NoOp)
  7639. break;
  7640. E = ICE->getSubExpr();
  7641. }
  7642. return E->getType()->isEnumeralType();
  7643. }
  7644. bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant,
  7645. Expr *Other, const llvm::APSInt &Value,
  7646. bool RhsConstant) {
  7647. // Disable warning in template instantiations
  7648. // and only analyze <, >, <= and >= operations.
  7649. if (S.inTemplateInstantiation() || !E->isRelationalOp())
  7650. return false;
  7651. BinaryOperatorKind Op = E->getOpcode();
  7652. QualType OType = Other->IgnoreParenImpCasts()->getType();
  7653. llvm::Optional<LimitType> ValueType; // Which limit (min/max) is the constant?
  7654. if (!(isNonBooleanIntegerValue(Other) &&
  7655. (ValueType = IsTypeLimit(S, Constant, Other, Value))))
  7656. return false;
  7657. bool ConstIsLowerBound = (Op == BO_LT || Op == BO_LE) ^ RhsConstant;
  7658. bool ResultWhenConstEqualsOther = (Op == BO_LE || Op == BO_GE);
  7659. if (ValueType != LimitType::Both) {
  7660. bool ResultWhenConstNeOther =
  7661. ConstIsLowerBound ^ (ValueType == LimitType::Max);
  7662. if (ResultWhenConstEqualsOther != ResultWhenConstNeOther)
  7663. return false; // The comparison is not tautological.
  7664. } else if (ResultWhenConstEqualsOther == ConstIsLowerBound)
  7665. return false; // The comparison is not tautological.
  7666. const bool Result = ResultWhenConstEqualsOther;
  7667. unsigned Diag = (isNonBooleanUnsignedValue(Other) && Value == 0)
  7668. ? (HasEnumType(Other)
  7669. ? diag::warn_unsigned_enum_always_true_comparison
  7670. : diag::warn_unsigned_always_true_comparison)
  7671. : diag::warn_tautological_constant_compare;
  7672. // Should be enough for uint128 (39 decimal digits)
  7673. SmallString<64> PrettySourceValue;
  7674. llvm::raw_svector_ostream OS(PrettySourceValue);
  7675. OS << Value;
  7676. S.Diag(E->getOperatorLoc(), Diag)
  7677. << RhsConstant << OType << E->getOpcodeStr() << OS.str() << Result
  7678. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  7679. return true;
  7680. }
  7681. bool DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
  7682. Expr *Other, const llvm::APSInt &Value,
  7683. bool RhsConstant) {
  7684. // Disable warning in template instantiations.
  7685. if (S.inTemplateInstantiation())
  7686. return false;
  7687. Constant = Constant->IgnoreParenImpCasts();
  7688. Other = Other->IgnoreParenImpCasts();
  7689. // TODO: Investigate using GetExprRange() to get tighter bounds
  7690. // on the bit ranges.
  7691. QualType OtherT = Other->getType();
  7692. if (const auto *AT = OtherT->getAs<AtomicType>())
  7693. OtherT = AT->getValueType();
  7694. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  7695. unsigned OtherWidth = OtherRange.Width;
  7696. bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
  7697. BinaryOperatorKind op = E->getOpcode();
  7698. bool IsTrue = true;
  7699. // Used for diagnostic printout.
  7700. enum {
  7701. LiteralConstant = 0,
  7702. CXXBoolLiteralTrue,
  7703. CXXBoolLiteralFalse
  7704. } LiteralOrBoolConstant = LiteralConstant;
  7705. if (!OtherIsBooleanType) {
  7706. QualType ConstantT = Constant->getType();
  7707. QualType CommonT = E->getLHS()->getType();
  7708. if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
  7709. return false;
  7710. assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
  7711. "comparison with non-integer type");
  7712. bool ConstantSigned = ConstantT->isSignedIntegerType();
  7713. bool CommonSigned = CommonT->isSignedIntegerType();
  7714. bool EqualityOnly = false;
  7715. if (CommonSigned) {
  7716. // The common type is signed, therefore no signed to unsigned conversion.
  7717. if (!OtherRange.NonNegative) {
  7718. // Check that the constant is representable in type OtherT.
  7719. if (ConstantSigned) {
  7720. if (OtherWidth >= Value.getMinSignedBits())
  7721. return false;
  7722. } else { // !ConstantSigned
  7723. if (OtherWidth >= Value.getActiveBits() + 1)
  7724. return false;
  7725. }
  7726. } else { // !OtherSigned
  7727. // Check that the constant is representable in type OtherT.
  7728. // Negative values are out of range.
  7729. if (ConstantSigned) {
  7730. if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
  7731. return false;
  7732. } else { // !ConstantSigned
  7733. if (OtherWidth >= Value.getActiveBits())
  7734. return false;
  7735. }
  7736. }
  7737. } else { // !CommonSigned
  7738. if (OtherRange.NonNegative) {
  7739. if (OtherWidth >= Value.getActiveBits())
  7740. return false;
  7741. } else { // OtherSigned
  7742. assert(!ConstantSigned &&
  7743. "Two signed types converted to unsigned types.");
  7744. // Check to see if the constant is representable in OtherT.
  7745. if (OtherWidth > Value.getActiveBits())
  7746. return false;
  7747. // Check to see if the constant is equivalent to a negative value
  7748. // cast to CommonT.
  7749. if (S.Context.getIntWidth(ConstantT) ==
  7750. S.Context.getIntWidth(CommonT) &&
  7751. Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
  7752. return false;
  7753. // The constant value rests between values that OtherT can represent
  7754. // after conversion. Relational comparison still works, but equality
  7755. // comparisons will be tautological.
  7756. EqualityOnly = true;
  7757. }
  7758. }
  7759. bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
  7760. if (op == BO_EQ || op == BO_NE) {
  7761. IsTrue = op == BO_NE;
  7762. } else if (EqualityOnly) {
  7763. return false;
  7764. } else if (RhsConstant) {
  7765. if (op == BO_GT || op == BO_GE)
  7766. IsTrue = !PositiveConstant;
  7767. else // op == BO_LT || op == BO_LE
  7768. IsTrue = PositiveConstant;
  7769. } else {
  7770. if (op == BO_LT || op == BO_LE)
  7771. IsTrue = !PositiveConstant;
  7772. else // op == BO_GT || op == BO_GE
  7773. IsTrue = PositiveConstant;
  7774. }
  7775. } else {
  7776. // Other isKnownToHaveBooleanValue
  7777. enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
  7778. enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
  7779. enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
  7780. static const struct LinkedConditions {
  7781. CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
  7782. CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
  7783. CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
  7784. CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
  7785. CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
  7786. CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
  7787. } TruthTable = {
  7788. // Constant on LHS. | Constant on RHS. |
  7789. // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
  7790. { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
  7791. { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
  7792. { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
  7793. { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
  7794. { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
  7795. { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
  7796. };
  7797. bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
  7798. enum ConstantValue ConstVal = Zero;
  7799. if (Value.isUnsigned() || Value.isNonNegative()) {
  7800. if (Value == 0) {
  7801. LiteralOrBoolConstant =
  7802. ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
  7803. ConstVal = Zero;
  7804. } else if (Value == 1) {
  7805. LiteralOrBoolConstant =
  7806. ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
  7807. ConstVal = One;
  7808. } else {
  7809. LiteralOrBoolConstant = LiteralConstant;
  7810. ConstVal = GT_One;
  7811. }
  7812. } else {
  7813. ConstVal = LT_Zero;
  7814. }
  7815. CompareBoolWithConstantResult CmpRes;
  7816. switch (op) {
  7817. case BO_LT:
  7818. CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
  7819. break;
  7820. case BO_GT:
  7821. CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
  7822. break;
  7823. case BO_LE:
  7824. CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
  7825. break;
  7826. case BO_GE:
  7827. CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
  7828. break;
  7829. case BO_EQ:
  7830. CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
  7831. break;
  7832. case BO_NE:
  7833. CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
  7834. break;
  7835. default:
  7836. CmpRes = Unkwn;
  7837. break;
  7838. }
  7839. if (CmpRes == AFals) {
  7840. IsTrue = false;
  7841. } else if (CmpRes == ATrue) {
  7842. IsTrue = true;
  7843. } else {
  7844. return false;
  7845. }
  7846. }
  7847. // If this is a comparison to an enum constant, include that
  7848. // constant in the diagnostic.
  7849. const EnumConstantDecl *ED = nullptr;
  7850. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  7851. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  7852. SmallString<64> PrettySourceValue;
  7853. llvm::raw_svector_ostream OS(PrettySourceValue);
  7854. if (ED)
  7855. OS << '\'' << *ED << "' (" << Value << ")";
  7856. else
  7857. OS << Value;
  7858. S.DiagRuntimeBehavior(
  7859. E->getOperatorLoc(), E,
  7860. S.PDiag(diag::warn_out_of_range_compare)
  7861. << OS.str() << LiteralOrBoolConstant
  7862. << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
  7863. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  7864. return true;
  7865. }
  7866. /// Analyze the operands of the given comparison. Implements the
  7867. /// fallback case from AnalyzeComparison.
  7868. void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  7869. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  7870. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  7871. }
  7872. /// \brief Implements -Wsign-compare.
  7873. ///
  7874. /// \param E the binary operator to check for warnings
  7875. void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  7876. // The type the comparison is being performed in.
  7877. QualType T = E->getLHS()->getType();
  7878. // Only analyze comparison operators where both sides have been converted to
  7879. // the same type.
  7880. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  7881. return AnalyzeImpConvsInComparison(S, E);
  7882. // Don't analyze value-dependent comparisons directly.
  7883. if (E->isValueDependent())
  7884. return AnalyzeImpConvsInComparison(S, E);
  7885. Expr *LHS = E->getLHS();
  7886. Expr *RHS = E->getRHS();
  7887. if (T->isIntegralType(S.Context)) {
  7888. llvm::APSInt RHSValue;
  7889. llvm::APSInt LHSValue;
  7890. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  7891. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  7892. // We don't care about expressions whose result is a constant.
  7893. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  7894. return AnalyzeImpConvsInComparison(S, E);
  7895. // We only care about expressions where just one side is literal
  7896. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  7897. // Is the constant on the RHS or LHS?
  7898. const bool RhsConstant = IsRHSIntegralLiteral;
  7899. Expr *Const = RhsConstant ? RHS : LHS;
  7900. Expr *Other = RhsConstant ? LHS : RHS;
  7901. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  7902. // Check whether an integer constant comparison results in a value
  7903. // of 'true' or 'false'.
  7904. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  7905. return AnalyzeImpConvsInComparison(S, E);
  7906. if (DiagnoseOutOfRangeComparison(S, E, Const, Other, Value, RhsConstant))
  7907. return AnalyzeImpConvsInComparison(S, E);
  7908. }
  7909. }
  7910. if (!T->hasUnsignedIntegerRepresentation()) {
  7911. // We don't do anything special if this isn't an unsigned integral
  7912. // comparison: we're only interested in integral comparisons, and
  7913. // signed comparisons only happen in cases we don't care to warn about.
  7914. return AnalyzeImpConvsInComparison(S, E);
  7915. }
  7916. LHS = LHS->IgnoreParenImpCasts();
  7917. RHS = RHS->IgnoreParenImpCasts();
  7918. // Check to see if one of the (unmodified) operands is of different
  7919. // signedness.
  7920. Expr *signedOperand, *unsignedOperand;
  7921. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  7922. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  7923. "unsigned comparison between two signed integer expressions?");
  7924. signedOperand = LHS;
  7925. unsignedOperand = RHS;
  7926. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  7927. signedOperand = RHS;
  7928. unsignedOperand = LHS;
  7929. } else {
  7930. return AnalyzeImpConvsInComparison(S, E);
  7931. }
  7932. // Otherwise, calculate the effective range of the signed operand.
  7933. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  7934. // Go ahead and analyze implicit conversions in the operands. Note
  7935. // that we skip the implicit conversions on both sides.
  7936. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  7937. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  7938. // If the signed range is non-negative, -Wsign-compare won't fire.
  7939. if (signedRange.NonNegative)
  7940. return;
  7941. // For (in)equality comparisons, if the unsigned operand is a
  7942. // constant which cannot collide with a overflowed signed operand,
  7943. // then reinterpreting the signed operand as unsigned will not
  7944. // change the result of the comparison.
  7945. if (E->isEqualityOp()) {
  7946. unsigned comparisonWidth = S.Context.getIntWidth(T);
  7947. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  7948. // We should never be unable to prove that the unsigned operand is
  7949. // non-negative.
  7950. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  7951. if (unsignedRange.Width < comparisonWidth)
  7952. return;
  7953. }
  7954. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  7955. S.PDiag(diag::warn_mixed_sign_comparison)
  7956. << LHS->getType() << RHS->getType()
  7957. << LHS->getSourceRange() << RHS->getSourceRange());
  7958. }
  7959. /// Analyzes an attempt to assign the given value to a bitfield.
  7960. ///
  7961. /// Returns true if there was something fishy about the attempt.
  7962. bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  7963. SourceLocation InitLoc) {
  7964. assert(Bitfield->isBitField());
  7965. if (Bitfield->isInvalidDecl())
  7966. return false;
  7967. // White-list bool bitfields.
  7968. QualType BitfieldType = Bitfield->getType();
  7969. if (BitfieldType->isBooleanType())
  7970. return false;
  7971. if (BitfieldType->isEnumeralType()) {
  7972. EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
  7973. // If the underlying enum type was not explicitly specified as an unsigned
  7974. // type and the enum contain only positive values, MSVC++ will cause an
  7975. // inconsistency by storing this as a signed type.
  7976. if (S.getLangOpts().CPlusPlus11 &&
  7977. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  7978. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  7979. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  7980. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  7981. << BitfieldEnumDecl->getNameAsString();
  7982. }
  7983. }
  7984. if (Bitfield->getType()->isBooleanType())
  7985. return false;
  7986. // Ignore value- or type-dependent expressions.
  7987. if (Bitfield->getBitWidth()->isValueDependent() ||
  7988. Bitfield->getBitWidth()->isTypeDependent() ||
  7989. Init->isValueDependent() ||
  7990. Init->isTypeDependent())
  7991. return false;
  7992. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  7993. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  7994. llvm::APSInt Value;
  7995. if (!OriginalInit->EvaluateAsInt(Value, S.Context,
  7996. Expr::SE_AllowSideEffects)) {
  7997. // The RHS is not constant. If the RHS has an enum type, make sure the
  7998. // bitfield is wide enough to hold all the values of the enum without
  7999. // truncation.
  8000. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  8001. EnumDecl *ED = EnumTy->getDecl();
  8002. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  8003. // Enum types are implicitly signed on Windows, so check if there are any
  8004. // negative enumerators to see if the enum was intended to be signed or
  8005. // not.
  8006. bool SignedEnum = ED->getNumNegativeBits() > 0;
  8007. // Check for surprising sign changes when assigning enum values to a
  8008. // bitfield of different signedness. If the bitfield is signed and we
  8009. // have exactly the right number of bits to store this unsigned enum,
  8010. // suggest changing the enum to an unsigned type. This typically happens
  8011. // on Windows where unfixed enums always use an underlying type of 'int'.
  8012. unsigned DiagID = 0;
  8013. if (SignedEnum && !SignedBitfield) {
  8014. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  8015. } else if (SignedBitfield && !SignedEnum &&
  8016. ED->getNumPositiveBits() == FieldWidth) {
  8017. DiagID = diag::warn_signed_bitfield_enum_conversion;
  8018. }
  8019. if (DiagID) {
  8020. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  8021. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  8022. SourceRange TypeRange =
  8023. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  8024. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  8025. << SignedEnum << TypeRange;
  8026. }
  8027. // Compute the required bitwidth. If the enum has negative values, we need
  8028. // one more bit than the normal number of positive bits to represent the
  8029. // sign bit.
  8030. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  8031. ED->getNumNegativeBits())
  8032. : ED->getNumPositiveBits();
  8033. // Check the bitwidth.
  8034. if (BitsNeeded > FieldWidth) {
  8035. Expr *WidthExpr = Bitfield->getBitWidth();
  8036. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  8037. << Bitfield << ED;
  8038. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  8039. << BitsNeeded << ED << WidthExpr->getSourceRange();
  8040. }
  8041. }
  8042. return false;
  8043. }
  8044. unsigned OriginalWidth = Value.getBitWidth();
  8045. if (!Value.isSigned() || Value.isNegative())
  8046. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  8047. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  8048. OriginalWidth = Value.getMinSignedBits();
  8049. if (OriginalWidth <= FieldWidth)
  8050. return false;
  8051. // Compute the value which the bitfield will contain.
  8052. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  8053. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  8054. // Check whether the stored value is equal to the original value.
  8055. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  8056. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  8057. return false;
  8058. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  8059. // therefore don't strictly fit into a signed bitfield of width 1.
  8060. if (FieldWidth == 1 && Value == 1)
  8061. return false;
  8062. std::string PrettyValue = Value.toString(10);
  8063. std::string PrettyTrunc = TruncatedValue.toString(10);
  8064. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  8065. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  8066. << Init->getSourceRange();
  8067. return true;
  8068. }
  8069. /// Analyze the given simple or compound assignment for warning-worthy
  8070. /// operations.
  8071. void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  8072. // Just recurse on the LHS.
  8073. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  8074. // We want to recurse on the RHS as normal unless we're assigning to
  8075. // a bitfield.
  8076. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  8077. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  8078. E->getOperatorLoc())) {
  8079. // Recurse, ignoring any implicit conversions on the RHS.
  8080. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  8081. E->getOperatorLoc());
  8082. }
  8083. }
  8084. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  8085. }
  8086. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  8087. void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  8088. SourceLocation CContext, unsigned diag,
  8089. bool pruneControlFlow = false) {
  8090. if (pruneControlFlow) {
  8091. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  8092. S.PDiag(diag)
  8093. << SourceType << T << E->getSourceRange()
  8094. << SourceRange(CContext));
  8095. return;
  8096. }
  8097. S.Diag(E->getExprLoc(), diag)
  8098. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  8099. }
  8100. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  8101. void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
  8102. unsigned diag, bool pruneControlFlow = false) {
  8103. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  8104. }
  8105. /// Diagnose an implicit cast from a floating point value to an integer value.
  8106. void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  8107. SourceLocation CContext) {
  8108. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  8109. const bool PruneWarnings = S.inTemplateInstantiation();
  8110. Expr *InnerE = E->IgnoreParenImpCasts();
  8111. // We also want to warn on, e.g., "int i = -1.234"
  8112. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  8113. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  8114. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  8115. const bool IsLiteral =
  8116. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  8117. llvm::APFloat Value(0.0);
  8118. bool IsConstant =
  8119. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  8120. if (!IsConstant) {
  8121. return DiagnoseImpCast(S, E, T, CContext,
  8122. diag::warn_impcast_float_integer, PruneWarnings);
  8123. }
  8124. bool isExact = false;
  8125. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  8126. T->hasUnsignedIntegerRepresentation());
  8127. if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
  8128. &isExact) == llvm::APFloat::opOK &&
  8129. isExact) {
  8130. if (IsLiteral) return;
  8131. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  8132. PruneWarnings);
  8133. }
  8134. unsigned DiagID = 0;
  8135. if (IsLiteral) {
  8136. // Warn on floating point literal to integer.
  8137. DiagID = diag::warn_impcast_literal_float_to_integer;
  8138. } else if (IntegerValue == 0) {
  8139. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  8140. return DiagnoseImpCast(S, E, T, CContext,
  8141. diag::warn_impcast_float_integer, PruneWarnings);
  8142. }
  8143. // Warn on non-zero to zero conversion.
  8144. DiagID = diag::warn_impcast_float_to_integer_zero;
  8145. } else {
  8146. if (IntegerValue.isUnsigned()) {
  8147. if (!IntegerValue.isMaxValue()) {
  8148. return DiagnoseImpCast(S, E, T, CContext,
  8149. diag::warn_impcast_float_integer, PruneWarnings);
  8150. }
  8151. } else { // IntegerValue.isSigned()
  8152. if (!IntegerValue.isMaxSignedValue() &&
  8153. !IntegerValue.isMinSignedValue()) {
  8154. return DiagnoseImpCast(S, E, T, CContext,
  8155. diag::warn_impcast_float_integer, PruneWarnings);
  8156. }
  8157. }
  8158. // Warn on evaluatable floating point expression to integer conversion.
  8159. DiagID = diag::warn_impcast_float_to_integer;
  8160. }
  8161. // FIXME: Force the precision of the source value down so we don't print
  8162. // digits which are usually useless (we don't really care here if we
  8163. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  8164. // would automatically print the shortest representation, but it's a bit
  8165. // tricky to implement.
  8166. SmallString<16> PrettySourceValue;
  8167. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  8168. precision = (precision * 59 + 195) / 196;
  8169. Value.toString(PrettySourceValue, precision);
  8170. SmallString<16> PrettyTargetValue;
  8171. if (IsBool)
  8172. PrettyTargetValue = Value.isZero() ? "false" : "true";
  8173. else
  8174. IntegerValue.toString(PrettyTargetValue);
  8175. if (PruneWarnings) {
  8176. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  8177. S.PDiag(DiagID)
  8178. << E->getType() << T.getUnqualifiedType()
  8179. << PrettySourceValue << PrettyTargetValue
  8180. << E->getSourceRange() << SourceRange(CContext));
  8181. } else {
  8182. S.Diag(E->getExprLoc(), DiagID)
  8183. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  8184. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  8185. }
  8186. }
  8187. std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
  8188. if (!Range.Width) return "0";
  8189. llvm::APSInt ValueInRange = Value;
  8190. ValueInRange.setIsSigned(!Range.NonNegative);
  8191. ValueInRange = ValueInRange.trunc(Range.Width);
  8192. return ValueInRange.toString(10);
  8193. }
  8194. bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  8195. if (!isa<ImplicitCastExpr>(Ex))
  8196. return false;
  8197. Expr *InnerE = Ex->IgnoreParenImpCasts();
  8198. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  8199. const Type *Source =
  8200. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  8201. if (Target->isDependentType())
  8202. return false;
  8203. const BuiltinType *FloatCandidateBT =
  8204. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  8205. const Type *BoolCandidateType = ToBool ? Target : Source;
  8206. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  8207. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  8208. }
  8209. void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  8210. SourceLocation CC) {
  8211. unsigned NumArgs = TheCall->getNumArgs();
  8212. for (unsigned i = 0; i < NumArgs; ++i) {
  8213. Expr *CurrA = TheCall->getArg(i);
  8214. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  8215. continue;
  8216. bool IsSwapped = ((i > 0) &&
  8217. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  8218. IsSwapped |= ((i < (NumArgs - 1)) &&
  8219. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  8220. if (IsSwapped) {
  8221. // Warn on this floating-point to bool conversion.
  8222. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  8223. CurrA->getType(), CC,
  8224. diag::warn_impcast_floating_point_to_bool);
  8225. }
  8226. }
  8227. }
  8228. void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
  8229. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  8230. E->getExprLoc()))
  8231. return;
  8232. // Don't warn on functions which have return type nullptr_t.
  8233. if (isa<CallExpr>(E))
  8234. return;
  8235. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  8236. const Expr::NullPointerConstantKind NullKind =
  8237. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  8238. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  8239. return;
  8240. // Return if target type is a safe conversion.
  8241. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  8242. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  8243. return;
  8244. SourceLocation Loc = E->getSourceRange().getBegin();
  8245. // Venture through the macro stacks to get to the source of macro arguments.
  8246. // The new location is a better location than the complete location that was
  8247. // passed in.
  8248. while (S.SourceMgr.isMacroArgExpansion(Loc))
  8249. Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
  8250. while (S.SourceMgr.isMacroArgExpansion(CC))
  8251. CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
  8252. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  8253. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  8254. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  8255. Loc, S.SourceMgr, S.getLangOpts());
  8256. if (MacroName == "NULL")
  8257. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
  8258. }
  8259. // Only warn if the null and context location are in the same macro expansion.
  8260. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  8261. return;
  8262. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  8263. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
  8264. << FixItHint::CreateReplacement(Loc,
  8265. S.getFixItZeroLiteralForType(T, Loc));
  8266. }
  8267. void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  8268. ObjCArrayLiteral *ArrayLiteral);
  8269. void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  8270. ObjCDictionaryLiteral *DictionaryLiteral);
  8271. /// Check a single element within a collection literal against the
  8272. /// target element type.
  8273. void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
  8274. Expr *Element, unsigned ElementKind) {
  8275. // Skip a bitcast to 'id' or qualified 'id'.
  8276. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  8277. if (ICE->getCastKind() == CK_BitCast &&
  8278. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  8279. Element = ICE->getSubExpr();
  8280. }
  8281. QualType ElementType = Element->getType();
  8282. ExprResult ElementResult(Element);
  8283. if (ElementType->getAs<ObjCObjectPointerType>() &&
  8284. S.CheckSingleAssignmentConstraints(TargetElementType,
  8285. ElementResult,
  8286. false, false)
  8287. != Sema::Compatible) {
  8288. S.Diag(Element->getLocStart(),
  8289. diag::warn_objc_collection_literal_element)
  8290. << ElementType << ElementKind << TargetElementType
  8291. << Element->getSourceRange();
  8292. }
  8293. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  8294. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  8295. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  8296. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  8297. }
  8298. /// Check an Objective-C array literal being converted to the given
  8299. /// target type.
  8300. void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  8301. ObjCArrayLiteral *ArrayLiteral) {
  8302. if (!S.NSArrayDecl)
  8303. return;
  8304. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  8305. if (!TargetObjCPtr)
  8306. return;
  8307. if (TargetObjCPtr->isUnspecialized() ||
  8308. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  8309. != S.NSArrayDecl->getCanonicalDecl())
  8310. return;
  8311. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  8312. if (TypeArgs.size() != 1)
  8313. return;
  8314. QualType TargetElementType = TypeArgs[0];
  8315. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  8316. checkObjCCollectionLiteralElement(S, TargetElementType,
  8317. ArrayLiteral->getElement(I),
  8318. 0);
  8319. }
  8320. }
  8321. /// Check an Objective-C dictionary literal being converted to the given
  8322. /// target type.
  8323. void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  8324. ObjCDictionaryLiteral *DictionaryLiteral) {
  8325. if (!S.NSDictionaryDecl)
  8326. return;
  8327. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  8328. if (!TargetObjCPtr)
  8329. return;
  8330. if (TargetObjCPtr->isUnspecialized() ||
  8331. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  8332. != S.NSDictionaryDecl->getCanonicalDecl())
  8333. return;
  8334. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  8335. if (TypeArgs.size() != 2)
  8336. return;
  8337. QualType TargetKeyType = TypeArgs[0];
  8338. QualType TargetObjectType = TypeArgs[1];
  8339. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  8340. auto Element = DictionaryLiteral->getKeyValueElement(I);
  8341. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  8342. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  8343. }
  8344. }
  8345. // Helper function to filter out cases for constant width constant conversion.
  8346. // Don't warn on char array initialization or for non-decimal values.
  8347. bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  8348. SourceLocation CC) {
  8349. // If initializing from a constant, and the constant starts with '0',
  8350. // then it is a binary, octal, or hexadecimal. Allow these constants
  8351. // to fill all the bits, even if there is a sign change.
  8352. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  8353. const char FirstLiteralCharacter =
  8354. S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
  8355. if (FirstLiteralCharacter == '0')
  8356. return false;
  8357. }
  8358. // If the CC location points to a '{', and the type is char, then assume
  8359. // assume it is an array initialization.
  8360. if (CC.isValid() && T->isCharType()) {
  8361. const char FirstContextCharacter =
  8362. S.getSourceManager().getCharacterData(CC)[0];
  8363. if (FirstContextCharacter == '{')
  8364. return false;
  8365. }
  8366. return true;
  8367. }
  8368. void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  8369. SourceLocation CC, bool *ICContext = nullptr) {
  8370. if (E->isTypeDependent() || E->isValueDependent()) return;
  8371. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  8372. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  8373. if (Source == Target) return;
  8374. if (Target->isDependentType()) return;
  8375. // If the conversion context location is invalid don't complain. We also
  8376. // don't want to emit a warning if the issue occurs from the expansion of
  8377. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  8378. // delay this check as long as possible. Once we detect we are in that
  8379. // scenario, we just return.
  8380. if (CC.isInvalid())
  8381. return;
  8382. // Diagnose implicit casts to bool.
  8383. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  8384. if (isa<StringLiteral>(E))
  8385. // Warn on string literal to bool. Checks for string literals in logical
  8386. // and expressions, for instance, assert(0 && "error here"), are
  8387. // prevented by a check in AnalyzeImplicitConversions().
  8388. return DiagnoseImpCast(S, E, T, CC,
  8389. diag::warn_impcast_string_literal_to_bool);
  8390. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  8391. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  8392. // This covers the literal expressions that evaluate to Objective-C
  8393. // objects.
  8394. return DiagnoseImpCast(S, E, T, CC,
  8395. diag::warn_impcast_objective_c_literal_to_bool);
  8396. }
  8397. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  8398. // Warn on pointer to bool conversion that is always true.
  8399. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  8400. SourceRange(CC));
  8401. }
  8402. }
  8403. // Check implicit casts from Objective-C collection literals to specialized
  8404. // collection types, e.g., NSArray<NSString *> *.
  8405. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  8406. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  8407. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  8408. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  8409. // Strip vector types.
  8410. if (isa<VectorType>(Source)) {
  8411. if (!isa<VectorType>(Target)) {
  8412. if (S.SourceMgr.isInSystemMacro(CC))
  8413. return;
  8414. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  8415. }
  8416. // If the vector cast is cast between two vectors of the same size, it is
  8417. // a bitcast, not a conversion.
  8418. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  8419. return;
  8420. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  8421. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  8422. }
  8423. if (auto VecTy = dyn_cast<VectorType>(Target))
  8424. Target = VecTy->getElementType().getTypePtr();
  8425. // Strip complex types.
  8426. if (isa<ComplexType>(Source)) {
  8427. if (!isa<ComplexType>(Target)) {
  8428. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  8429. return;
  8430. return DiagnoseImpCast(S, E, T, CC,
  8431. S.getLangOpts().CPlusPlus
  8432. ? diag::err_impcast_complex_scalar
  8433. : diag::warn_impcast_complex_scalar);
  8434. }
  8435. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  8436. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  8437. }
  8438. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  8439. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  8440. // If the source is floating point...
  8441. if (SourceBT && SourceBT->isFloatingPoint()) {
  8442. // ...and the target is floating point...
  8443. if (TargetBT && TargetBT->isFloatingPoint()) {
  8444. // ...then warn if we're dropping FP rank.
  8445. // Builtin FP kinds are ordered by increasing FP rank.
  8446. if (SourceBT->getKind() > TargetBT->getKind()) {
  8447. // Don't warn about float constants that are precisely
  8448. // representable in the target type.
  8449. Expr::EvalResult result;
  8450. if (E->EvaluateAsRValue(result, S.Context)) {
  8451. // Value might be a float, a float vector, or a float complex.
  8452. if (IsSameFloatAfterCast(result.Val,
  8453. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  8454. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  8455. return;
  8456. }
  8457. if (S.SourceMgr.isInSystemMacro(CC))
  8458. return;
  8459. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  8460. }
  8461. // ... or possibly if we're increasing rank, too
  8462. else if (TargetBT->getKind() > SourceBT->getKind()) {
  8463. if (S.SourceMgr.isInSystemMacro(CC))
  8464. return;
  8465. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  8466. }
  8467. return;
  8468. }
  8469. // If the target is integral, always warn.
  8470. if (TargetBT && TargetBT->isInteger()) {
  8471. if (S.SourceMgr.isInSystemMacro(CC))
  8472. return;
  8473. DiagnoseFloatingImpCast(S, E, T, CC);
  8474. }
  8475. // Detect the case where a call result is converted from floating-point to
  8476. // to bool, and the final argument to the call is converted from bool, to
  8477. // discover this typo:
  8478. //
  8479. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  8480. //
  8481. // FIXME: This is an incredibly special case; is there some more general
  8482. // way to detect this class of misplaced-parentheses bug?
  8483. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  8484. // Check last argument of function call to see if it is an
  8485. // implicit cast from a type matching the type the result
  8486. // is being cast to.
  8487. CallExpr *CEx = cast<CallExpr>(E);
  8488. if (unsigned NumArgs = CEx->getNumArgs()) {
  8489. Expr *LastA = CEx->getArg(NumArgs - 1);
  8490. Expr *InnerE = LastA->IgnoreParenImpCasts();
  8491. if (isa<ImplicitCastExpr>(LastA) &&
  8492. InnerE->getType()->isBooleanType()) {
  8493. // Warn on this floating-point to bool conversion
  8494. DiagnoseImpCast(S, E, T, CC,
  8495. diag::warn_impcast_floating_point_to_bool);
  8496. }
  8497. }
  8498. }
  8499. return;
  8500. }
  8501. DiagnoseNullConversion(S, E, T, CC);
  8502. S.DiscardMisalignedMemberAddress(Target, E);
  8503. if (!Source->isIntegerType() || !Target->isIntegerType())
  8504. return;
  8505. // TODO: remove this early return once the false positives for constant->bool
  8506. // in templates, macros, etc, are reduced or removed.
  8507. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  8508. return;
  8509. IntRange SourceRange = GetExprRange(S.Context, E);
  8510. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  8511. if (SourceRange.Width > TargetRange.Width) {
  8512. // If the source is a constant, use a default-on diagnostic.
  8513. // TODO: this should happen for bitfield stores, too.
  8514. llvm::APSInt Value(32);
  8515. if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
  8516. if (S.SourceMgr.isInSystemMacro(CC))
  8517. return;
  8518. std::string PrettySourceValue = Value.toString(10);
  8519. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  8520. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  8521. S.PDiag(diag::warn_impcast_integer_precision_constant)
  8522. << PrettySourceValue << PrettyTargetValue
  8523. << E->getType() << T << E->getSourceRange()
  8524. << clang::SourceRange(CC));
  8525. return;
  8526. }
  8527. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  8528. if (S.SourceMgr.isInSystemMacro(CC))
  8529. return;
  8530. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  8531. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  8532. /* pruneControlFlow */ true);
  8533. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  8534. }
  8535. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  8536. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  8537. // Warn when doing a signed to signed conversion, warn if the positive
  8538. // source value is exactly the width of the target type, which will
  8539. // cause a negative value to be stored.
  8540. llvm::APSInt Value;
  8541. if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
  8542. !S.SourceMgr.isInSystemMacro(CC)) {
  8543. if (isSameWidthConstantConversion(S, E, T, CC)) {
  8544. std::string PrettySourceValue = Value.toString(10);
  8545. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  8546. S.DiagRuntimeBehavior(
  8547. E->getExprLoc(), E,
  8548. S.PDiag(diag::warn_impcast_integer_precision_constant)
  8549. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  8550. << E->getSourceRange() << clang::SourceRange(CC));
  8551. return;
  8552. }
  8553. }
  8554. // Fall through for non-constants to give a sign conversion warning.
  8555. }
  8556. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  8557. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  8558. SourceRange.Width == TargetRange.Width)) {
  8559. if (S.SourceMgr.isInSystemMacro(CC))
  8560. return;
  8561. unsigned DiagID = diag::warn_impcast_integer_sign;
  8562. // Traditionally, gcc has warned about this under -Wsign-compare.
  8563. // We also want to warn about it in -Wconversion.
  8564. // So if -Wconversion is off, use a completely identical diagnostic
  8565. // in the sign-compare group.
  8566. // The conditional-checking code will
  8567. if (ICContext) {
  8568. DiagID = diag::warn_impcast_integer_sign_conditional;
  8569. *ICContext = true;
  8570. }
  8571. return DiagnoseImpCast(S, E, T, CC, DiagID);
  8572. }
  8573. // Diagnose conversions between different enumeration types.
  8574. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  8575. // type, to give us better diagnostics.
  8576. QualType SourceType = E->getType();
  8577. if (!S.getLangOpts().CPlusPlus) {
  8578. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  8579. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  8580. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  8581. SourceType = S.Context.getTypeDeclType(Enum);
  8582. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  8583. }
  8584. }
  8585. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  8586. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  8587. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  8588. TargetEnum->getDecl()->hasNameForLinkage() &&
  8589. SourceEnum != TargetEnum) {
  8590. if (S.SourceMgr.isInSystemMacro(CC))
  8591. return;
  8592. return DiagnoseImpCast(S, E, SourceType, T, CC,
  8593. diag::warn_impcast_different_enum_types);
  8594. }
  8595. }
  8596. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  8597. SourceLocation CC, QualType T);
  8598. void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  8599. SourceLocation CC, bool &ICContext) {
  8600. E = E->IgnoreParenImpCasts();
  8601. if (isa<ConditionalOperator>(E))
  8602. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  8603. AnalyzeImplicitConversions(S, E, CC);
  8604. if (E->getType() != T)
  8605. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  8606. }
  8607. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  8608. SourceLocation CC, QualType T) {
  8609. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  8610. bool Suspicious = false;
  8611. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  8612. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  8613. // If -Wconversion would have warned about either of the candidates
  8614. // for a signedness conversion to the context type...
  8615. if (!Suspicious) return;
  8616. // ...but it's currently ignored...
  8617. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  8618. return;
  8619. // ...then check whether it would have warned about either of the
  8620. // candidates for a signedness conversion to the condition type.
  8621. if (E->getType() == T) return;
  8622. Suspicious = false;
  8623. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  8624. E->getType(), CC, &Suspicious);
  8625. if (!Suspicious)
  8626. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  8627. E->getType(), CC, &Suspicious);
  8628. }
  8629. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  8630. /// Input argument E is a logical expression.
  8631. void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  8632. if (S.getLangOpts().Bool)
  8633. return;
  8634. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  8635. }
  8636. /// AnalyzeImplicitConversions - Find and report any interesting
  8637. /// implicit conversions in the given expression. There are a couple
  8638. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  8639. void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
  8640. QualType T = OrigE->getType();
  8641. Expr *E = OrigE->IgnoreParenImpCasts();
  8642. if (E->isTypeDependent() || E->isValueDependent())
  8643. return;
  8644. // For conditional operators, we analyze the arguments as if they
  8645. // were being fed directly into the output.
  8646. if (isa<ConditionalOperator>(E)) {
  8647. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  8648. CheckConditionalOperator(S, CO, CC, T);
  8649. return;
  8650. }
  8651. // Check implicit argument conversions for function calls.
  8652. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  8653. CheckImplicitArgumentConversions(S, Call, CC);
  8654. // Go ahead and check any implicit conversions we might have skipped.
  8655. // The non-canonical typecheck is just an optimization;
  8656. // CheckImplicitConversion will filter out dead implicit conversions.
  8657. if (E->getType() != T)
  8658. CheckImplicitConversion(S, E, T, CC);
  8659. // Now continue drilling into this expression.
  8660. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  8661. // The bound subexpressions in a PseudoObjectExpr are not reachable
  8662. // as transitive children.
  8663. // FIXME: Use a more uniform representation for this.
  8664. for (auto *SE : POE->semantics())
  8665. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  8666. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  8667. }
  8668. // Skip past explicit casts.
  8669. if (isa<ExplicitCastExpr>(E)) {
  8670. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  8671. return AnalyzeImplicitConversions(S, E, CC);
  8672. }
  8673. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  8674. // Do a somewhat different check with comparison operators.
  8675. if (BO->isComparisonOp())
  8676. return AnalyzeComparison(S, BO);
  8677. // And with simple assignments.
  8678. if (BO->getOpcode() == BO_Assign)
  8679. return AnalyzeAssignment(S, BO);
  8680. }
  8681. // These break the otherwise-useful invariant below. Fortunately,
  8682. // we don't really need to recurse into them, because any internal
  8683. // expressions should have been analyzed already when they were
  8684. // built into statements.
  8685. if (isa<StmtExpr>(E)) return;
  8686. // Don't descend into unevaluated contexts.
  8687. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  8688. // Now just recurse over the expression's children.
  8689. CC = E->getExprLoc();
  8690. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  8691. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  8692. for (Stmt *SubStmt : E->children()) {
  8693. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  8694. if (!ChildExpr)
  8695. continue;
  8696. if (IsLogicalAndOperator &&
  8697. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  8698. // Ignore checking string literals that are in logical and operators.
  8699. // This is a common pattern for asserts.
  8700. continue;
  8701. AnalyzeImplicitConversions(S, ChildExpr, CC);
  8702. }
  8703. if (BO && BO->isLogicalOp()) {
  8704. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  8705. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  8706. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  8707. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  8708. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  8709. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  8710. }
  8711. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
  8712. if (U->getOpcode() == UO_LNot)
  8713. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  8714. }
  8715. } // end anonymous namespace
  8716. /// Diagnose integer type and any valid implicit convertion to it.
  8717. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  8718. // Taking into account implicit conversions,
  8719. // allow any integer.
  8720. if (!E->getType()->isIntegerType()) {
  8721. S.Diag(E->getLocStart(),
  8722. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  8723. return true;
  8724. }
  8725. // Potentially emit standard warnings for implicit conversions if enabled
  8726. // using -Wconversion.
  8727. CheckImplicitConversion(S, E, IntT, E->getLocStart());
  8728. return false;
  8729. }
  8730. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  8731. // Returns true when emitting a warning about taking the address of a reference.
  8732. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  8733. const PartialDiagnostic &PD) {
  8734. E = E->IgnoreParenImpCasts();
  8735. const FunctionDecl *FD = nullptr;
  8736. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  8737. if (!DRE->getDecl()->getType()->isReferenceType())
  8738. return false;
  8739. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  8740. if (!M->getMemberDecl()->getType()->isReferenceType())
  8741. return false;
  8742. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  8743. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  8744. return false;
  8745. FD = Call->getDirectCallee();
  8746. } else {
  8747. return false;
  8748. }
  8749. SemaRef.Diag(E->getExprLoc(), PD);
  8750. // If possible, point to location of function.
  8751. if (FD) {
  8752. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  8753. }
  8754. return true;
  8755. }
  8756. // Returns true if the SourceLocation is expanded from any macro body.
  8757. // Returns false if the SourceLocation is invalid, is from not in a macro
  8758. // expansion, or is from expanded from a top-level macro argument.
  8759. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  8760. if (Loc.isInvalid())
  8761. return false;
  8762. while (Loc.isMacroID()) {
  8763. if (SM.isMacroBodyExpansion(Loc))
  8764. return true;
  8765. Loc = SM.getImmediateMacroCallerLoc(Loc);
  8766. }
  8767. return false;
  8768. }
  8769. /// \brief Diagnose pointers that are always non-null.
  8770. /// \param E the expression containing the pointer
  8771. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  8772. /// compared to a null pointer
  8773. /// \param IsEqual True when the comparison is equal to a null pointer
  8774. /// \param Range Extra SourceRange to highlight in the diagnostic
  8775. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  8776. Expr::NullPointerConstantKind NullKind,
  8777. bool IsEqual, SourceRange Range) {
  8778. if (!E)
  8779. return;
  8780. // Don't warn inside macros.
  8781. if (E->getExprLoc().isMacroID()) {
  8782. const SourceManager &SM = getSourceManager();
  8783. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  8784. IsInAnyMacroBody(SM, Range.getBegin()))
  8785. return;
  8786. }
  8787. E = E->IgnoreImpCasts();
  8788. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  8789. if (isa<CXXThisExpr>(E)) {
  8790. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  8791. : diag::warn_this_bool_conversion;
  8792. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  8793. return;
  8794. }
  8795. bool IsAddressOf = false;
  8796. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  8797. if (UO->getOpcode() != UO_AddrOf)
  8798. return;
  8799. IsAddressOf = true;
  8800. E = UO->getSubExpr();
  8801. }
  8802. if (IsAddressOf) {
  8803. unsigned DiagID = IsCompare
  8804. ? diag::warn_address_of_reference_null_compare
  8805. : diag::warn_address_of_reference_bool_conversion;
  8806. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  8807. << IsEqual;
  8808. if (CheckForReference(*this, E, PD)) {
  8809. return;
  8810. }
  8811. }
  8812. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  8813. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  8814. std::string Str;
  8815. llvm::raw_string_ostream S(Str);
  8816. E->printPretty(S, nullptr, getPrintingPolicy());
  8817. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  8818. : diag::warn_cast_nonnull_to_bool;
  8819. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  8820. << E->getSourceRange() << Range << IsEqual;
  8821. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  8822. };
  8823. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  8824. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  8825. if (auto *Callee = Call->getDirectCallee()) {
  8826. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  8827. ComplainAboutNonnullParamOrCall(A);
  8828. return;
  8829. }
  8830. }
  8831. }
  8832. // Expect to find a single Decl. Skip anything more complicated.
  8833. ValueDecl *D = nullptr;
  8834. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  8835. D = R->getDecl();
  8836. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  8837. D = M->getMemberDecl();
  8838. }
  8839. // Weak Decls can be null.
  8840. if (!D || D->isWeak())
  8841. return;
  8842. // Check for parameter decl with nonnull attribute
  8843. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  8844. if (getCurFunction() &&
  8845. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  8846. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  8847. ComplainAboutNonnullParamOrCall(A);
  8848. return;
  8849. }
  8850. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  8851. auto ParamIter = llvm::find(FD->parameters(), PV);
  8852. assert(ParamIter != FD->param_end());
  8853. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  8854. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  8855. if (!NonNull->args_size()) {
  8856. ComplainAboutNonnullParamOrCall(NonNull);
  8857. return;
  8858. }
  8859. for (unsigned ArgNo : NonNull->args()) {
  8860. if (ArgNo == ParamNo) {
  8861. ComplainAboutNonnullParamOrCall(NonNull);
  8862. return;
  8863. }
  8864. }
  8865. }
  8866. }
  8867. }
  8868. }
  8869. QualType T = D->getType();
  8870. const bool IsArray = T->isArrayType();
  8871. const bool IsFunction = T->isFunctionType();
  8872. // Address of function is used to silence the function warning.
  8873. if (IsAddressOf && IsFunction) {
  8874. return;
  8875. }
  8876. // Found nothing.
  8877. if (!IsAddressOf && !IsFunction && !IsArray)
  8878. return;
  8879. // Pretty print the expression for the diagnostic.
  8880. std::string Str;
  8881. llvm::raw_string_ostream S(Str);
  8882. E->printPretty(S, nullptr, getPrintingPolicy());
  8883. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  8884. : diag::warn_impcast_pointer_to_bool;
  8885. enum {
  8886. AddressOf,
  8887. FunctionPointer,
  8888. ArrayPointer
  8889. } DiagType;
  8890. if (IsAddressOf)
  8891. DiagType = AddressOf;
  8892. else if (IsFunction)
  8893. DiagType = FunctionPointer;
  8894. else if (IsArray)
  8895. DiagType = ArrayPointer;
  8896. else
  8897. llvm_unreachable("Could not determine diagnostic.");
  8898. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  8899. << Range << IsEqual;
  8900. if (!IsFunction)
  8901. return;
  8902. // Suggest '&' to silence the function warning.
  8903. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  8904. << FixItHint::CreateInsertion(E->getLocStart(), "&");
  8905. // Check to see if '()' fixit should be emitted.
  8906. QualType ReturnType;
  8907. UnresolvedSet<4> NonTemplateOverloads;
  8908. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  8909. if (ReturnType.isNull())
  8910. return;
  8911. if (IsCompare) {
  8912. // There are two cases here. If there is null constant, the only suggest
  8913. // for a pointer return type. If the null is 0, then suggest if the return
  8914. // type is a pointer or an integer type.
  8915. if (!ReturnType->isPointerType()) {
  8916. if (NullKind == Expr::NPCK_ZeroExpression ||
  8917. NullKind == Expr::NPCK_ZeroLiteral) {
  8918. if (!ReturnType->isIntegerType())
  8919. return;
  8920. } else {
  8921. return;
  8922. }
  8923. }
  8924. } else { // !IsCompare
  8925. // For function to bool, only suggest if the function pointer has bool
  8926. // return type.
  8927. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  8928. return;
  8929. }
  8930. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  8931. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
  8932. }
  8933. /// Diagnoses "dangerous" implicit conversions within the given
  8934. /// expression (which is a full expression). Implements -Wconversion
  8935. /// and -Wsign-compare.
  8936. ///
  8937. /// \param CC the "context" location of the implicit conversion, i.e.
  8938. /// the most location of the syntactic entity requiring the implicit
  8939. /// conversion
  8940. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  8941. // Don't diagnose in unevaluated contexts.
  8942. if (isUnevaluatedContext())
  8943. return;
  8944. // Don't diagnose for value- or type-dependent expressions.
  8945. if (E->isTypeDependent() || E->isValueDependent())
  8946. return;
  8947. // Check for array bounds violations in cases where the check isn't triggered
  8948. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  8949. // ArraySubscriptExpr is on the RHS of a variable initialization.
  8950. CheckArrayAccess(E);
  8951. // This is not the right CC for (e.g.) a variable initialization.
  8952. AnalyzeImplicitConversions(*this, E, CC);
  8953. }
  8954. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  8955. /// Input argument E is a logical expression.
  8956. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  8957. ::CheckBoolLikeConversion(*this, E, CC);
  8958. }
  8959. /// Diagnose when expression is an integer constant expression and its evaluation
  8960. /// results in integer overflow
  8961. void Sema::CheckForIntOverflow (Expr *E) {
  8962. // Use a work list to deal with nested struct initializers.
  8963. SmallVector<Expr *, 2> Exprs(1, E);
  8964. do {
  8965. Expr *E = Exprs.pop_back_val();
  8966. if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
  8967. E->IgnoreParenCasts()->EvaluateForOverflow(Context);
  8968. continue;
  8969. }
  8970. if (auto InitList = dyn_cast<InitListExpr>(E))
  8971. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  8972. if (isa<ObjCBoxedExpr>(E))
  8973. E->IgnoreParenCasts()->EvaluateForOverflow(Context);
  8974. } while (!Exprs.empty());
  8975. }
  8976. namespace {
  8977. /// \brief Visitor for expressions which looks for unsequenced operations on the
  8978. /// same object.
  8979. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  8980. typedef EvaluatedExprVisitor<SequenceChecker> Base;
  8981. /// \brief A tree of sequenced regions within an expression. Two regions are
  8982. /// unsequenced if one is an ancestor or a descendent of the other. When we
  8983. /// finish processing an expression with sequencing, such as a comma
  8984. /// expression, we fold its tree nodes into its parent, since they are
  8985. /// unsequenced with respect to nodes we will visit later.
  8986. class SequenceTree {
  8987. struct Value {
  8988. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  8989. unsigned Parent : 31;
  8990. unsigned Merged : 1;
  8991. };
  8992. SmallVector<Value, 8> Values;
  8993. public:
  8994. /// \brief A region within an expression which may be sequenced with respect
  8995. /// to some other region.
  8996. class Seq {
  8997. explicit Seq(unsigned N) : Index(N) {}
  8998. unsigned Index;
  8999. friend class SequenceTree;
  9000. public:
  9001. Seq() : Index(0) {}
  9002. };
  9003. SequenceTree() { Values.push_back(Value(0)); }
  9004. Seq root() const { return Seq(0); }
  9005. /// \brief Create a new sequence of operations, which is an unsequenced
  9006. /// subset of \p Parent. This sequence of operations is sequenced with
  9007. /// respect to other children of \p Parent.
  9008. Seq allocate(Seq Parent) {
  9009. Values.push_back(Value(Parent.Index));
  9010. return Seq(Values.size() - 1);
  9011. }
  9012. /// \brief Merge a sequence of operations into its parent.
  9013. void merge(Seq S) {
  9014. Values[S.Index].Merged = true;
  9015. }
  9016. /// \brief Determine whether two operations are unsequenced. This operation
  9017. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  9018. /// should have been merged into its parent as appropriate.
  9019. bool isUnsequenced(Seq Cur, Seq Old) {
  9020. unsigned C = representative(Cur.Index);
  9021. unsigned Target = representative(Old.Index);
  9022. while (C >= Target) {
  9023. if (C == Target)
  9024. return true;
  9025. C = Values[C].Parent;
  9026. }
  9027. return false;
  9028. }
  9029. private:
  9030. /// \brief Pick a representative for a sequence.
  9031. unsigned representative(unsigned K) {
  9032. if (Values[K].Merged)
  9033. // Perform path compression as we go.
  9034. return Values[K].Parent = representative(Values[K].Parent);
  9035. return K;
  9036. }
  9037. };
  9038. /// An object for which we can track unsequenced uses.
  9039. typedef NamedDecl *Object;
  9040. /// Different flavors of object usage which we track. We only track the
  9041. /// least-sequenced usage of each kind.
  9042. enum UsageKind {
  9043. /// A read of an object. Multiple unsequenced reads are OK.
  9044. UK_Use,
  9045. /// A modification of an object which is sequenced before the value
  9046. /// computation of the expression, such as ++n in C++.
  9047. UK_ModAsValue,
  9048. /// A modification of an object which is not sequenced before the value
  9049. /// computation of the expression, such as n++.
  9050. UK_ModAsSideEffect,
  9051. UK_Count = UK_ModAsSideEffect + 1
  9052. };
  9053. struct Usage {
  9054. Usage() : Use(nullptr), Seq() {}
  9055. Expr *Use;
  9056. SequenceTree::Seq Seq;
  9057. };
  9058. struct UsageInfo {
  9059. UsageInfo() : Diagnosed(false) {}
  9060. Usage Uses[UK_Count];
  9061. /// Have we issued a diagnostic for this variable already?
  9062. bool Diagnosed;
  9063. };
  9064. typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
  9065. Sema &SemaRef;
  9066. /// Sequenced regions within the expression.
  9067. SequenceTree Tree;
  9068. /// Declaration modifications and references which we have seen.
  9069. UsageInfoMap UsageMap;
  9070. /// The region we are currently within.
  9071. SequenceTree::Seq Region;
  9072. /// Filled in with declarations which were modified as a side-effect
  9073. /// (that is, post-increment operations).
  9074. SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
  9075. /// Expressions to check later. We defer checking these to reduce
  9076. /// stack usage.
  9077. SmallVectorImpl<Expr *> &WorkList;
  9078. /// RAII object wrapping the visitation of a sequenced subexpression of an
  9079. /// expression. At the end of this process, the side-effects of the evaluation
  9080. /// become sequenced with respect to the value computation of the result, so
  9081. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  9082. /// UK_ModAsValue.
  9083. struct SequencedSubexpression {
  9084. SequencedSubexpression(SequenceChecker &Self)
  9085. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  9086. Self.ModAsSideEffect = &ModAsSideEffect;
  9087. }
  9088. ~SequencedSubexpression() {
  9089. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  9090. UsageInfo &U = Self.UsageMap[M.first];
  9091. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  9092. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  9093. SideEffectUsage = M.second;
  9094. }
  9095. Self.ModAsSideEffect = OldModAsSideEffect;
  9096. }
  9097. SequenceChecker &Self;
  9098. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  9099. SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
  9100. };
  9101. /// RAII object wrapping the visitation of a subexpression which we might
  9102. /// choose to evaluate as a constant. If any subexpression is evaluated and
  9103. /// found to be non-constant, this allows us to suppress the evaluation of
  9104. /// the outer expression.
  9105. class EvaluationTracker {
  9106. public:
  9107. EvaluationTracker(SequenceChecker &Self)
  9108. : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
  9109. Self.EvalTracker = this;
  9110. }
  9111. ~EvaluationTracker() {
  9112. Self.EvalTracker = Prev;
  9113. if (Prev)
  9114. Prev->EvalOK &= EvalOK;
  9115. }
  9116. bool evaluate(const Expr *E, bool &Result) {
  9117. if (!EvalOK || E->isValueDependent())
  9118. return false;
  9119. EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
  9120. return EvalOK;
  9121. }
  9122. private:
  9123. SequenceChecker &Self;
  9124. EvaluationTracker *Prev;
  9125. bool EvalOK;
  9126. } *EvalTracker;
  9127. /// \brief Find the object which is produced by the specified expression,
  9128. /// if any.
  9129. Object getObject(Expr *E, bool Mod) const {
  9130. E = E->IgnoreParenCasts();
  9131. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  9132. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  9133. return getObject(UO->getSubExpr(), Mod);
  9134. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9135. if (BO->getOpcode() == BO_Comma)
  9136. return getObject(BO->getRHS(), Mod);
  9137. if (Mod && BO->isAssignmentOp())
  9138. return getObject(BO->getLHS(), Mod);
  9139. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  9140. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  9141. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  9142. return ME->getMemberDecl();
  9143. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  9144. // FIXME: If this is a reference, map through to its value.
  9145. return DRE->getDecl();
  9146. return nullptr;
  9147. }
  9148. /// \brief Note that an object was modified or used by an expression.
  9149. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  9150. Usage &U = UI.Uses[UK];
  9151. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  9152. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  9153. ModAsSideEffect->push_back(std::make_pair(O, U));
  9154. U.Use = Ref;
  9155. U.Seq = Region;
  9156. }
  9157. }
  9158. /// \brief Check whether a modification or use conflicts with a prior usage.
  9159. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  9160. bool IsModMod) {
  9161. if (UI.Diagnosed)
  9162. return;
  9163. const Usage &U = UI.Uses[OtherKind];
  9164. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  9165. return;
  9166. Expr *Mod = U.Use;
  9167. Expr *ModOrUse = Ref;
  9168. if (OtherKind == UK_Use)
  9169. std::swap(Mod, ModOrUse);
  9170. SemaRef.Diag(Mod->getExprLoc(),
  9171. IsModMod ? diag::warn_unsequenced_mod_mod
  9172. : diag::warn_unsequenced_mod_use)
  9173. << O << SourceRange(ModOrUse->getExprLoc());
  9174. UI.Diagnosed = true;
  9175. }
  9176. void notePreUse(Object O, Expr *Use) {
  9177. UsageInfo &U = UsageMap[O];
  9178. // Uses conflict with other modifications.
  9179. checkUsage(O, U, Use, UK_ModAsValue, false);
  9180. }
  9181. void notePostUse(Object O, Expr *Use) {
  9182. UsageInfo &U = UsageMap[O];
  9183. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  9184. addUsage(U, O, Use, UK_Use);
  9185. }
  9186. void notePreMod(Object O, Expr *Mod) {
  9187. UsageInfo &U = UsageMap[O];
  9188. // Modifications conflict with other modifications and with uses.
  9189. checkUsage(O, U, Mod, UK_ModAsValue, true);
  9190. checkUsage(O, U, Mod, UK_Use, false);
  9191. }
  9192. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  9193. UsageInfo &U = UsageMap[O];
  9194. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  9195. addUsage(U, O, Use, UK);
  9196. }
  9197. public:
  9198. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  9199. : Base(S.Context), SemaRef(S), Region(Tree.root()),
  9200. ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
  9201. Visit(E);
  9202. }
  9203. void VisitStmt(Stmt *S) {
  9204. // Skip all statements which aren't expressions for now.
  9205. }
  9206. void VisitExpr(Expr *E) {
  9207. // By default, just recurse to evaluated subexpressions.
  9208. Base::VisitStmt(E);
  9209. }
  9210. void VisitCastExpr(CastExpr *E) {
  9211. Object O = Object();
  9212. if (E->getCastKind() == CK_LValueToRValue)
  9213. O = getObject(E->getSubExpr(), false);
  9214. if (O)
  9215. notePreUse(O, E);
  9216. VisitExpr(E);
  9217. if (O)
  9218. notePostUse(O, E);
  9219. }
  9220. void VisitBinComma(BinaryOperator *BO) {
  9221. // C++11 [expr.comma]p1:
  9222. // Every value computation and side effect associated with the left
  9223. // expression is sequenced before every value computation and side
  9224. // effect associated with the right expression.
  9225. SequenceTree::Seq LHS = Tree.allocate(Region);
  9226. SequenceTree::Seq RHS = Tree.allocate(Region);
  9227. SequenceTree::Seq OldRegion = Region;
  9228. {
  9229. SequencedSubexpression SeqLHS(*this);
  9230. Region = LHS;
  9231. Visit(BO->getLHS());
  9232. }
  9233. Region = RHS;
  9234. Visit(BO->getRHS());
  9235. Region = OldRegion;
  9236. // Forget that LHS and RHS are sequenced. They are both unsequenced
  9237. // with respect to other stuff.
  9238. Tree.merge(LHS);
  9239. Tree.merge(RHS);
  9240. }
  9241. void VisitBinAssign(BinaryOperator *BO) {
  9242. // The modification is sequenced after the value computation of the LHS
  9243. // and RHS, so check it before inspecting the operands and update the
  9244. // map afterwards.
  9245. Object O = getObject(BO->getLHS(), true);
  9246. if (!O)
  9247. return VisitExpr(BO);
  9248. notePreMod(O, BO);
  9249. // C++11 [expr.ass]p7:
  9250. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  9251. // only once.
  9252. //
  9253. // Therefore, for a compound assignment operator, O is considered used
  9254. // everywhere except within the evaluation of E1 itself.
  9255. if (isa<CompoundAssignOperator>(BO))
  9256. notePreUse(O, BO);
  9257. Visit(BO->getLHS());
  9258. if (isa<CompoundAssignOperator>(BO))
  9259. notePostUse(O, BO);
  9260. Visit(BO->getRHS());
  9261. // C++11 [expr.ass]p1:
  9262. // the assignment is sequenced [...] before the value computation of the
  9263. // assignment expression.
  9264. // C11 6.5.16/3 has no such rule.
  9265. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  9266. : UK_ModAsSideEffect);
  9267. }
  9268. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  9269. VisitBinAssign(CAO);
  9270. }
  9271. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  9272. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  9273. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  9274. Object O = getObject(UO->getSubExpr(), true);
  9275. if (!O)
  9276. return VisitExpr(UO);
  9277. notePreMod(O, UO);
  9278. Visit(UO->getSubExpr());
  9279. // C++11 [expr.pre.incr]p1:
  9280. // the expression ++x is equivalent to x+=1
  9281. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  9282. : UK_ModAsSideEffect);
  9283. }
  9284. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  9285. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  9286. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  9287. Object O = getObject(UO->getSubExpr(), true);
  9288. if (!O)
  9289. return VisitExpr(UO);
  9290. notePreMod(O, UO);
  9291. Visit(UO->getSubExpr());
  9292. notePostMod(O, UO, UK_ModAsSideEffect);
  9293. }
  9294. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  9295. void VisitBinLOr(BinaryOperator *BO) {
  9296. // The side-effects of the LHS of an '&&' are sequenced before the
  9297. // value computation of the RHS, and hence before the value computation
  9298. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  9299. // as if they were unconditionally sequenced.
  9300. EvaluationTracker Eval(*this);
  9301. {
  9302. SequencedSubexpression Sequenced(*this);
  9303. Visit(BO->getLHS());
  9304. }
  9305. bool Result;
  9306. if (Eval.evaluate(BO->getLHS(), Result)) {
  9307. if (!Result)
  9308. Visit(BO->getRHS());
  9309. } else {
  9310. // Check for unsequenced operations in the RHS, treating it as an
  9311. // entirely separate evaluation.
  9312. //
  9313. // FIXME: If there are operations in the RHS which are unsequenced
  9314. // with respect to operations outside the RHS, and those operations
  9315. // are unconditionally evaluated, diagnose them.
  9316. WorkList.push_back(BO->getRHS());
  9317. }
  9318. }
  9319. void VisitBinLAnd(BinaryOperator *BO) {
  9320. EvaluationTracker Eval(*this);
  9321. {
  9322. SequencedSubexpression Sequenced(*this);
  9323. Visit(BO->getLHS());
  9324. }
  9325. bool Result;
  9326. if (Eval.evaluate(BO->getLHS(), Result)) {
  9327. if (Result)
  9328. Visit(BO->getRHS());
  9329. } else {
  9330. WorkList.push_back(BO->getRHS());
  9331. }
  9332. }
  9333. // Only visit the condition, unless we can be sure which subexpression will
  9334. // be chosen.
  9335. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  9336. EvaluationTracker Eval(*this);
  9337. {
  9338. SequencedSubexpression Sequenced(*this);
  9339. Visit(CO->getCond());
  9340. }
  9341. bool Result;
  9342. if (Eval.evaluate(CO->getCond(), Result))
  9343. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  9344. else {
  9345. WorkList.push_back(CO->getTrueExpr());
  9346. WorkList.push_back(CO->getFalseExpr());
  9347. }
  9348. }
  9349. void VisitCallExpr(CallExpr *CE) {
  9350. // C++11 [intro.execution]p15:
  9351. // When calling a function [...], every value computation and side effect
  9352. // associated with any argument expression, or with the postfix expression
  9353. // designating the called function, is sequenced before execution of every
  9354. // expression or statement in the body of the function [and thus before
  9355. // the value computation of its result].
  9356. SequencedSubexpression Sequenced(*this);
  9357. Base::VisitCallExpr(CE);
  9358. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  9359. }
  9360. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  9361. // This is a call, so all subexpressions are sequenced before the result.
  9362. SequencedSubexpression Sequenced(*this);
  9363. if (!CCE->isListInitialization())
  9364. return VisitExpr(CCE);
  9365. // In C++11, list initializations are sequenced.
  9366. SmallVector<SequenceTree::Seq, 32> Elts;
  9367. SequenceTree::Seq Parent = Region;
  9368. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  9369. E = CCE->arg_end();
  9370. I != E; ++I) {
  9371. Region = Tree.allocate(Parent);
  9372. Elts.push_back(Region);
  9373. Visit(*I);
  9374. }
  9375. // Forget that the initializers are sequenced.
  9376. Region = Parent;
  9377. for (unsigned I = 0; I < Elts.size(); ++I)
  9378. Tree.merge(Elts[I]);
  9379. }
  9380. void VisitInitListExpr(InitListExpr *ILE) {
  9381. if (!SemaRef.getLangOpts().CPlusPlus11)
  9382. return VisitExpr(ILE);
  9383. // In C++11, list initializations are sequenced.
  9384. SmallVector<SequenceTree::Seq, 32> Elts;
  9385. SequenceTree::Seq Parent = Region;
  9386. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  9387. Expr *E = ILE->getInit(I);
  9388. if (!E) continue;
  9389. Region = Tree.allocate(Parent);
  9390. Elts.push_back(Region);
  9391. Visit(E);
  9392. }
  9393. // Forget that the initializers are sequenced.
  9394. Region = Parent;
  9395. for (unsigned I = 0; I < Elts.size(); ++I)
  9396. Tree.merge(Elts[I]);
  9397. }
  9398. };
  9399. } // end anonymous namespace
  9400. void Sema::CheckUnsequencedOperations(Expr *E) {
  9401. SmallVector<Expr *, 8> WorkList;
  9402. WorkList.push_back(E);
  9403. while (!WorkList.empty()) {
  9404. Expr *Item = WorkList.pop_back_val();
  9405. SequenceChecker(*this, Item, WorkList);
  9406. }
  9407. }
  9408. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  9409. bool IsConstexpr) {
  9410. CheckImplicitConversions(E, CheckLoc);
  9411. if (!E->isInstantiationDependent())
  9412. CheckUnsequencedOperations(E);
  9413. if (!IsConstexpr && !E->isValueDependent())
  9414. CheckForIntOverflow(E);
  9415. DiagnoseMisalignedMembers();
  9416. }
  9417. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  9418. FieldDecl *BitField,
  9419. Expr *Init) {
  9420. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  9421. }
  9422. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  9423. SourceLocation Loc) {
  9424. if (!PType->isVariablyModifiedType())
  9425. return;
  9426. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  9427. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  9428. return;
  9429. }
  9430. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  9431. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  9432. return;
  9433. }
  9434. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  9435. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  9436. return;
  9437. }
  9438. const ArrayType *AT = S.Context.getAsArrayType(PType);
  9439. if (!AT)
  9440. return;
  9441. if (AT->getSizeModifier() != ArrayType::Star) {
  9442. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  9443. return;
  9444. }
  9445. S.Diag(Loc, diag::err_array_star_in_function_definition);
  9446. }
  9447. /// CheckParmsForFunctionDef - Check that the parameters of the given
  9448. /// function are appropriate for the definition of a function. This
  9449. /// takes care of any checks that cannot be performed on the
  9450. /// declaration itself, e.g., that the types of each of the function
  9451. /// parameters are complete.
  9452. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  9453. bool CheckParameterNames) {
  9454. bool HasInvalidParm = false;
  9455. for (ParmVarDecl *Param : Parameters) {
  9456. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  9457. // function declarator that is part of a function definition of
  9458. // that function shall not have incomplete type.
  9459. //
  9460. // This is also C++ [dcl.fct]p6.
  9461. if (!Param->isInvalidDecl() &&
  9462. RequireCompleteType(Param->getLocation(), Param->getType(),
  9463. diag::err_typecheck_decl_incomplete_type)) {
  9464. Param->setInvalidDecl();
  9465. HasInvalidParm = true;
  9466. }
  9467. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  9468. // declaration of each parameter shall include an identifier.
  9469. if (CheckParameterNames &&
  9470. Param->getIdentifier() == nullptr &&
  9471. !Param->isImplicit() &&
  9472. !getLangOpts().CPlusPlus)
  9473. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  9474. // C99 6.7.5.3p12:
  9475. // If the function declarator is not part of a definition of that
  9476. // function, parameters may have incomplete type and may use the [*]
  9477. // notation in their sequences of declarator specifiers to specify
  9478. // variable length array types.
  9479. QualType PType = Param->getOriginalType();
  9480. // FIXME: This diagnostic should point the '[*]' if source-location
  9481. // information is added for it.
  9482. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  9483. // MSVC destroys objects passed by value in the callee. Therefore a
  9484. // function definition which takes such a parameter must be able to call the
  9485. // object's destructor. However, we don't perform any direct access check
  9486. // on the dtor.
  9487. if (getLangOpts().CPlusPlus && Context.getTargetInfo()
  9488. .getCXXABI()
  9489. .areArgsDestroyedLeftToRightInCallee()) {
  9490. if (!Param->isInvalidDecl()) {
  9491. if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
  9492. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  9493. if (!ClassDecl->isInvalidDecl() &&
  9494. !ClassDecl->hasIrrelevantDestructor() &&
  9495. !ClassDecl->isDependentContext()) {
  9496. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  9497. MarkFunctionReferenced(Param->getLocation(), Destructor);
  9498. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  9499. }
  9500. }
  9501. }
  9502. }
  9503. // Parameters with the pass_object_size attribute only need to be marked
  9504. // constant at function definitions. Because we lack information about
  9505. // whether we're on a declaration or definition when we're instantiating the
  9506. // attribute, we need to check for constness here.
  9507. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  9508. if (!Param->getType().isConstQualified())
  9509. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  9510. << Attr->getSpelling() << 1;
  9511. }
  9512. return HasInvalidParm;
  9513. }
  9514. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  9515. /// or MemberExpr.
  9516. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  9517. ASTContext &Context) {
  9518. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  9519. return Context.getDeclAlign(DRE->getDecl());
  9520. if (const auto *ME = dyn_cast<MemberExpr>(E))
  9521. return Context.getDeclAlign(ME->getMemberDecl());
  9522. return TypeAlign;
  9523. }
  9524. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  9525. /// pointer cast increases the alignment requirements.
  9526. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  9527. // This is actually a lot of work to potentially be doing on every
  9528. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  9529. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  9530. return;
  9531. // Ignore dependent types.
  9532. if (T->isDependentType() || Op->getType()->isDependentType())
  9533. return;
  9534. // Require that the destination be a pointer type.
  9535. const PointerType *DestPtr = T->getAs<PointerType>();
  9536. if (!DestPtr) return;
  9537. // If the destination has alignment 1, we're done.
  9538. QualType DestPointee = DestPtr->getPointeeType();
  9539. if (DestPointee->isIncompleteType()) return;
  9540. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  9541. if (DestAlign.isOne()) return;
  9542. // Require that the source be a pointer type.
  9543. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  9544. if (!SrcPtr) return;
  9545. QualType SrcPointee = SrcPtr->getPointeeType();
  9546. // Whitelist casts from cv void*. We already implicitly
  9547. // whitelisted casts to cv void*, since they have alignment 1.
  9548. // Also whitelist casts involving incomplete types, which implicitly
  9549. // includes 'void'.
  9550. if (SrcPointee->isIncompleteType()) return;
  9551. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  9552. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  9553. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  9554. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  9555. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  9556. if (UO->getOpcode() == UO_AddrOf)
  9557. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  9558. }
  9559. if (SrcAlign >= DestAlign) return;
  9560. Diag(TRange.getBegin(), diag::warn_cast_align)
  9561. << Op->getType() << T
  9562. << static_cast<unsigned>(SrcAlign.getQuantity())
  9563. << static_cast<unsigned>(DestAlign.getQuantity())
  9564. << TRange << Op->getSourceRange();
  9565. }
  9566. /// \brief Check whether this array fits the idiom of a size-one tail padded
  9567. /// array member of a struct.
  9568. ///
  9569. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  9570. /// commonly used to emulate flexible arrays in C89 code.
  9571. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  9572. const NamedDecl *ND) {
  9573. if (Size != 1 || !ND) return false;
  9574. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  9575. if (!FD) return false;
  9576. // Don't consider sizes resulting from macro expansions or template argument
  9577. // substitution to form C89 tail-padded arrays.
  9578. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  9579. while (TInfo) {
  9580. TypeLoc TL = TInfo->getTypeLoc();
  9581. // Look through typedefs.
  9582. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  9583. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  9584. TInfo = TDL->getTypeSourceInfo();
  9585. continue;
  9586. }
  9587. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  9588. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  9589. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  9590. return false;
  9591. }
  9592. break;
  9593. }
  9594. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  9595. if (!RD) return false;
  9596. if (RD->isUnion()) return false;
  9597. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  9598. if (!CRD->isStandardLayout()) return false;
  9599. }
  9600. // See if this is the last field decl in the record.
  9601. const Decl *D = FD;
  9602. while ((D = D->getNextDeclInContext()))
  9603. if (isa<FieldDecl>(D))
  9604. return false;
  9605. return true;
  9606. }
  9607. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  9608. const ArraySubscriptExpr *ASE,
  9609. bool AllowOnePastEnd, bool IndexNegated) {
  9610. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  9611. if (IndexExpr->isValueDependent())
  9612. return;
  9613. const Type *EffectiveType =
  9614. BaseExpr->getType()->getPointeeOrArrayElementType();
  9615. BaseExpr = BaseExpr->IgnoreParenCasts();
  9616. const ConstantArrayType *ArrayTy =
  9617. Context.getAsConstantArrayType(BaseExpr->getType());
  9618. if (!ArrayTy)
  9619. return;
  9620. llvm::APSInt index;
  9621. if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
  9622. return;
  9623. if (IndexNegated)
  9624. index = -index;
  9625. const NamedDecl *ND = nullptr;
  9626. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  9627. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  9628. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  9629. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  9630. if (index.isUnsigned() || !index.isNegative()) {
  9631. llvm::APInt size = ArrayTy->getSize();
  9632. if (!size.isStrictlyPositive())
  9633. return;
  9634. const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
  9635. if (BaseType != EffectiveType) {
  9636. // Make sure we're comparing apples to apples when comparing index to size
  9637. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  9638. uint64_t array_typesize = Context.getTypeSize(BaseType);
  9639. // Handle ptrarith_typesize being zero, such as when casting to void*
  9640. if (!ptrarith_typesize) ptrarith_typesize = 1;
  9641. if (ptrarith_typesize != array_typesize) {
  9642. // There's a cast to a different size type involved
  9643. uint64_t ratio = array_typesize / ptrarith_typesize;
  9644. // TODO: Be smarter about handling cases where array_typesize is not a
  9645. // multiple of ptrarith_typesize
  9646. if (ptrarith_typesize * ratio == array_typesize)
  9647. size *= llvm::APInt(size.getBitWidth(), ratio);
  9648. }
  9649. }
  9650. if (size.getBitWidth() > index.getBitWidth())
  9651. index = index.zext(size.getBitWidth());
  9652. else if (size.getBitWidth() < index.getBitWidth())
  9653. size = size.zext(index.getBitWidth());
  9654. // For array subscripting the index must be less than size, but for pointer
  9655. // arithmetic also allow the index (offset) to be equal to size since
  9656. // computing the next address after the end of the array is legal and
  9657. // commonly done e.g. in C++ iterators and range-based for loops.
  9658. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  9659. return;
  9660. // Also don't warn for arrays of size 1 which are members of some
  9661. // structure. These are often used to approximate flexible arrays in C89
  9662. // code.
  9663. if (IsTailPaddedMemberArray(*this, size, ND))
  9664. return;
  9665. // Suppress the warning if the subscript expression (as identified by the
  9666. // ']' location) and the index expression are both from macro expansions
  9667. // within a system header.
  9668. if (ASE) {
  9669. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  9670. ASE->getRBracketLoc());
  9671. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  9672. SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
  9673. IndexExpr->getLocStart());
  9674. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  9675. return;
  9676. }
  9677. }
  9678. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  9679. if (ASE)
  9680. DiagID = diag::warn_array_index_exceeds_bounds;
  9681. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  9682. PDiag(DiagID) << index.toString(10, true)
  9683. << size.toString(10, true)
  9684. << (unsigned)size.getLimitedValue(~0U)
  9685. << IndexExpr->getSourceRange());
  9686. } else {
  9687. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  9688. if (!ASE) {
  9689. DiagID = diag::warn_ptr_arith_precedes_bounds;
  9690. if (index.isNegative()) index = -index;
  9691. }
  9692. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  9693. PDiag(DiagID) << index.toString(10, true)
  9694. << IndexExpr->getSourceRange());
  9695. }
  9696. if (!ND) {
  9697. // Try harder to find a NamedDecl to point at in the note.
  9698. while (const ArraySubscriptExpr *ASE =
  9699. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  9700. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  9701. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  9702. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  9703. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  9704. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  9705. }
  9706. if (ND)
  9707. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  9708. PDiag(diag::note_array_index_out_of_bounds)
  9709. << ND->getDeclName());
  9710. }
  9711. void Sema::CheckArrayAccess(const Expr *expr) {
  9712. int AllowOnePastEnd = 0;
  9713. while (expr) {
  9714. expr = expr->IgnoreParenImpCasts();
  9715. switch (expr->getStmtClass()) {
  9716. case Stmt::ArraySubscriptExprClass: {
  9717. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  9718. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  9719. AllowOnePastEnd > 0);
  9720. return;
  9721. }
  9722. case Stmt::OMPArraySectionExprClass: {
  9723. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  9724. if (ASE->getLowerBound())
  9725. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  9726. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  9727. return;
  9728. }
  9729. case Stmt::UnaryOperatorClass: {
  9730. // Only unwrap the * and & unary operators
  9731. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  9732. expr = UO->getSubExpr();
  9733. switch (UO->getOpcode()) {
  9734. case UO_AddrOf:
  9735. AllowOnePastEnd++;
  9736. break;
  9737. case UO_Deref:
  9738. AllowOnePastEnd--;
  9739. break;
  9740. default:
  9741. return;
  9742. }
  9743. break;
  9744. }
  9745. case Stmt::ConditionalOperatorClass: {
  9746. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  9747. if (const Expr *lhs = cond->getLHS())
  9748. CheckArrayAccess(lhs);
  9749. if (const Expr *rhs = cond->getRHS())
  9750. CheckArrayAccess(rhs);
  9751. return;
  9752. }
  9753. case Stmt::CXXOperatorCallExprClass: {
  9754. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  9755. for (const auto *Arg : OCE->arguments())
  9756. CheckArrayAccess(Arg);
  9757. return;
  9758. }
  9759. default:
  9760. return;
  9761. }
  9762. }
  9763. }
  9764. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  9765. namespace {
  9766. struct RetainCycleOwner {
  9767. RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
  9768. VarDecl *Variable;
  9769. SourceRange Range;
  9770. SourceLocation Loc;
  9771. bool Indirect;
  9772. void setLocsFrom(Expr *e) {
  9773. Loc = e->getExprLoc();
  9774. Range = e->getSourceRange();
  9775. }
  9776. };
  9777. } // end anonymous namespace
  9778. /// Consider whether capturing the given variable can possibly lead to
  9779. /// a retain cycle.
  9780. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  9781. // In ARC, it's captured strongly iff the variable has __strong
  9782. // lifetime. In MRR, it's captured strongly if the variable is
  9783. // __block and has an appropriate type.
  9784. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  9785. return false;
  9786. owner.Variable = var;
  9787. if (ref)
  9788. owner.setLocsFrom(ref);
  9789. return true;
  9790. }
  9791. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  9792. while (true) {
  9793. e = e->IgnoreParens();
  9794. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  9795. switch (cast->getCastKind()) {
  9796. case CK_BitCast:
  9797. case CK_LValueBitCast:
  9798. case CK_LValueToRValue:
  9799. case CK_ARCReclaimReturnedObject:
  9800. e = cast->getSubExpr();
  9801. continue;
  9802. default:
  9803. return false;
  9804. }
  9805. }
  9806. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  9807. ObjCIvarDecl *ivar = ref->getDecl();
  9808. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  9809. return false;
  9810. // Try to find a retain cycle in the base.
  9811. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  9812. return false;
  9813. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  9814. owner.Indirect = true;
  9815. return true;
  9816. }
  9817. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  9818. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  9819. if (!var) return false;
  9820. return considerVariable(var, ref, owner);
  9821. }
  9822. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  9823. if (member->isArrow()) return false;
  9824. // Don't count this as an indirect ownership.
  9825. e = member->getBase();
  9826. continue;
  9827. }
  9828. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  9829. // Only pay attention to pseudo-objects on property references.
  9830. ObjCPropertyRefExpr *pre
  9831. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  9832. ->IgnoreParens());
  9833. if (!pre) return false;
  9834. if (pre->isImplicitProperty()) return false;
  9835. ObjCPropertyDecl *property = pre->getExplicitProperty();
  9836. if (!property->isRetaining() &&
  9837. !(property->getPropertyIvarDecl() &&
  9838. property->getPropertyIvarDecl()->getType()
  9839. .getObjCLifetime() == Qualifiers::OCL_Strong))
  9840. return false;
  9841. owner.Indirect = true;
  9842. if (pre->isSuperReceiver()) {
  9843. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  9844. if (!owner.Variable)
  9845. return false;
  9846. owner.Loc = pre->getLocation();
  9847. owner.Range = pre->getSourceRange();
  9848. return true;
  9849. }
  9850. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  9851. ->getSourceExpr());
  9852. continue;
  9853. }
  9854. // Array ivars?
  9855. return false;
  9856. }
  9857. }
  9858. namespace {
  9859. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  9860. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  9861. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  9862. Context(Context), Variable(variable), Capturer(nullptr),
  9863. VarWillBeReased(false) {}
  9864. ASTContext &Context;
  9865. VarDecl *Variable;
  9866. Expr *Capturer;
  9867. bool VarWillBeReased;
  9868. void VisitDeclRefExpr(DeclRefExpr *ref) {
  9869. if (ref->getDecl() == Variable && !Capturer)
  9870. Capturer = ref;
  9871. }
  9872. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  9873. if (Capturer) return;
  9874. Visit(ref->getBase());
  9875. if (Capturer && ref->isFreeIvar())
  9876. Capturer = ref;
  9877. }
  9878. void VisitBlockExpr(BlockExpr *block) {
  9879. // Look inside nested blocks
  9880. if (block->getBlockDecl()->capturesVariable(Variable))
  9881. Visit(block->getBlockDecl()->getBody());
  9882. }
  9883. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  9884. if (Capturer) return;
  9885. if (OVE->getSourceExpr())
  9886. Visit(OVE->getSourceExpr());
  9887. }
  9888. void VisitBinaryOperator(BinaryOperator *BinOp) {
  9889. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  9890. return;
  9891. Expr *LHS = BinOp->getLHS();
  9892. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  9893. if (DRE->getDecl() != Variable)
  9894. return;
  9895. if (Expr *RHS = BinOp->getRHS()) {
  9896. RHS = RHS->IgnoreParenCasts();
  9897. llvm::APSInt Value;
  9898. VarWillBeReased =
  9899. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  9900. }
  9901. }
  9902. }
  9903. };
  9904. } // end anonymous namespace
  9905. /// Check whether the given argument is a block which captures a
  9906. /// variable.
  9907. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  9908. assert(owner.Variable && owner.Loc.isValid());
  9909. e = e->IgnoreParenCasts();
  9910. // Look through [^{...} copy] and Block_copy(^{...}).
  9911. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  9912. Selector Cmd = ME->getSelector();
  9913. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  9914. e = ME->getInstanceReceiver();
  9915. if (!e)
  9916. return nullptr;
  9917. e = e->IgnoreParenCasts();
  9918. }
  9919. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  9920. if (CE->getNumArgs() == 1) {
  9921. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  9922. if (Fn) {
  9923. const IdentifierInfo *FnI = Fn->getIdentifier();
  9924. if (FnI && FnI->isStr("_Block_copy")) {
  9925. e = CE->getArg(0)->IgnoreParenCasts();
  9926. }
  9927. }
  9928. }
  9929. }
  9930. BlockExpr *block = dyn_cast<BlockExpr>(e);
  9931. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  9932. return nullptr;
  9933. FindCaptureVisitor visitor(S.Context, owner.Variable);
  9934. visitor.Visit(block->getBlockDecl()->getBody());
  9935. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  9936. }
  9937. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  9938. RetainCycleOwner &owner) {
  9939. assert(capturer);
  9940. assert(owner.Variable && owner.Loc.isValid());
  9941. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  9942. << owner.Variable << capturer->getSourceRange();
  9943. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  9944. << owner.Indirect << owner.Range;
  9945. }
  9946. /// Check for a keyword selector that starts with the word 'add' or
  9947. /// 'set'.
  9948. static bool isSetterLikeSelector(Selector sel) {
  9949. if (sel.isUnarySelector()) return false;
  9950. StringRef str = sel.getNameForSlot(0);
  9951. while (!str.empty() && str.front() == '_') str = str.substr(1);
  9952. if (str.startswith("set"))
  9953. str = str.substr(3);
  9954. else if (str.startswith("add")) {
  9955. // Specially whitelist 'addOperationWithBlock:'.
  9956. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  9957. return false;
  9958. str = str.substr(3);
  9959. }
  9960. else
  9961. return false;
  9962. if (str.empty()) return true;
  9963. return !isLowercase(str.front());
  9964. }
  9965. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  9966. ObjCMessageExpr *Message) {
  9967. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  9968. Message->getReceiverInterface(),
  9969. NSAPI::ClassId_NSMutableArray);
  9970. if (!IsMutableArray) {
  9971. return None;
  9972. }
  9973. Selector Sel = Message->getSelector();
  9974. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  9975. S.NSAPIObj->getNSArrayMethodKind(Sel);
  9976. if (!MKOpt) {
  9977. return None;
  9978. }
  9979. NSAPI::NSArrayMethodKind MK = *MKOpt;
  9980. switch (MK) {
  9981. case NSAPI::NSMutableArr_addObject:
  9982. case NSAPI::NSMutableArr_insertObjectAtIndex:
  9983. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  9984. return 0;
  9985. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  9986. return 1;
  9987. default:
  9988. return None;
  9989. }
  9990. return None;
  9991. }
  9992. static
  9993. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  9994. ObjCMessageExpr *Message) {
  9995. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  9996. Message->getReceiverInterface(),
  9997. NSAPI::ClassId_NSMutableDictionary);
  9998. if (!IsMutableDictionary) {
  9999. return None;
  10000. }
  10001. Selector Sel = Message->getSelector();
  10002. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  10003. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  10004. if (!MKOpt) {
  10005. return None;
  10006. }
  10007. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  10008. switch (MK) {
  10009. case NSAPI::NSMutableDict_setObjectForKey:
  10010. case NSAPI::NSMutableDict_setValueForKey:
  10011. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  10012. return 0;
  10013. default:
  10014. return None;
  10015. }
  10016. return None;
  10017. }
  10018. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  10019. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  10020. Message->getReceiverInterface(),
  10021. NSAPI::ClassId_NSMutableSet);
  10022. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  10023. Message->getReceiverInterface(),
  10024. NSAPI::ClassId_NSMutableOrderedSet);
  10025. if (!IsMutableSet && !IsMutableOrderedSet) {
  10026. return None;
  10027. }
  10028. Selector Sel = Message->getSelector();
  10029. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  10030. if (!MKOpt) {
  10031. return None;
  10032. }
  10033. NSAPI::NSSetMethodKind MK = *MKOpt;
  10034. switch (MK) {
  10035. case NSAPI::NSMutableSet_addObject:
  10036. case NSAPI::NSOrderedSet_setObjectAtIndex:
  10037. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  10038. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  10039. return 0;
  10040. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  10041. return 1;
  10042. }
  10043. return None;
  10044. }
  10045. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  10046. if (!Message->isInstanceMessage()) {
  10047. return;
  10048. }
  10049. Optional<int> ArgOpt;
  10050. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  10051. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  10052. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  10053. return;
  10054. }
  10055. int ArgIndex = *ArgOpt;
  10056. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  10057. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  10058. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  10059. }
  10060. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  10061. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  10062. if (ArgRE->isObjCSelfExpr()) {
  10063. Diag(Message->getSourceRange().getBegin(),
  10064. diag::warn_objc_circular_container)
  10065. << ArgRE->getDecl()->getName() << StringRef("super");
  10066. }
  10067. }
  10068. } else {
  10069. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  10070. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  10071. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  10072. }
  10073. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  10074. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  10075. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  10076. ValueDecl *Decl = ReceiverRE->getDecl();
  10077. Diag(Message->getSourceRange().getBegin(),
  10078. diag::warn_objc_circular_container)
  10079. << Decl->getName() << Decl->getName();
  10080. if (!ArgRE->isObjCSelfExpr()) {
  10081. Diag(Decl->getLocation(),
  10082. diag::note_objc_circular_container_declared_here)
  10083. << Decl->getName();
  10084. }
  10085. }
  10086. }
  10087. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  10088. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  10089. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  10090. ObjCIvarDecl *Decl = IvarRE->getDecl();
  10091. Diag(Message->getSourceRange().getBegin(),
  10092. diag::warn_objc_circular_container)
  10093. << Decl->getName() << Decl->getName();
  10094. Diag(Decl->getLocation(),
  10095. diag::note_objc_circular_container_declared_here)
  10096. << Decl->getName();
  10097. }
  10098. }
  10099. }
  10100. }
  10101. }
  10102. /// Check a message send to see if it's likely to cause a retain cycle.
  10103. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  10104. // Only check instance methods whose selector looks like a setter.
  10105. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  10106. return;
  10107. // Try to find a variable that the receiver is strongly owned by.
  10108. RetainCycleOwner owner;
  10109. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  10110. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  10111. return;
  10112. } else {
  10113. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  10114. owner.Variable = getCurMethodDecl()->getSelfDecl();
  10115. owner.Loc = msg->getSuperLoc();
  10116. owner.Range = msg->getSuperLoc();
  10117. }
  10118. // Check whether the receiver is captured by any of the arguments.
  10119. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
  10120. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
  10121. return diagnoseRetainCycle(*this, capturer, owner);
  10122. }
  10123. /// Check a property assign to see if it's likely to cause a retain cycle.
  10124. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  10125. RetainCycleOwner owner;
  10126. if (!findRetainCycleOwner(*this, receiver, owner))
  10127. return;
  10128. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  10129. diagnoseRetainCycle(*this, capturer, owner);
  10130. }
  10131. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  10132. RetainCycleOwner Owner;
  10133. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  10134. return;
  10135. // Because we don't have an expression for the variable, we have to set the
  10136. // location explicitly here.
  10137. Owner.Loc = Var->getLocation();
  10138. Owner.Range = Var->getSourceRange();
  10139. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  10140. diagnoseRetainCycle(*this, Capturer, Owner);
  10141. }
  10142. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  10143. Expr *RHS, bool isProperty) {
  10144. // Check if RHS is an Objective-C object literal, which also can get
  10145. // immediately zapped in a weak reference. Note that we explicitly
  10146. // allow ObjCStringLiterals, since those are designed to never really die.
  10147. RHS = RHS->IgnoreParenImpCasts();
  10148. // This enum needs to match with the 'select' in
  10149. // warn_objc_arc_literal_assign (off-by-1).
  10150. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  10151. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  10152. return false;
  10153. S.Diag(Loc, diag::warn_arc_literal_assign)
  10154. << (unsigned) Kind
  10155. << (isProperty ? 0 : 1)
  10156. << RHS->getSourceRange();
  10157. return true;
  10158. }
  10159. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  10160. Qualifiers::ObjCLifetime LT,
  10161. Expr *RHS, bool isProperty) {
  10162. // Strip off any implicit cast added to get to the one ARC-specific.
  10163. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  10164. if (cast->getCastKind() == CK_ARCConsumeObject) {
  10165. S.Diag(Loc, diag::warn_arc_retained_assign)
  10166. << (LT == Qualifiers::OCL_ExplicitNone)
  10167. << (isProperty ? 0 : 1)
  10168. << RHS->getSourceRange();
  10169. return true;
  10170. }
  10171. RHS = cast->getSubExpr();
  10172. }
  10173. if (LT == Qualifiers::OCL_Weak &&
  10174. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  10175. return true;
  10176. return false;
  10177. }
  10178. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  10179. QualType LHS, Expr *RHS) {
  10180. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  10181. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  10182. return false;
  10183. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  10184. return true;
  10185. return false;
  10186. }
  10187. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  10188. Expr *LHS, Expr *RHS) {
  10189. QualType LHSType;
  10190. // PropertyRef on LHS type need be directly obtained from
  10191. // its declaration as it has a PseudoType.
  10192. ObjCPropertyRefExpr *PRE
  10193. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  10194. if (PRE && !PRE->isImplicitProperty()) {
  10195. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  10196. if (PD)
  10197. LHSType = PD->getType();
  10198. }
  10199. if (LHSType.isNull())
  10200. LHSType = LHS->getType();
  10201. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  10202. if (LT == Qualifiers::OCL_Weak) {
  10203. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  10204. getCurFunction()->markSafeWeakUse(LHS);
  10205. }
  10206. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  10207. return;
  10208. // FIXME. Check for other life times.
  10209. if (LT != Qualifiers::OCL_None)
  10210. return;
  10211. if (PRE) {
  10212. if (PRE->isImplicitProperty())
  10213. return;
  10214. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  10215. if (!PD)
  10216. return;
  10217. unsigned Attributes = PD->getPropertyAttributes();
  10218. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  10219. // when 'assign' attribute was not explicitly specified
  10220. // by user, ignore it and rely on property type itself
  10221. // for lifetime info.
  10222. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  10223. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  10224. LHSType->isObjCRetainableType())
  10225. return;
  10226. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  10227. if (cast->getCastKind() == CK_ARCConsumeObject) {
  10228. Diag(Loc, diag::warn_arc_retained_property_assign)
  10229. << RHS->getSourceRange();
  10230. return;
  10231. }
  10232. RHS = cast->getSubExpr();
  10233. }
  10234. }
  10235. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  10236. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  10237. return;
  10238. }
  10239. }
  10240. }
  10241. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  10242. namespace {
  10243. bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  10244. SourceLocation StmtLoc,
  10245. const NullStmt *Body) {
  10246. // Do not warn if the body is a macro that expands to nothing, e.g:
  10247. //
  10248. // #define CALL(x)
  10249. // if (condition)
  10250. // CALL(0);
  10251. //
  10252. if (Body->hasLeadingEmptyMacro())
  10253. return false;
  10254. // Get line numbers of statement and body.
  10255. bool StmtLineInvalid;
  10256. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  10257. &StmtLineInvalid);
  10258. if (StmtLineInvalid)
  10259. return false;
  10260. bool BodyLineInvalid;
  10261. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  10262. &BodyLineInvalid);
  10263. if (BodyLineInvalid)
  10264. return false;
  10265. // Warn if null statement and body are on the same line.
  10266. if (StmtLine != BodyLine)
  10267. return false;
  10268. return true;
  10269. }
  10270. } // end anonymous namespace
  10271. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  10272. const Stmt *Body,
  10273. unsigned DiagID) {
  10274. // Since this is a syntactic check, don't emit diagnostic for template
  10275. // instantiations, this just adds noise.
  10276. if (CurrentInstantiationScope)
  10277. return;
  10278. // The body should be a null statement.
  10279. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  10280. if (!NBody)
  10281. return;
  10282. // Do the usual checks.
  10283. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  10284. return;
  10285. Diag(NBody->getSemiLoc(), DiagID);
  10286. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  10287. }
  10288. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  10289. const Stmt *PossibleBody) {
  10290. assert(!CurrentInstantiationScope); // Ensured by caller
  10291. SourceLocation StmtLoc;
  10292. const Stmt *Body;
  10293. unsigned DiagID;
  10294. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  10295. StmtLoc = FS->getRParenLoc();
  10296. Body = FS->getBody();
  10297. DiagID = diag::warn_empty_for_body;
  10298. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  10299. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  10300. Body = WS->getBody();
  10301. DiagID = diag::warn_empty_while_body;
  10302. } else
  10303. return; // Neither `for' nor `while'.
  10304. // The body should be a null statement.
  10305. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  10306. if (!NBody)
  10307. return;
  10308. // Skip expensive checks if diagnostic is disabled.
  10309. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  10310. return;
  10311. // Do the usual checks.
  10312. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  10313. return;
  10314. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  10315. // noise level low, emit diagnostics only if for/while is followed by a
  10316. // CompoundStmt, e.g.:
  10317. // for (int i = 0; i < n; i++);
  10318. // {
  10319. // a(i);
  10320. // }
  10321. // or if for/while is followed by a statement with more indentation
  10322. // than for/while itself:
  10323. // for (int i = 0; i < n; i++);
  10324. // a(i);
  10325. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  10326. if (!ProbableTypo) {
  10327. bool BodyColInvalid;
  10328. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  10329. PossibleBody->getLocStart(),
  10330. &BodyColInvalid);
  10331. if (BodyColInvalid)
  10332. return;
  10333. bool StmtColInvalid;
  10334. unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
  10335. S->getLocStart(),
  10336. &StmtColInvalid);
  10337. if (StmtColInvalid)
  10338. return;
  10339. if (BodyCol > StmtCol)
  10340. ProbableTypo = true;
  10341. }
  10342. if (ProbableTypo) {
  10343. Diag(NBody->getSemiLoc(), DiagID);
  10344. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  10345. }
  10346. }
  10347. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  10348. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  10349. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  10350. SourceLocation OpLoc) {
  10351. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  10352. return;
  10353. if (inTemplateInstantiation())
  10354. return;
  10355. // Strip parens and casts away.
  10356. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  10357. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  10358. // Check for a call expression
  10359. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  10360. if (!CE || CE->getNumArgs() != 1)
  10361. return;
  10362. // Check for a call to std::move
  10363. if (!CE->isCallToStdMove())
  10364. return;
  10365. // Get argument from std::move
  10366. RHSExpr = CE->getArg(0);
  10367. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  10368. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  10369. // Two DeclRefExpr's, check that the decls are the same.
  10370. if (LHSDeclRef && RHSDeclRef) {
  10371. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  10372. return;
  10373. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  10374. RHSDeclRef->getDecl()->getCanonicalDecl())
  10375. return;
  10376. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  10377. << LHSExpr->getSourceRange()
  10378. << RHSExpr->getSourceRange();
  10379. return;
  10380. }
  10381. // Member variables require a different approach to check for self moves.
  10382. // MemberExpr's are the same if every nested MemberExpr refers to the same
  10383. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  10384. // the base Expr's are CXXThisExpr's.
  10385. const Expr *LHSBase = LHSExpr;
  10386. const Expr *RHSBase = RHSExpr;
  10387. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  10388. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  10389. if (!LHSME || !RHSME)
  10390. return;
  10391. while (LHSME && RHSME) {
  10392. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  10393. RHSME->getMemberDecl()->getCanonicalDecl())
  10394. return;
  10395. LHSBase = LHSME->getBase();
  10396. RHSBase = RHSME->getBase();
  10397. LHSME = dyn_cast<MemberExpr>(LHSBase);
  10398. RHSME = dyn_cast<MemberExpr>(RHSBase);
  10399. }
  10400. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  10401. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  10402. if (LHSDeclRef && RHSDeclRef) {
  10403. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  10404. return;
  10405. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  10406. RHSDeclRef->getDecl()->getCanonicalDecl())
  10407. return;
  10408. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  10409. << LHSExpr->getSourceRange()
  10410. << RHSExpr->getSourceRange();
  10411. return;
  10412. }
  10413. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  10414. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  10415. << LHSExpr->getSourceRange()
  10416. << RHSExpr->getSourceRange();
  10417. }
  10418. //===--- Layout compatibility ----------------------------------------------//
  10419. namespace {
  10420. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  10421. /// \brief Check if two enumeration types are layout-compatible.
  10422. bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  10423. // C++11 [dcl.enum] p8:
  10424. // Two enumeration types are layout-compatible if they have the same
  10425. // underlying type.
  10426. return ED1->isComplete() && ED2->isComplete() &&
  10427. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  10428. }
  10429. /// \brief Check if two fields are layout-compatible.
  10430. bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
  10431. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  10432. return false;
  10433. if (Field1->isBitField() != Field2->isBitField())
  10434. return false;
  10435. if (Field1->isBitField()) {
  10436. // Make sure that the bit-fields are the same length.
  10437. unsigned Bits1 = Field1->getBitWidthValue(C);
  10438. unsigned Bits2 = Field2->getBitWidthValue(C);
  10439. if (Bits1 != Bits2)
  10440. return false;
  10441. }
  10442. return true;
  10443. }
  10444. /// \brief Check if two standard-layout structs are layout-compatible.
  10445. /// (C++11 [class.mem] p17)
  10446. bool isLayoutCompatibleStruct(ASTContext &C,
  10447. RecordDecl *RD1,
  10448. RecordDecl *RD2) {
  10449. // If both records are C++ classes, check that base classes match.
  10450. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  10451. // If one of records is a CXXRecordDecl we are in C++ mode,
  10452. // thus the other one is a CXXRecordDecl, too.
  10453. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  10454. // Check number of base classes.
  10455. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  10456. return false;
  10457. // Check the base classes.
  10458. for (CXXRecordDecl::base_class_const_iterator
  10459. Base1 = D1CXX->bases_begin(),
  10460. BaseEnd1 = D1CXX->bases_end(),
  10461. Base2 = D2CXX->bases_begin();
  10462. Base1 != BaseEnd1;
  10463. ++Base1, ++Base2) {
  10464. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  10465. return false;
  10466. }
  10467. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  10468. // If only RD2 is a C++ class, it should have zero base classes.
  10469. if (D2CXX->getNumBases() > 0)
  10470. return false;
  10471. }
  10472. // Check the fields.
  10473. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  10474. Field2End = RD2->field_end(),
  10475. Field1 = RD1->field_begin(),
  10476. Field1End = RD1->field_end();
  10477. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  10478. if (!isLayoutCompatible(C, *Field1, *Field2))
  10479. return false;
  10480. }
  10481. if (Field1 != Field1End || Field2 != Field2End)
  10482. return false;
  10483. return true;
  10484. }
  10485. /// \brief Check if two standard-layout unions are layout-compatible.
  10486. /// (C++11 [class.mem] p18)
  10487. bool isLayoutCompatibleUnion(ASTContext &C,
  10488. RecordDecl *RD1,
  10489. RecordDecl *RD2) {
  10490. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  10491. for (auto *Field2 : RD2->fields())
  10492. UnmatchedFields.insert(Field2);
  10493. for (auto *Field1 : RD1->fields()) {
  10494. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  10495. I = UnmatchedFields.begin(),
  10496. E = UnmatchedFields.end();
  10497. for ( ; I != E; ++I) {
  10498. if (isLayoutCompatible(C, Field1, *I)) {
  10499. bool Result = UnmatchedFields.erase(*I);
  10500. (void) Result;
  10501. assert(Result);
  10502. break;
  10503. }
  10504. }
  10505. if (I == E)
  10506. return false;
  10507. }
  10508. return UnmatchedFields.empty();
  10509. }
  10510. bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
  10511. if (RD1->isUnion() != RD2->isUnion())
  10512. return false;
  10513. if (RD1->isUnion())
  10514. return isLayoutCompatibleUnion(C, RD1, RD2);
  10515. else
  10516. return isLayoutCompatibleStruct(C, RD1, RD2);
  10517. }
  10518. /// \brief Check if two types are layout-compatible in C++11 sense.
  10519. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  10520. if (T1.isNull() || T2.isNull())
  10521. return false;
  10522. // C++11 [basic.types] p11:
  10523. // If two types T1 and T2 are the same type, then T1 and T2 are
  10524. // layout-compatible types.
  10525. if (C.hasSameType(T1, T2))
  10526. return true;
  10527. T1 = T1.getCanonicalType().getUnqualifiedType();
  10528. T2 = T2.getCanonicalType().getUnqualifiedType();
  10529. const Type::TypeClass TC1 = T1->getTypeClass();
  10530. const Type::TypeClass TC2 = T2->getTypeClass();
  10531. if (TC1 != TC2)
  10532. return false;
  10533. if (TC1 == Type::Enum) {
  10534. return isLayoutCompatible(C,
  10535. cast<EnumType>(T1)->getDecl(),
  10536. cast<EnumType>(T2)->getDecl());
  10537. } else if (TC1 == Type::Record) {
  10538. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  10539. return false;
  10540. return isLayoutCompatible(C,
  10541. cast<RecordType>(T1)->getDecl(),
  10542. cast<RecordType>(T2)->getDecl());
  10543. }
  10544. return false;
  10545. }
  10546. } // end anonymous namespace
  10547. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  10548. namespace {
  10549. /// \brief Given a type tag expression find the type tag itself.
  10550. ///
  10551. /// \param TypeExpr Type tag expression, as it appears in user's code.
  10552. ///
  10553. /// \param VD Declaration of an identifier that appears in a type tag.
  10554. ///
  10555. /// \param MagicValue Type tag magic value.
  10556. bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  10557. const ValueDecl **VD, uint64_t *MagicValue) {
  10558. while(true) {
  10559. if (!TypeExpr)
  10560. return false;
  10561. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  10562. switch (TypeExpr->getStmtClass()) {
  10563. case Stmt::UnaryOperatorClass: {
  10564. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  10565. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  10566. TypeExpr = UO->getSubExpr();
  10567. continue;
  10568. }
  10569. return false;
  10570. }
  10571. case Stmt::DeclRefExprClass: {
  10572. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  10573. *VD = DRE->getDecl();
  10574. return true;
  10575. }
  10576. case Stmt::IntegerLiteralClass: {
  10577. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  10578. llvm::APInt MagicValueAPInt = IL->getValue();
  10579. if (MagicValueAPInt.getActiveBits() <= 64) {
  10580. *MagicValue = MagicValueAPInt.getZExtValue();
  10581. return true;
  10582. } else
  10583. return false;
  10584. }
  10585. case Stmt::BinaryConditionalOperatorClass:
  10586. case Stmt::ConditionalOperatorClass: {
  10587. const AbstractConditionalOperator *ACO =
  10588. cast<AbstractConditionalOperator>(TypeExpr);
  10589. bool Result;
  10590. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  10591. if (Result)
  10592. TypeExpr = ACO->getTrueExpr();
  10593. else
  10594. TypeExpr = ACO->getFalseExpr();
  10595. continue;
  10596. }
  10597. return false;
  10598. }
  10599. case Stmt::BinaryOperatorClass: {
  10600. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  10601. if (BO->getOpcode() == BO_Comma) {
  10602. TypeExpr = BO->getRHS();
  10603. continue;
  10604. }
  10605. return false;
  10606. }
  10607. default:
  10608. return false;
  10609. }
  10610. }
  10611. }
  10612. /// \brief Retrieve the C type corresponding to type tag TypeExpr.
  10613. ///
  10614. /// \param TypeExpr Expression that specifies a type tag.
  10615. ///
  10616. /// \param MagicValues Registered magic values.
  10617. ///
  10618. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  10619. /// kind.
  10620. ///
  10621. /// \param TypeInfo Information about the corresponding C type.
  10622. ///
  10623. /// \returns true if the corresponding C type was found.
  10624. bool GetMatchingCType(
  10625. const IdentifierInfo *ArgumentKind,
  10626. const Expr *TypeExpr, const ASTContext &Ctx,
  10627. const llvm::DenseMap<Sema::TypeTagMagicValue,
  10628. Sema::TypeTagData> *MagicValues,
  10629. bool &FoundWrongKind,
  10630. Sema::TypeTagData &TypeInfo) {
  10631. FoundWrongKind = false;
  10632. // Variable declaration that has type_tag_for_datatype attribute.
  10633. const ValueDecl *VD = nullptr;
  10634. uint64_t MagicValue;
  10635. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  10636. return false;
  10637. if (VD) {
  10638. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  10639. if (I->getArgumentKind() != ArgumentKind) {
  10640. FoundWrongKind = true;
  10641. return false;
  10642. }
  10643. TypeInfo.Type = I->getMatchingCType();
  10644. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  10645. TypeInfo.MustBeNull = I->getMustBeNull();
  10646. return true;
  10647. }
  10648. return false;
  10649. }
  10650. if (!MagicValues)
  10651. return false;
  10652. llvm::DenseMap<Sema::TypeTagMagicValue,
  10653. Sema::TypeTagData>::const_iterator I =
  10654. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  10655. if (I == MagicValues->end())
  10656. return false;
  10657. TypeInfo = I->second;
  10658. return true;
  10659. }
  10660. } // end anonymous namespace
  10661. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  10662. uint64_t MagicValue, QualType Type,
  10663. bool LayoutCompatible,
  10664. bool MustBeNull) {
  10665. if (!TypeTagForDatatypeMagicValues)
  10666. TypeTagForDatatypeMagicValues.reset(
  10667. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  10668. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  10669. (*TypeTagForDatatypeMagicValues)[Magic] =
  10670. TypeTagData(Type, LayoutCompatible, MustBeNull);
  10671. }
  10672. namespace {
  10673. bool IsSameCharType(QualType T1, QualType T2) {
  10674. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  10675. if (!BT1)
  10676. return false;
  10677. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  10678. if (!BT2)
  10679. return false;
  10680. BuiltinType::Kind T1Kind = BT1->getKind();
  10681. BuiltinType::Kind T2Kind = BT2->getKind();
  10682. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  10683. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  10684. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  10685. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  10686. }
  10687. } // end anonymous namespace
  10688. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  10689. const Expr * const *ExprArgs) {
  10690. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  10691. bool IsPointerAttr = Attr->getIsPointer();
  10692. const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
  10693. bool FoundWrongKind;
  10694. TypeTagData TypeInfo;
  10695. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  10696. TypeTagForDatatypeMagicValues.get(),
  10697. FoundWrongKind, TypeInfo)) {
  10698. if (FoundWrongKind)
  10699. Diag(TypeTagExpr->getExprLoc(),
  10700. diag::warn_type_tag_for_datatype_wrong_kind)
  10701. << TypeTagExpr->getSourceRange();
  10702. return;
  10703. }
  10704. const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
  10705. if (IsPointerAttr) {
  10706. // Skip implicit cast of pointer to `void *' (as a function argument).
  10707. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  10708. if (ICE->getType()->isVoidPointerType() &&
  10709. ICE->getCastKind() == CK_BitCast)
  10710. ArgumentExpr = ICE->getSubExpr();
  10711. }
  10712. QualType ArgumentType = ArgumentExpr->getType();
  10713. // Passing a `void*' pointer shouldn't trigger a warning.
  10714. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  10715. return;
  10716. if (TypeInfo.MustBeNull) {
  10717. // Type tag with matching void type requires a null pointer.
  10718. if (!ArgumentExpr->isNullPointerConstant(Context,
  10719. Expr::NPC_ValueDependentIsNotNull)) {
  10720. Diag(ArgumentExpr->getExprLoc(),
  10721. diag::warn_type_safety_null_pointer_required)
  10722. << ArgumentKind->getName()
  10723. << ArgumentExpr->getSourceRange()
  10724. << TypeTagExpr->getSourceRange();
  10725. }
  10726. return;
  10727. }
  10728. QualType RequiredType = TypeInfo.Type;
  10729. if (IsPointerAttr)
  10730. RequiredType = Context.getPointerType(RequiredType);
  10731. bool mismatch = false;
  10732. if (!TypeInfo.LayoutCompatible) {
  10733. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  10734. // C++11 [basic.fundamental] p1:
  10735. // Plain char, signed char, and unsigned char are three distinct types.
  10736. //
  10737. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  10738. // char' depending on the current char signedness mode.
  10739. if (mismatch)
  10740. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  10741. RequiredType->getPointeeType())) ||
  10742. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  10743. mismatch = false;
  10744. } else
  10745. if (IsPointerAttr)
  10746. mismatch = !isLayoutCompatible(Context,
  10747. ArgumentType->getPointeeType(),
  10748. RequiredType->getPointeeType());
  10749. else
  10750. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  10751. if (mismatch)
  10752. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  10753. << ArgumentType << ArgumentKind
  10754. << TypeInfo.LayoutCompatible << RequiredType
  10755. << ArgumentExpr->getSourceRange()
  10756. << TypeTagExpr->getSourceRange();
  10757. }
  10758. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  10759. CharUnits Alignment) {
  10760. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  10761. }
  10762. void Sema::DiagnoseMisalignedMembers() {
  10763. for (MisalignedMember &m : MisalignedMembers) {
  10764. const NamedDecl *ND = m.RD;
  10765. if (ND->getName().empty()) {
  10766. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  10767. ND = TD;
  10768. }
  10769. Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
  10770. << m.MD << ND << m.E->getSourceRange();
  10771. }
  10772. MisalignedMembers.clear();
  10773. }
  10774. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  10775. E = E->IgnoreParens();
  10776. if (!T->isPointerType() && !T->isIntegerType())
  10777. return;
  10778. if (isa<UnaryOperator>(E) &&
  10779. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  10780. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  10781. if (isa<MemberExpr>(Op)) {
  10782. auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
  10783. MisalignedMember(Op));
  10784. if (MA != MisalignedMembers.end() &&
  10785. (T->isIntegerType() ||
  10786. (T->isPointerType() &&
  10787. Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
  10788. MisalignedMembers.erase(MA);
  10789. }
  10790. }
  10791. }
  10792. void Sema::RefersToMemberWithReducedAlignment(
  10793. Expr *E,
  10794. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  10795. Action) {
  10796. const auto *ME = dyn_cast<MemberExpr>(E);
  10797. if (!ME)
  10798. return;
  10799. // No need to check expressions with an __unaligned-qualified type.
  10800. if (E->getType().getQualifiers().hasUnaligned())
  10801. return;
  10802. // For a chain of MemberExpr like "a.b.c.d" this list
  10803. // will keep FieldDecl's like [d, c, b].
  10804. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  10805. const MemberExpr *TopME = nullptr;
  10806. bool AnyIsPacked = false;
  10807. do {
  10808. QualType BaseType = ME->getBase()->getType();
  10809. if (ME->isArrow())
  10810. BaseType = BaseType->getPointeeType();
  10811. RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
  10812. if (RD->isInvalidDecl())
  10813. return;
  10814. ValueDecl *MD = ME->getMemberDecl();
  10815. auto *FD = dyn_cast<FieldDecl>(MD);
  10816. // We do not care about non-data members.
  10817. if (!FD || FD->isInvalidDecl())
  10818. return;
  10819. AnyIsPacked =
  10820. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  10821. ReverseMemberChain.push_back(FD);
  10822. TopME = ME;
  10823. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  10824. } while (ME);
  10825. assert(TopME && "We did not compute a topmost MemberExpr!");
  10826. // Not the scope of this diagnostic.
  10827. if (!AnyIsPacked)
  10828. return;
  10829. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  10830. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  10831. // TODO: The innermost base of the member expression may be too complicated.
  10832. // For now, just disregard these cases. This is left for future
  10833. // improvement.
  10834. if (!DRE && !isa<CXXThisExpr>(TopBase))
  10835. return;
  10836. // Alignment expected by the whole expression.
  10837. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  10838. // No need to do anything else with this case.
  10839. if (ExpectedAlignment.isOne())
  10840. return;
  10841. // Synthesize offset of the whole access.
  10842. CharUnits Offset;
  10843. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  10844. I++) {
  10845. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  10846. }
  10847. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  10848. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  10849. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  10850. // The base expression of the innermost MemberExpr may give
  10851. // stronger guarantees than the class containing the member.
  10852. if (DRE && !TopME->isArrow()) {
  10853. const ValueDecl *VD = DRE->getDecl();
  10854. if (!VD->getType()->isReferenceType())
  10855. CompleteObjectAlignment =
  10856. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  10857. }
  10858. // Check if the synthesized offset fulfills the alignment.
  10859. if (Offset % ExpectedAlignment != 0 ||
  10860. // It may fulfill the offset it but the effective alignment may still be
  10861. // lower than the expected expression alignment.
  10862. CompleteObjectAlignment < ExpectedAlignment) {
  10863. // If this happens, we want to determine a sensible culprit of this.
  10864. // Intuitively, watching the chain of member expressions from right to
  10865. // left, we start with the required alignment (as required by the field
  10866. // type) but some packed attribute in that chain has reduced the alignment.
  10867. // It may happen that another packed structure increases it again. But if
  10868. // we are here such increase has not been enough. So pointing the first
  10869. // FieldDecl that either is packed or else its RecordDecl is,
  10870. // seems reasonable.
  10871. FieldDecl *FD = nullptr;
  10872. CharUnits Alignment;
  10873. for (FieldDecl *FDI : ReverseMemberChain) {
  10874. if (FDI->hasAttr<PackedAttr>() ||
  10875. FDI->getParent()->hasAttr<PackedAttr>()) {
  10876. FD = FDI;
  10877. Alignment = std::min(
  10878. Context.getTypeAlignInChars(FD->getType()),
  10879. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  10880. break;
  10881. }
  10882. }
  10883. assert(FD && "We did not find a packed FieldDecl!");
  10884. Action(E, FD->getParent(), FD, Alignment);
  10885. }
  10886. }
  10887. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  10888. using namespace std::placeholders;
  10889. RefersToMemberWithReducedAlignment(
  10890. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  10891. _2, _3, _4));
  10892. }