SemaChecking.cpp 457 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500
  1. //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements extra semantic analysis beyond what is enforced
  11. // by the C type system.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/AST/APValue.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/Attr.h"
  17. #include "clang/AST/AttrIterator.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclBase.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/DeclarationName.h"
  24. #include "clang/AST/EvaluatedExprVisitor.h"
  25. #include "clang/AST/Expr.h"
  26. #include "clang/AST/ExprCXX.h"
  27. #include "clang/AST/ExprObjC.h"
  28. #include "clang/AST/ExprOpenMP.h"
  29. #include "clang/AST/NSAPI.h"
  30. #include "clang/AST/OperationKinds.h"
  31. #include "clang/AST/Stmt.h"
  32. #include "clang/AST/TemplateBase.h"
  33. #include "clang/AST/Type.h"
  34. #include "clang/AST/TypeLoc.h"
  35. #include "clang/AST/UnresolvedSet.h"
  36. #include "clang/Analysis/Analyses/FormatString.h"
  37. #include "clang/Basic/AddressSpaces.h"
  38. #include "clang/Basic/CharInfo.h"
  39. #include "clang/Basic/Diagnostic.h"
  40. #include "clang/Basic/IdentifierTable.h"
  41. #include "clang/Basic/LLVM.h"
  42. #include "clang/Basic/LangOptions.h"
  43. #include "clang/Basic/OpenCLOptions.h"
  44. #include "clang/Basic/OperatorKinds.h"
  45. #include "clang/Basic/PartialDiagnostic.h"
  46. #include "clang/Basic/SourceLocation.h"
  47. #include "clang/Basic/SourceManager.h"
  48. #include "clang/Basic/Specifiers.h"
  49. #include "clang/Basic/SyncScope.h"
  50. #include "clang/Basic/TargetBuiltins.h"
  51. #include "clang/Basic/TargetCXXABI.h"
  52. #include "clang/Basic/TargetInfo.h"
  53. #include "clang/Basic/TypeTraits.h"
  54. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  55. #include "clang/Sema/Initialization.h"
  56. #include "clang/Sema/Lookup.h"
  57. #include "clang/Sema/Ownership.h"
  58. #include "clang/Sema/Scope.h"
  59. #include "clang/Sema/ScopeInfo.h"
  60. #include "clang/Sema/Sema.h"
  61. #include "clang/Sema/SemaInternal.h"
  62. #include "llvm/ADT/APFloat.h"
  63. #include "llvm/ADT/APInt.h"
  64. #include "llvm/ADT/APSInt.h"
  65. #include "llvm/ADT/ArrayRef.h"
  66. #include "llvm/ADT/DenseMap.h"
  67. #include "llvm/ADT/FoldingSet.h"
  68. #include "llvm/ADT/None.h"
  69. #include "llvm/ADT/Optional.h"
  70. #include "llvm/ADT/STLExtras.h"
  71. #include "llvm/ADT/SmallBitVector.h"
  72. #include "llvm/ADT/SmallPtrSet.h"
  73. #include "llvm/ADT/SmallString.h"
  74. #include "llvm/ADT/SmallVector.h"
  75. #include "llvm/ADT/StringRef.h"
  76. #include "llvm/ADT/StringSwitch.h"
  77. #include "llvm/ADT/Triple.h"
  78. #include "llvm/Support/AtomicOrdering.h"
  79. #include "llvm/Support/Casting.h"
  80. #include "llvm/Support/Compiler.h"
  81. #include "llvm/Support/ConvertUTF.h"
  82. #include "llvm/Support/ErrorHandling.h"
  83. #include "llvm/Support/Format.h"
  84. #include "llvm/Support/Locale.h"
  85. #include "llvm/Support/MathExtras.h"
  86. #include "llvm/Support/raw_ostream.h"
  87. #include <algorithm>
  88. #include <cassert>
  89. #include <cstddef>
  90. #include <cstdint>
  91. #include <functional>
  92. #include <limits>
  93. #include <string>
  94. #include <tuple>
  95. #include <utility>
  96. using namespace clang;
  97. using namespace sema;
  98. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  99. unsigned ByteNo) const {
  100. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  101. Context.getTargetInfo());
  102. }
  103. /// Checks that a call expression's argument count is the desired number.
  104. /// This is useful when doing custom type-checking. Returns true on error.
  105. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  106. unsigned argCount = call->getNumArgs();
  107. if (argCount == desiredArgCount) return false;
  108. if (argCount < desiredArgCount)
  109. return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
  110. << 0 /*function call*/ << desiredArgCount << argCount
  111. << call->getSourceRange();
  112. // Highlight all the excess arguments.
  113. SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
  114. call->getArg(argCount - 1)->getLocEnd());
  115. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  116. << 0 /*function call*/ << desiredArgCount << argCount
  117. << call->getArg(1)->getSourceRange();
  118. }
  119. /// Check that the first argument to __builtin_annotation is an integer
  120. /// and the second argument is a non-wide string literal.
  121. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  122. if (checkArgCount(S, TheCall, 2))
  123. return true;
  124. // First argument should be an integer.
  125. Expr *ValArg = TheCall->getArg(0);
  126. QualType Ty = ValArg->getType();
  127. if (!Ty->isIntegerType()) {
  128. S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
  129. << ValArg->getSourceRange();
  130. return true;
  131. }
  132. // Second argument should be a constant string.
  133. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  134. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  135. if (!Literal || !Literal->isAscii()) {
  136. S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
  137. << StrArg->getSourceRange();
  138. return true;
  139. }
  140. TheCall->setType(Ty);
  141. return false;
  142. }
  143. static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
  144. // We need at least one argument.
  145. if (TheCall->getNumArgs() < 1) {
  146. S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  147. << 0 << 1 << TheCall->getNumArgs()
  148. << TheCall->getCallee()->getSourceRange();
  149. return true;
  150. }
  151. // All arguments should be wide string literals.
  152. for (Expr *Arg : TheCall->arguments()) {
  153. auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  154. if (!Literal || !Literal->isWide()) {
  155. S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
  156. << Arg->getSourceRange();
  157. return true;
  158. }
  159. }
  160. return false;
  161. }
  162. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  163. /// result type to the corresponding pointer type.
  164. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  165. if (checkArgCount(S, TheCall, 1))
  166. return true;
  167. ExprResult Arg(TheCall->getArg(0));
  168. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
  169. if (ResultType.isNull())
  170. return true;
  171. TheCall->setArg(0, Arg.get());
  172. TheCall->setType(ResultType);
  173. return false;
  174. }
  175. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
  176. if (checkArgCount(S, TheCall, 3))
  177. return true;
  178. // First two arguments should be integers.
  179. for (unsigned I = 0; I < 2; ++I) {
  180. Expr *Arg = TheCall->getArg(I);
  181. QualType Ty = Arg->getType();
  182. if (!Ty->isIntegerType()) {
  183. S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
  184. << Ty << Arg->getSourceRange();
  185. return true;
  186. }
  187. }
  188. // Third argument should be a pointer to a non-const integer.
  189. // IRGen correctly handles volatile, restrict, and address spaces, and
  190. // the other qualifiers aren't possible.
  191. {
  192. Expr *Arg = TheCall->getArg(2);
  193. QualType Ty = Arg->getType();
  194. const auto *PtrTy = Ty->getAs<PointerType>();
  195. if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
  196. !PtrTy->getPointeeType().isConstQualified())) {
  197. S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
  198. << Ty << Arg->getSourceRange();
  199. return true;
  200. }
  201. }
  202. return false;
  203. }
  204. static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
  205. CallExpr *TheCall, unsigned SizeIdx,
  206. unsigned DstSizeIdx) {
  207. if (TheCall->getNumArgs() <= SizeIdx ||
  208. TheCall->getNumArgs() <= DstSizeIdx)
  209. return;
  210. const Expr *SizeArg = TheCall->getArg(SizeIdx);
  211. const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
  212. llvm::APSInt Size, DstSize;
  213. // find out if both sizes are known at compile time
  214. if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
  215. !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
  216. return;
  217. if (Size.ule(DstSize))
  218. return;
  219. // confirmed overflow so generate the diagnostic.
  220. IdentifierInfo *FnName = FDecl->getIdentifier();
  221. SourceLocation SL = TheCall->getLocStart();
  222. SourceRange SR = TheCall->getSourceRange();
  223. S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
  224. }
  225. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  226. if (checkArgCount(S, BuiltinCall, 2))
  227. return true;
  228. SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
  229. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  230. Expr *Call = BuiltinCall->getArg(0);
  231. Expr *Chain = BuiltinCall->getArg(1);
  232. if (Call->getStmtClass() != Stmt::CallExprClass) {
  233. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  234. << Call->getSourceRange();
  235. return true;
  236. }
  237. auto CE = cast<CallExpr>(Call);
  238. if (CE->getCallee()->getType()->isBlockPointerType()) {
  239. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  240. << Call->getSourceRange();
  241. return true;
  242. }
  243. const Decl *TargetDecl = CE->getCalleeDecl();
  244. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  245. if (FD->getBuiltinID()) {
  246. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  247. << Call->getSourceRange();
  248. return true;
  249. }
  250. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  251. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  252. << Call->getSourceRange();
  253. return true;
  254. }
  255. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  256. if (ChainResult.isInvalid())
  257. return true;
  258. if (!ChainResult.get()->getType()->isPointerType()) {
  259. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  260. << Chain->getSourceRange();
  261. return true;
  262. }
  263. QualType ReturnTy = CE->getCallReturnType(S.Context);
  264. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  265. QualType BuiltinTy = S.Context.getFunctionType(
  266. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  267. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  268. Builtin =
  269. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  270. BuiltinCall->setType(CE->getType());
  271. BuiltinCall->setValueKind(CE->getValueKind());
  272. BuiltinCall->setObjectKind(CE->getObjectKind());
  273. BuiltinCall->setCallee(Builtin);
  274. BuiltinCall->setArg(1, ChainResult.get());
  275. return false;
  276. }
  277. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  278. Scope::ScopeFlags NeededScopeFlags,
  279. unsigned DiagID) {
  280. // Scopes aren't available during instantiation. Fortunately, builtin
  281. // functions cannot be template args so they cannot be formed through template
  282. // instantiation. Therefore checking once during the parse is sufficient.
  283. if (SemaRef.inTemplateInstantiation())
  284. return false;
  285. Scope *S = SemaRef.getCurScope();
  286. while (S && !S->isSEHExceptScope())
  287. S = S->getParent();
  288. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  289. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  290. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  291. << DRE->getDecl()->getIdentifier();
  292. return true;
  293. }
  294. return false;
  295. }
  296. static inline bool isBlockPointer(Expr *Arg) {
  297. return Arg->getType()->isBlockPointerType();
  298. }
  299. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  300. /// void*, which is a requirement of device side enqueue.
  301. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  302. const BlockPointerType *BPT =
  303. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  304. ArrayRef<QualType> Params =
  305. BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
  306. unsigned ArgCounter = 0;
  307. bool IllegalParams = false;
  308. // Iterate through the block parameters until either one is found that is not
  309. // a local void*, or the block is valid.
  310. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  311. I != E; ++I, ++ArgCounter) {
  312. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  313. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  314. LangAS::opencl_local) {
  315. // Get the location of the error. If a block literal has been passed
  316. // (BlockExpr) then we can point straight to the offending argument,
  317. // else we just point to the variable reference.
  318. SourceLocation ErrorLoc;
  319. if (isa<BlockExpr>(BlockArg)) {
  320. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  321. ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
  322. } else if (isa<DeclRefExpr>(BlockArg)) {
  323. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
  324. }
  325. S.Diag(ErrorLoc,
  326. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  327. IllegalParams = true;
  328. }
  329. }
  330. return IllegalParams;
  331. }
  332. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  333. if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
  334. S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
  335. << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
  336. return true;
  337. }
  338. return false;
  339. }
  340. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  341. if (checkArgCount(S, TheCall, 2))
  342. return true;
  343. if (checkOpenCLSubgroupExt(S, TheCall))
  344. return true;
  345. // First argument is an ndrange_t type.
  346. Expr *NDRangeArg = TheCall->getArg(0);
  347. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  348. S.Diag(NDRangeArg->getLocStart(),
  349. diag::err_opencl_builtin_expected_type)
  350. << TheCall->getDirectCallee() << "'ndrange_t'";
  351. return true;
  352. }
  353. Expr *BlockArg = TheCall->getArg(1);
  354. if (!isBlockPointer(BlockArg)) {
  355. S.Diag(BlockArg->getLocStart(),
  356. diag::err_opencl_builtin_expected_type)
  357. << TheCall->getDirectCallee() << "block";
  358. return true;
  359. }
  360. return checkOpenCLBlockArgs(S, BlockArg);
  361. }
  362. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  363. /// get_kernel_work_group_size
  364. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  365. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  366. if (checkArgCount(S, TheCall, 1))
  367. return true;
  368. Expr *BlockArg = TheCall->getArg(0);
  369. if (!isBlockPointer(BlockArg)) {
  370. S.Diag(BlockArg->getLocStart(),
  371. diag::err_opencl_builtin_expected_type)
  372. << TheCall->getDirectCallee() << "block";
  373. return true;
  374. }
  375. return checkOpenCLBlockArgs(S, BlockArg);
  376. }
  377. /// Diagnose integer type and any valid implicit conversion to it.
  378. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  379. const QualType &IntType);
  380. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  381. unsigned Start, unsigned End) {
  382. bool IllegalParams = false;
  383. for (unsigned I = Start; I <= End; ++I)
  384. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  385. S.Context.getSizeType());
  386. return IllegalParams;
  387. }
  388. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  389. /// 'local void*' parameter of passed block.
  390. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  391. Expr *BlockArg,
  392. unsigned NumNonVarArgs) {
  393. const BlockPointerType *BPT =
  394. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  395. unsigned NumBlockParams =
  396. BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
  397. unsigned TotalNumArgs = TheCall->getNumArgs();
  398. // For each argument passed to the block, a corresponding uint needs to
  399. // be passed to describe the size of the local memory.
  400. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  401. S.Diag(TheCall->getLocStart(),
  402. diag::err_opencl_enqueue_kernel_local_size_args);
  403. return true;
  404. }
  405. // Check that the sizes of the local memory are specified by integers.
  406. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  407. TotalNumArgs - 1);
  408. }
  409. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  410. /// overload formats specified in Table 6.13.17.1.
  411. /// int enqueue_kernel(queue_t queue,
  412. /// kernel_enqueue_flags_t flags,
  413. /// const ndrange_t ndrange,
  414. /// void (^block)(void))
  415. /// int enqueue_kernel(queue_t queue,
  416. /// kernel_enqueue_flags_t flags,
  417. /// const ndrange_t ndrange,
  418. /// uint num_events_in_wait_list,
  419. /// clk_event_t *event_wait_list,
  420. /// clk_event_t *event_ret,
  421. /// void (^block)(void))
  422. /// int enqueue_kernel(queue_t queue,
  423. /// kernel_enqueue_flags_t flags,
  424. /// const ndrange_t ndrange,
  425. /// void (^block)(local void*, ...),
  426. /// uint size0, ...)
  427. /// int enqueue_kernel(queue_t queue,
  428. /// kernel_enqueue_flags_t flags,
  429. /// const ndrange_t ndrange,
  430. /// uint num_events_in_wait_list,
  431. /// clk_event_t *event_wait_list,
  432. /// clk_event_t *event_ret,
  433. /// void (^block)(local void*, ...),
  434. /// uint size0, ...)
  435. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  436. unsigned NumArgs = TheCall->getNumArgs();
  437. if (NumArgs < 4) {
  438. S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
  439. return true;
  440. }
  441. Expr *Arg0 = TheCall->getArg(0);
  442. Expr *Arg1 = TheCall->getArg(1);
  443. Expr *Arg2 = TheCall->getArg(2);
  444. Expr *Arg3 = TheCall->getArg(3);
  445. // First argument always needs to be a queue_t type.
  446. if (!Arg0->getType()->isQueueT()) {
  447. S.Diag(TheCall->getArg(0)->getLocStart(),
  448. diag::err_opencl_builtin_expected_type)
  449. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  450. return true;
  451. }
  452. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  453. if (!Arg1->getType()->isIntegerType()) {
  454. S.Diag(TheCall->getArg(1)->getLocStart(),
  455. diag::err_opencl_builtin_expected_type)
  456. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  457. return true;
  458. }
  459. // Third argument is always an ndrange_t type.
  460. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  461. S.Diag(TheCall->getArg(2)->getLocStart(),
  462. diag::err_opencl_builtin_expected_type)
  463. << TheCall->getDirectCallee() << "'ndrange_t'";
  464. return true;
  465. }
  466. // With four arguments, there is only one form that the function could be
  467. // called in: no events and no variable arguments.
  468. if (NumArgs == 4) {
  469. // check that the last argument is the right block type.
  470. if (!isBlockPointer(Arg3)) {
  471. S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
  472. << TheCall->getDirectCallee() << "block";
  473. return true;
  474. }
  475. // we have a block type, check the prototype
  476. const BlockPointerType *BPT =
  477. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  478. if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
  479. S.Diag(Arg3->getLocStart(),
  480. diag::err_opencl_enqueue_kernel_blocks_no_args);
  481. return true;
  482. }
  483. return false;
  484. }
  485. // we can have block + varargs.
  486. if (isBlockPointer(Arg3))
  487. return (checkOpenCLBlockArgs(S, Arg3) ||
  488. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  489. // last two cases with either exactly 7 args or 7 args and varargs.
  490. if (NumArgs >= 7) {
  491. // check common block argument.
  492. Expr *Arg6 = TheCall->getArg(6);
  493. if (!isBlockPointer(Arg6)) {
  494. S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
  495. << TheCall->getDirectCallee() << "block";
  496. return true;
  497. }
  498. if (checkOpenCLBlockArgs(S, Arg6))
  499. return true;
  500. // Forth argument has to be any integer type.
  501. if (!Arg3->getType()->isIntegerType()) {
  502. S.Diag(TheCall->getArg(3)->getLocStart(),
  503. diag::err_opencl_builtin_expected_type)
  504. << TheCall->getDirectCallee() << "integer";
  505. return true;
  506. }
  507. // check remaining common arguments.
  508. Expr *Arg4 = TheCall->getArg(4);
  509. Expr *Arg5 = TheCall->getArg(5);
  510. // Fifth argument is always passed as a pointer to clk_event_t.
  511. if (!Arg4->isNullPointerConstant(S.Context,
  512. Expr::NPC_ValueDependentIsNotNull) &&
  513. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  514. S.Diag(TheCall->getArg(4)->getLocStart(),
  515. diag::err_opencl_builtin_expected_type)
  516. << TheCall->getDirectCallee()
  517. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  518. return true;
  519. }
  520. // Sixth argument is always passed as a pointer to clk_event_t.
  521. if (!Arg5->isNullPointerConstant(S.Context,
  522. Expr::NPC_ValueDependentIsNotNull) &&
  523. !(Arg5->getType()->isPointerType() &&
  524. Arg5->getType()->getPointeeType()->isClkEventT())) {
  525. S.Diag(TheCall->getArg(5)->getLocStart(),
  526. diag::err_opencl_builtin_expected_type)
  527. << TheCall->getDirectCallee()
  528. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  529. return true;
  530. }
  531. if (NumArgs == 7)
  532. return false;
  533. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  534. }
  535. // None of the specific case has been detected, give generic error
  536. S.Diag(TheCall->getLocStart(),
  537. diag::err_opencl_enqueue_kernel_incorrect_args);
  538. return true;
  539. }
  540. /// Returns OpenCL access qual.
  541. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  542. return D->getAttr<OpenCLAccessAttr>();
  543. }
  544. /// Returns true if pipe element type is different from the pointer.
  545. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  546. const Expr *Arg0 = Call->getArg(0);
  547. // First argument type should always be pipe.
  548. if (!Arg0->getType()->isPipeType()) {
  549. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
  550. << Call->getDirectCallee() << Arg0->getSourceRange();
  551. return true;
  552. }
  553. OpenCLAccessAttr *AccessQual =
  554. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  555. // Validates the access qualifier is compatible with the call.
  556. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  557. // read_only and write_only, and assumed to be read_only if no qualifier is
  558. // specified.
  559. switch (Call->getDirectCallee()->getBuiltinID()) {
  560. case Builtin::BIread_pipe:
  561. case Builtin::BIreserve_read_pipe:
  562. case Builtin::BIcommit_read_pipe:
  563. case Builtin::BIwork_group_reserve_read_pipe:
  564. case Builtin::BIsub_group_reserve_read_pipe:
  565. case Builtin::BIwork_group_commit_read_pipe:
  566. case Builtin::BIsub_group_commit_read_pipe:
  567. if (!(!AccessQual || AccessQual->isReadOnly())) {
  568. S.Diag(Arg0->getLocStart(),
  569. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  570. << "read_only" << Arg0->getSourceRange();
  571. return true;
  572. }
  573. break;
  574. case Builtin::BIwrite_pipe:
  575. case Builtin::BIreserve_write_pipe:
  576. case Builtin::BIcommit_write_pipe:
  577. case Builtin::BIwork_group_reserve_write_pipe:
  578. case Builtin::BIsub_group_reserve_write_pipe:
  579. case Builtin::BIwork_group_commit_write_pipe:
  580. case Builtin::BIsub_group_commit_write_pipe:
  581. if (!(AccessQual && AccessQual->isWriteOnly())) {
  582. S.Diag(Arg0->getLocStart(),
  583. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  584. << "write_only" << Arg0->getSourceRange();
  585. return true;
  586. }
  587. break;
  588. default:
  589. break;
  590. }
  591. return false;
  592. }
  593. /// Returns true if pipe element type is different from the pointer.
  594. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  595. const Expr *Arg0 = Call->getArg(0);
  596. const Expr *ArgIdx = Call->getArg(Idx);
  597. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  598. const QualType EltTy = PipeTy->getElementType();
  599. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  600. // The Idx argument should be a pointer and the type of the pointer and
  601. // the type of pipe element should also be the same.
  602. if (!ArgTy ||
  603. !S.Context.hasSameType(
  604. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  605. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  606. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  607. << ArgIdx->getType() << ArgIdx->getSourceRange();
  608. return true;
  609. }
  610. return false;
  611. }
  612. // \brief Performs semantic analysis for the read/write_pipe call.
  613. // \param S Reference to the semantic analyzer.
  614. // \param Call A pointer to the builtin call.
  615. // \return True if a semantic error has been found, false otherwise.
  616. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  617. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  618. // functions have two forms.
  619. switch (Call->getNumArgs()) {
  620. case 2:
  621. if (checkOpenCLPipeArg(S, Call))
  622. return true;
  623. // The call with 2 arguments should be
  624. // read/write_pipe(pipe T, T*).
  625. // Check packet type T.
  626. if (checkOpenCLPipePacketType(S, Call, 1))
  627. return true;
  628. break;
  629. case 4: {
  630. if (checkOpenCLPipeArg(S, Call))
  631. return true;
  632. // The call with 4 arguments should be
  633. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  634. // Check reserve_id_t.
  635. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  636. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  637. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  638. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  639. return true;
  640. }
  641. // Check the index.
  642. const Expr *Arg2 = Call->getArg(2);
  643. if (!Arg2->getType()->isIntegerType() &&
  644. !Arg2->getType()->isUnsignedIntegerType()) {
  645. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  646. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  647. << Arg2->getType() << Arg2->getSourceRange();
  648. return true;
  649. }
  650. // Check packet type T.
  651. if (checkOpenCLPipePacketType(S, Call, 3))
  652. return true;
  653. } break;
  654. default:
  655. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
  656. << Call->getDirectCallee() << Call->getSourceRange();
  657. return true;
  658. }
  659. return false;
  660. }
  661. // \brief Performs a semantic analysis on the {work_group_/sub_group_
  662. // /_}reserve_{read/write}_pipe
  663. // \param S Reference to the semantic analyzer.
  664. // \param Call The call to the builtin function to be analyzed.
  665. // \return True if a semantic error was found, false otherwise.
  666. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  667. if (checkArgCount(S, Call, 2))
  668. return true;
  669. if (checkOpenCLPipeArg(S, Call))
  670. return true;
  671. // Check the reserve size.
  672. if (!Call->getArg(1)->getType()->isIntegerType() &&
  673. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  674. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  675. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  676. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  677. return true;
  678. }
  679. // Since return type of reserve_read/write_pipe built-in function is
  680. // reserve_id_t, which is not defined in the builtin def file , we used int
  681. // as return type and need to override the return type of these functions.
  682. Call->setType(S.Context.OCLReserveIDTy);
  683. return false;
  684. }
  685. // \brief Performs a semantic analysis on {work_group_/sub_group_
  686. // /_}commit_{read/write}_pipe
  687. // \param S Reference to the semantic analyzer.
  688. // \param Call The call to the builtin function to be analyzed.
  689. // \return True if a semantic error was found, false otherwise.
  690. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  691. if (checkArgCount(S, Call, 2))
  692. return true;
  693. if (checkOpenCLPipeArg(S, Call))
  694. return true;
  695. // Check reserve_id_t.
  696. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  697. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  698. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  699. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  700. return true;
  701. }
  702. return false;
  703. }
  704. // \brief Performs a semantic analysis on the call to built-in Pipe
  705. // Query Functions.
  706. // \param S Reference to the semantic analyzer.
  707. // \param Call The call to the builtin function to be analyzed.
  708. // \return True if a semantic error was found, false otherwise.
  709. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  710. if (checkArgCount(S, Call, 1))
  711. return true;
  712. if (!Call->getArg(0)->getType()->isPipeType()) {
  713. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
  714. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  715. return true;
  716. }
  717. return false;
  718. }
  719. // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  720. // \brief Performs semantic analysis for the to_global/local/private call.
  721. // \param S Reference to the semantic analyzer.
  722. // \param BuiltinID ID of the builtin function.
  723. // \param Call A pointer to the builtin call.
  724. // \return True if a semantic error has been found, false otherwise.
  725. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  726. CallExpr *Call) {
  727. if (Call->getNumArgs() != 1) {
  728. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
  729. << Call->getDirectCallee() << Call->getSourceRange();
  730. return true;
  731. }
  732. auto RT = Call->getArg(0)->getType();
  733. if (!RT->isPointerType() || RT->getPointeeType()
  734. .getAddressSpace() == LangAS::opencl_constant) {
  735. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
  736. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  737. return true;
  738. }
  739. RT = RT->getPointeeType();
  740. auto Qual = RT.getQualifiers();
  741. switch (BuiltinID) {
  742. case Builtin::BIto_global:
  743. Qual.setAddressSpace(LangAS::opencl_global);
  744. break;
  745. case Builtin::BIto_local:
  746. Qual.setAddressSpace(LangAS::opencl_local);
  747. break;
  748. case Builtin::BIto_private:
  749. Qual.setAddressSpace(LangAS::opencl_private);
  750. break;
  751. default:
  752. llvm_unreachable("Invalid builtin function");
  753. }
  754. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  755. RT.getUnqualifiedType(), Qual)));
  756. return false;
  757. }
  758. ExprResult
  759. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  760. CallExpr *TheCall) {
  761. ExprResult TheCallResult(TheCall);
  762. // Find out if any arguments are required to be integer constant expressions.
  763. unsigned ICEArguments = 0;
  764. ASTContext::GetBuiltinTypeError Error;
  765. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  766. if (Error != ASTContext::GE_None)
  767. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  768. // If any arguments are required to be ICE's, check and diagnose.
  769. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  770. // Skip arguments not required to be ICE's.
  771. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  772. llvm::APSInt Result;
  773. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  774. return true;
  775. ICEArguments &= ~(1 << ArgNo);
  776. }
  777. switch (BuiltinID) {
  778. case Builtin::BI__builtin___CFStringMakeConstantString:
  779. assert(TheCall->getNumArgs() == 1 &&
  780. "Wrong # arguments to builtin CFStringMakeConstantString");
  781. if (CheckObjCString(TheCall->getArg(0)))
  782. return ExprError();
  783. break;
  784. case Builtin::BI__builtin_ms_va_start:
  785. case Builtin::BI__builtin_stdarg_start:
  786. case Builtin::BI__builtin_va_start:
  787. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  788. return ExprError();
  789. break;
  790. case Builtin::BI__va_start: {
  791. switch (Context.getTargetInfo().getTriple().getArch()) {
  792. case llvm::Triple::arm:
  793. case llvm::Triple::thumb:
  794. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  795. return ExprError();
  796. break;
  797. default:
  798. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  799. return ExprError();
  800. break;
  801. }
  802. break;
  803. }
  804. case Builtin::BI__builtin_isgreater:
  805. case Builtin::BI__builtin_isgreaterequal:
  806. case Builtin::BI__builtin_isless:
  807. case Builtin::BI__builtin_islessequal:
  808. case Builtin::BI__builtin_islessgreater:
  809. case Builtin::BI__builtin_isunordered:
  810. if (SemaBuiltinUnorderedCompare(TheCall))
  811. return ExprError();
  812. break;
  813. case Builtin::BI__builtin_fpclassify:
  814. if (SemaBuiltinFPClassification(TheCall, 6))
  815. return ExprError();
  816. break;
  817. case Builtin::BI__builtin_isfinite:
  818. case Builtin::BI__builtin_isinf:
  819. case Builtin::BI__builtin_isinf_sign:
  820. case Builtin::BI__builtin_isnan:
  821. case Builtin::BI__builtin_isnormal:
  822. if (SemaBuiltinFPClassification(TheCall, 1))
  823. return ExprError();
  824. break;
  825. case Builtin::BI__builtin_shufflevector:
  826. return SemaBuiltinShuffleVector(TheCall);
  827. // TheCall will be freed by the smart pointer here, but that's fine, since
  828. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  829. case Builtin::BI__builtin_prefetch:
  830. if (SemaBuiltinPrefetch(TheCall))
  831. return ExprError();
  832. break;
  833. case Builtin::BI__builtin_alloca_with_align:
  834. if (SemaBuiltinAllocaWithAlign(TheCall))
  835. return ExprError();
  836. break;
  837. case Builtin::BI__assume:
  838. case Builtin::BI__builtin_assume:
  839. if (SemaBuiltinAssume(TheCall))
  840. return ExprError();
  841. break;
  842. case Builtin::BI__builtin_assume_aligned:
  843. if (SemaBuiltinAssumeAligned(TheCall))
  844. return ExprError();
  845. break;
  846. case Builtin::BI__builtin_object_size:
  847. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  848. return ExprError();
  849. break;
  850. case Builtin::BI__builtin_longjmp:
  851. if (SemaBuiltinLongjmp(TheCall))
  852. return ExprError();
  853. break;
  854. case Builtin::BI__builtin_setjmp:
  855. if (SemaBuiltinSetjmp(TheCall))
  856. return ExprError();
  857. break;
  858. case Builtin::BI_setjmp:
  859. case Builtin::BI_setjmpex:
  860. if (checkArgCount(*this, TheCall, 1))
  861. return true;
  862. break;
  863. case Builtin::BI__builtin_classify_type:
  864. if (checkArgCount(*this, TheCall, 1)) return true;
  865. TheCall->setType(Context.IntTy);
  866. break;
  867. case Builtin::BI__builtin_constant_p:
  868. if (checkArgCount(*this, TheCall, 1)) return true;
  869. TheCall->setType(Context.IntTy);
  870. break;
  871. case Builtin::BI__sync_fetch_and_add:
  872. case Builtin::BI__sync_fetch_and_add_1:
  873. case Builtin::BI__sync_fetch_and_add_2:
  874. case Builtin::BI__sync_fetch_and_add_4:
  875. case Builtin::BI__sync_fetch_and_add_8:
  876. case Builtin::BI__sync_fetch_and_add_16:
  877. case Builtin::BI__sync_fetch_and_sub:
  878. case Builtin::BI__sync_fetch_and_sub_1:
  879. case Builtin::BI__sync_fetch_and_sub_2:
  880. case Builtin::BI__sync_fetch_and_sub_4:
  881. case Builtin::BI__sync_fetch_and_sub_8:
  882. case Builtin::BI__sync_fetch_and_sub_16:
  883. case Builtin::BI__sync_fetch_and_or:
  884. case Builtin::BI__sync_fetch_and_or_1:
  885. case Builtin::BI__sync_fetch_and_or_2:
  886. case Builtin::BI__sync_fetch_and_or_4:
  887. case Builtin::BI__sync_fetch_and_or_8:
  888. case Builtin::BI__sync_fetch_and_or_16:
  889. case Builtin::BI__sync_fetch_and_and:
  890. case Builtin::BI__sync_fetch_and_and_1:
  891. case Builtin::BI__sync_fetch_and_and_2:
  892. case Builtin::BI__sync_fetch_and_and_4:
  893. case Builtin::BI__sync_fetch_and_and_8:
  894. case Builtin::BI__sync_fetch_and_and_16:
  895. case Builtin::BI__sync_fetch_and_xor:
  896. case Builtin::BI__sync_fetch_and_xor_1:
  897. case Builtin::BI__sync_fetch_and_xor_2:
  898. case Builtin::BI__sync_fetch_and_xor_4:
  899. case Builtin::BI__sync_fetch_and_xor_8:
  900. case Builtin::BI__sync_fetch_and_xor_16:
  901. case Builtin::BI__sync_fetch_and_nand:
  902. case Builtin::BI__sync_fetch_and_nand_1:
  903. case Builtin::BI__sync_fetch_and_nand_2:
  904. case Builtin::BI__sync_fetch_and_nand_4:
  905. case Builtin::BI__sync_fetch_and_nand_8:
  906. case Builtin::BI__sync_fetch_and_nand_16:
  907. case Builtin::BI__sync_add_and_fetch:
  908. case Builtin::BI__sync_add_and_fetch_1:
  909. case Builtin::BI__sync_add_and_fetch_2:
  910. case Builtin::BI__sync_add_and_fetch_4:
  911. case Builtin::BI__sync_add_and_fetch_8:
  912. case Builtin::BI__sync_add_and_fetch_16:
  913. case Builtin::BI__sync_sub_and_fetch:
  914. case Builtin::BI__sync_sub_and_fetch_1:
  915. case Builtin::BI__sync_sub_and_fetch_2:
  916. case Builtin::BI__sync_sub_and_fetch_4:
  917. case Builtin::BI__sync_sub_and_fetch_8:
  918. case Builtin::BI__sync_sub_and_fetch_16:
  919. case Builtin::BI__sync_and_and_fetch:
  920. case Builtin::BI__sync_and_and_fetch_1:
  921. case Builtin::BI__sync_and_and_fetch_2:
  922. case Builtin::BI__sync_and_and_fetch_4:
  923. case Builtin::BI__sync_and_and_fetch_8:
  924. case Builtin::BI__sync_and_and_fetch_16:
  925. case Builtin::BI__sync_or_and_fetch:
  926. case Builtin::BI__sync_or_and_fetch_1:
  927. case Builtin::BI__sync_or_and_fetch_2:
  928. case Builtin::BI__sync_or_and_fetch_4:
  929. case Builtin::BI__sync_or_and_fetch_8:
  930. case Builtin::BI__sync_or_and_fetch_16:
  931. case Builtin::BI__sync_xor_and_fetch:
  932. case Builtin::BI__sync_xor_and_fetch_1:
  933. case Builtin::BI__sync_xor_and_fetch_2:
  934. case Builtin::BI__sync_xor_and_fetch_4:
  935. case Builtin::BI__sync_xor_and_fetch_8:
  936. case Builtin::BI__sync_xor_and_fetch_16:
  937. case Builtin::BI__sync_nand_and_fetch:
  938. case Builtin::BI__sync_nand_and_fetch_1:
  939. case Builtin::BI__sync_nand_and_fetch_2:
  940. case Builtin::BI__sync_nand_and_fetch_4:
  941. case Builtin::BI__sync_nand_and_fetch_8:
  942. case Builtin::BI__sync_nand_and_fetch_16:
  943. case Builtin::BI__sync_val_compare_and_swap:
  944. case Builtin::BI__sync_val_compare_and_swap_1:
  945. case Builtin::BI__sync_val_compare_and_swap_2:
  946. case Builtin::BI__sync_val_compare_and_swap_4:
  947. case Builtin::BI__sync_val_compare_and_swap_8:
  948. case Builtin::BI__sync_val_compare_and_swap_16:
  949. case Builtin::BI__sync_bool_compare_and_swap:
  950. case Builtin::BI__sync_bool_compare_and_swap_1:
  951. case Builtin::BI__sync_bool_compare_and_swap_2:
  952. case Builtin::BI__sync_bool_compare_and_swap_4:
  953. case Builtin::BI__sync_bool_compare_and_swap_8:
  954. case Builtin::BI__sync_bool_compare_and_swap_16:
  955. case Builtin::BI__sync_lock_test_and_set:
  956. case Builtin::BI__sync_lock_test_and_set_1:
  957. case Builtin::BI__sync_lock_test_and_set_2:
  958. case Builtin::BI__sync_lock_test_and_set_4:
  959. case Builtin::BI__sync_lock_test_and_set_8:
  960. case Builtin::BI__sync_lock_test_and_set_16:
  961. case Builtin::BI__sync_lock_release:
  962. case Builtin::BI__sync_lock_release_1:
  963. case Builtin::BI__sync_lock_release_2:
  964. case Builtin::BI__sync_lock_release_4:
  965. case Builtin::BI__sync_lock_release_8:
  966. case Builtin::BI__sync_lock_release_16:
  967. case Builtin::BI__sync_swap:
  968. case Builtin::BI__sync_swap_1:
  969. case Builtin::BI__sync_swap_2:
  970. case Builtin::BI__sync_swap_4:
  971. case Builtin::BI__sync_swap_8:
  972. case Builtin::BI__sync_swap_16:
  973. return SemaBuiltinAtomicOverloaded(TheCallResult);
  974. case Builtin::BI__builtin_nontemporal_load:
  975. case Builtin::BI__builtin_nontemporal_store:
  976. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  977. #define BUILTIN(ID, TYPE, ATTRS)
  978. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  979. case Builtin::BI##ID: \
  980. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  981. #include "clang/Basic/Builtins.def"
  982. case Builtin::BI__annotation:
  983. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  984. return ExprError();
  985. break;
  986. case Builtin::BI__builtin_annotation:
  987. if (SemaBuiltinAnnotation(*this, TheCall))
  988. return ExprError();
  989. break;
  990. case Builtin::BI__builtin_addressof:
  991. if (SemaBuiltinAddressof(*this, TheCall))
  992. return ExprError();
  993. break;
  994. case Builtin::BI__builtin_add_overflow:
  995. case Builtin::BI__builtin_sub_overflow:
  996. case Builtin::BI__builtin_mul_overflow:
  997. if (SemaBuiltinOverflow(*this, TheCall))
  998. return ExprError();
  999. break;
  1000. case Builtin::BI__builtin_operator_new:
  1001. case Builtin::BI__builtin_operator_delete:
  1002. if (!getLangOpts().CPlusPlus) {
  1003. Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
  1004. << (BuiltinID == Builtin::BI__builtin_operator_new
  1005. ? "__builtin_operator_new"
  1006. : "__builtin_operator_delete")
  1007. << "C++";
  1008. return ExprError();
  1009. }
  1010. // CodeGen assumes it can find the global new and delete to call,
  1011. // so ensure that they are declared.
  1012. DeclareGlobalNewDelete();
  1013. break;
  1014. // check secure string manipulation functions where overflows
  1015. // are detectable at compile time
  1016. case Builtin::BI__builtin___memcpy_chk:
  1017. case Builtin::BI__builtin___memmove_chk:
  1018. case Builtin::BI__builtin___memset_chk:
  1019. case Builtin::BI__builtin___strlcat_chk:
  1020. case Builtin::BI__builtin___strlcpy_chk:
  1021. case Builtin::BI__builtin___strncat_chk:
  1022. case Builtin::BI__builtin___strncpy_chk:
  1023. case Builtin::BI__builtin___stpncpy_chk:
  1024. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
  1025. break;
  1026. case Builtin::BI__builtin___memccpy_chk:
  1027. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
  1028. break;
  1029. case Builtin::BI__builtin___snprintf_chk:
  1030. case Builtin::BI__builtin___vsnprintf_chk:
  1031. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
  1032. break;
  1033. case Builtin::BI__builtin_call_with_static_chain:
  1034. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  1035. return ExprError();
  1036. break;
  1037. case Builtin::BI__exception_code:
  1038. case Builtin::BI_exception_code:
  1039. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  1040. diag::err_seh___except_block))
  1041. return ExprError();
  1042. break;
  1043. case Builtin::BI__exception_info:
  1044. case Builtin::BI_exception_info:
  1045. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  1046. diag::err_seh___except_filter))
  1047. return ExprError();
  1048. break;
  1049. case Builtin::BI__GetExceptionInfo:
  1050. if (checkArgCount(*this, TheCall, 1))
  1051. return ExprError();
  1052. if (CheckCXXThrowOperand(
  1053. TheCall->getLocStart(),
  1054. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1055. TheCall))
  1056. return ExprError();
  1057. TheCall->setType(Context.VoidPtrTy);
  1058. break;
  1059. // OpenCL v2.0, s6.13.16 - Pipe functions
  1060. case Builtin::BIread_pipe:
  1061. case Builtin::BIwrite_pipe:
  1062. // Since those two functions are declared with var args, we need a semantic
  1063. // check for the argument.
  1064. if (SemaBuiltinRWPipe(*this, TheCall))
  1065. return ExprError();
  1066. TheCall->setType(Context.IntTy);
  1067. break;
  1068. case Builtin::BIreserve_read_pipe:
  1069. case Builtin::BIreserve_write_pipe:
  1070. case Builtin::BIwork_group_reserve_read_pipe:
  1071. case Builtin::BIwork_group_reserve_write_pipe:
  1072. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1073. return ExprError();
  1074. break;
  1075. case Builtin::BIsub_group_reserve_read_pipe:
  1076. case Builtin::BIsub_group_reserve_write_pipe:
  1077. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1078. SemaBuiltinReserveRWPipe(*this, TheCall))
  1079. return ExprError();
  1080. break;
  1081. case Builtin::BIcommit_read_pipe:
  1082. case Builtin::BIcommit_write_pipe:
  1083. case Builtin::BIwork_group_commit_read_pipe:
  1084. case Builtin::BIwork_group_commit_write_pipe:
  1085. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1086. return ExprError();
  1087. break;
  1088. case Builtin::BIsub_group_commit_read_pipe:
  1089. case Builtin::BIsub_group_commit_write_pipe:
  1090. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1091. SemaBuiltinCommitRWPipe(*this, TheCall))
  1092. return ExprError();
  1093. break;
  1094. case Builtin::BIget_pipe_num_packets:
  1095. case Builtin::BIget_pipe_max_packets:
  1096. if (SemaBuiltinPipePackets(*this, TheCall))
  1097. return ExprError();
  1098. TheCall->setType(Context.UnsignedIntTy);
  1099. break;
  1100. case Builtin::BIto_global:
  1101. case Builtin::BIto_local:
  1102. case Builtin::BIto_private:
  1103. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1104. return ExprError();
  1105. break;
  1106. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1107. case Builtin::BIenqueue_kernel:
  1108. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1109. return ExprError();
  1110. break;
  1111. case Builtin::BIget_kernel_work_group_size:
  1112. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1113. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1114. return ExprError();
  1115. break;
  1116. break;
  1117. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1118. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1119. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1120. return ExprError();
  1121. break;
  1122. case Builtin::BI__builtin_os_log_format:
  1123. case Builtin::BI__builtin_os_log_format_buffer_size:
  1124. if (SemaBuiltinOSLogFormat(TheCall))
  1125. return ExprError();
  1126. break;
  1127. }
  1128. // Since the target specific builtins for each arch overlap, only check those
  1129. // of the arch we are compiling for.
  1130. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  1131. switch (Context.getTargetInfo().getTriple().getArch()) {
  1132. case llvm::Triple::arm:
  1133. case llvm::Triple::armeb:
  1134. case llvm::Triple::thumb:
  1135. case llvm::Triple::thumbeb:
  1136. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  1137. return ExprError();
  1138. break;
  1139. case llvm::Triple::aarch64:
  1140. case llvm::Triple::aarch64_be:
  1141. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  1142. return ExprError();
  1143. break;
  1144. case llvm::Triple::mips:
  1145. case llvm::Triple::mipsel:
  1146. case llvm::Triple::mips64:
  1147. case llvm::Triple::mips64el:
  1148. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  1149. return ExprError();
  1150. break;
  1151. case llvm::Triple::systemz:
  1152. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  1153. return ExprError();
  1154. break;
  1155. case llvm::Triple::x86:
  1156. case llvm::Triple::x86_64:
  1157. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  1158. return ExprError();
  1159. break;
  1160. case llvm::Triple::ppc:
  1161. case llvm::Triple::ppc64:
  1162. case llvm::Triple::ppc64le:
  1163. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  1164. return ExprError();
  1165. break;
  1166. default:
  1167. break;
  1168. }
  1169. }
  1170. return TheCallResult;
  1171. }
  1172. // Get the valid immediate range for the specified NEON type code.
  1173. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  1174. NeonTypeFlags Type(t);
  1175. int IsQuad = ForceQuad ? true : Type.isQuad();
  1176. switch (Type.getEltType()) {
  1177. case NeonTypeFlags::Int8:
  1178. case NeonTypeFlags::Poly8:
  1179. return shift ? 7 : (8 << IsQuad) - 1;
  1180. case NeonTypeFlags::Int16:
  1181. case NeonTypeFlags::Poly16:
  1182. return shift ? 15 : (4 << IsQuad) - 1;
  1183. case NeonTypeFlags::Int32:
  1184. return shift ? 31 : (2 << IsQuad) - 1;
  1185. case NeonTypeFlags::Int64:
  1186. case NeonTypeFlags::Poly64:
  1187. return shift ? 63 : (1 << IsQuad) - 1;
  1188. case NeonTypeFlags::Poly128:
  1189. return shift ? 127 : (1 << IsQuad) - 1;
  1190. case NeonTypeFlags::Float16:
  1191. assert(!shift && "cannot shift float types!");
  1192. return (4 << IsQuad) - 1;
  1193. case NeonTypeFlags::Float32:
  1194. assert(!shift && "cannot shift float types!");
  1195. return (2 << IsQuad) - 1;
  1196. case NeonTypeFlags::Float64:
  1197. assert(!shift && "cannot shift float types!");
  1198. return (1 << IsQuad) - 1;
  1199. }
  1200. llvm_unreachable("Invalid NeonTypeFlag!");
  1201. }
  1202. /// getNeonEltType - Return the QualType corresponding to the elements of
  1203. /// the vector type specified by the NeonTypeFlags. This is used to check
  1204. /// the pointer arguments for Neon load/store intrinsics.
  1205. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  1206. bool IsPolyUnsigned, bool IsInt64Long) {
  1207. switch (Flags.getEltType()) {
  1208. case NeonTypeFlags::Int8:
  1209. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  1210. case NeonTypeFlags::Int16:
  1211. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  1212. case NeonTypeFlags::Int32:
  1213. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  1214. case NeonTypeFlags::Int64:
  1215. if (IsInt64Long)
  1216. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  1217. else
  1218. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  1219. : Context.LongLongTy;
  1220. case NeonTypeFlags::Poly8:
  1221. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  1222. case NeonTypeFlags::Poly16:
  1223. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  1224. case NeonTypeFlags::Poly64:
  1225. if (IsInt64Long)
  1226. return Context.UnsignedLongTy;
  1227. else
  1228. return Context.UnsignedLongLongTy;
  1229. case NeonTypeFlags::Poly128:
  1230. break;
  1231. case NeonTypeFlags::Float16:
  1232. return Context.HalfTy;
  1233. case NeonTypeFlags::Float32:
  1234. return Context.FloatTy;
  1235. case NeonTypeFlags::Float64:
  1236. return Context.DoubleTy;
  1237. }
  1238. llvm_unreachable("Invalid NeonTypeFlag!");
  1239. }
  1240. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1241. llvm::APSInt Result;
  1242. uint64_t mask = 0;
  1243. unsigned TV = 0;
  1244. int PtrArgNum = -1;
  1245. bool HasConstPtr = false;
  1246. switch (BuiltinID) {
  1247. #define GET_NEON_OVERLOAD_CHECK
  1248. #include "clang/Basic/arm_neon.inc"
  1249. #undef GET_NEON_OVERLOAD_CHECK
  1250. }
  1251. // For NEON intrinsics which are overloaded on vector element type, validate
  1252. // the immediate which specifies which variant to emit.
  1253. unsigned ImmArg = TheCall->getNumArgs()-1;
  1254. if (mask) {
  1255. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  1256. return true;
  1257. TV = Result.getLimitedValue(64);
  1258. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  1259. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  1260. << TheCall->getArg(ImmArg)->getSourceRange();
  1261. }
  1262. if (PtrArgNum >= 0) {
  1263. // Check that pointer arguments have the specified type.
  1264. Expr *Arg = TheCall->getArg(PtrArgNum);
  1265. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  1266. Arg = ICE->getSubExpr();
  1267. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  1268. QualType RHSTy = RHS.get()->getType();
  1269. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  1270. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  1271. Arch == llvm::Triple::aarch64_be;
  1272. bool IsInt64Long =
  1273. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  1274. QualType EltTy =
  1275. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  1276. if (HasConstPtr)
  1277. EltTy = EltTy.withConst();
  1278. QualType LHSTy = Context.getPointerType(EltTy);
  1279. AssignConvertType ConvTy;
  1280. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  1281. if (RHS.isInvalid())
  1282. return true;
  1283. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  1284. RHS.get(), AA_Assigning))
  1285. return true;
  1286. }
  1287. // For NEON intrinsics which take an immediate value as part of the
  1288. // instruction, range check them here.
  1289. unsigned i = 0, l = 0, u = 0;
  1290. switch (BuiltinID) {
  1291. default:
  1292. return false;
  1293. #define GET_NEON_IMMEDIATE_CHECK
  1294. #include "clang/Basic/arm_neon.inc"
  1295. #undef GET_NEON_IMMEDIATE_CHECK
  1296. }
  1297. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1298. }
  1299. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  1300. unsigned MaxWidth) {
  1301. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1302. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1303. BuiltinID == ARM::BI__builtin_arm_strex ||
  1304. BuiltinID == ARM::BI__builtin_arm_stlex ||
  1305. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1306. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1307. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1308. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  1309. "unexpected ARM builtin");
  1310. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1311. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1312. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1313. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  1314. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1315. // Ensure that we have the proper number of arguments.
  1316. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  1317. return true;
  1318. // Inspect the pointer argument of the atomic builtin. This should always be
  1319. // a pointer type, whose element is an integral scalar or pointer type.
  1320. // Because it is a pointer type, we don't have to worry about any implicit
  1321. // casts here.
  1322. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  1323. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  1324. if (PointerArgRes.isInvalid())
  1325. return true;
  1326. PointerArg = PointerArgRes.get();
  1327. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  1328. if (!pointerType) {
  1329. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  1330. << PointerArg->getType() << PointerArg->getSourceRange();
  1331. return true;
  1332. }
  1333. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  1334. // task is to insert the appropriate casts into the AST. First work out just
  1335. // what the appropriate type is.
  1336. QualType ValType = pointerType->getPointeeType();
  1337. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  1338. if (IsLdrex)
  1339. AddrType.addConst();
  1340. // Issue a warning if the cast is dodgy.
  1341. CastKind CastNeeded = CK_NoOp;
  1342. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  1343. CastNeeded = CK_BitCast;
  1344. Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
  1345. << PointerArg->getType()
  1346. << Context.getPointerType(AddrType)
  1347. << AA_Passing << PointerArg->getSourceRange();
  1348. }
  1349. // Finally, do the cast and replace the argument with the corrected version.
  1350. AddrType = Context.getPointerType(AddrType);
  1351. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  1352. if (PointerArgRes.isInvalid())
  1353. return true;
  1354. PointerArg = PointerArgRes.get();
  1355. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  1356. // In general, we allow ints, floats and pointers to be loaded and stored.
  1357. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1358. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  1359. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  1360. << PointerArg->getType() << PointerArg->getSourceRange();
  1361. return true;
  1362. }
  1363. // But ARM doesn't have instructions to deal with 128-bit versions.
  1364. if (Context.getTypeSize(ValType) > MaxWidth) {
  1365. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  1366. Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
  1367. << PointerArg->getType() << PointerArg->getSourceRange();
  1368. return true;
  1369. }
  1370. switch (ValType.getObjCLifetime()) {
  1371. case Qualifiers::OCL_None:
  1372. case Qualifiers::OCL_ExplicitNone:
  1373. // okay
  1374. break;
  1375. case Qualifiers::OCL_Weak:
  1376. case Qualifiers::OCL_Strong:
  1377. case Qualifiers::OCL_Autoreleasing:
  1378. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  1379. << ValType << PointerArg->getSourceRange();
  1380. return true;
  1381. }
  1382. if (IsLdrex) {
  1383. TheCall->setType(ValType);
  1384. return false;
  1385. }
  1386. // Initialize the argument to be stored.
  1387. ExprResult ValArg = TheCall->getArg(0);
  1388. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  1389. Context, ValType, /*consume*/ false);
  1390. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  1391. if (ValArg.isInvalid())
  1392. return true;
  1393. TheCall->setArg(0, ValArg.get());
  1394. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  1395. // but the custom checker bypasses all default analysis.
  1396. TheCall->setType(Context.IntTy);
  1397. return false;
  1398. }
  1399. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1400. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1401. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1402. BuiltinID == ARM::BI__builtin_arm_strex ||
  1403. BuiltinID == ARM::BI__builtin_arm_stlex) {
  1404. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  1405. }
  1406. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  1407. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1408. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  1409. }
  1410. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  1411. BuiltinID == ARM::BI__builtin_arm_wsr64)
  1412. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  1413. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  1414. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  1415. BuiltinID == ARM::BI__builtin_arm_wsr ||
  1416. BuiltinID == ARM::BI__builtin_arm_wsrp)
  1417. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1418. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1419. return true;
  1420. // For intrinsics which take an immediate value as part of the instruction,
  1421. // range check them here.
  1422. // FIXME: VFP Intrinsics should error if VFP not present.
  1423. switch (BuiltinID) {
  1424. default: return false;
  1425. case ARM::BI__builtin_arm_ssat:
  1426. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  1427. case ARM::BI__builtin_arm_usat:
  1428. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  1429. case ARM::BI__builtin_arm_ssat16:
  1430. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  1431. case ARM::BI__builtin_arm_usat16:
  1432. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  1433. case ARM::BI__builtin_arm_vcvtr_f:
  1434. case ARM::BI__builtin_arm_vcvtr_d:
  1435. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  1436. case ARM::BI__builtin_arm_dmb:
  1437. case ARM::BI__builtin_arm_dsb:
  1438. case ARM::BI__builtin_arm_isb:
  1439. case ARM::BI__builtin_arm_dbg:
  1440. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  1441. }
  1442. }
  1443. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  1444. CallExpr *TheCall) {
  1445. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1446. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1447. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1448. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  1449. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  1450. }
  1451. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  1452. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1453. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  1454. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  1455. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  1456. }
  1457. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  1458. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  1459. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1460. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  1461. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  1462. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  1463. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  1464. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1465. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1466. return true;
  1467. // For intrinsics which take an immediate value as part of the instruction,
  1468. // range check them here.
  1469. unsigned i = 0, l = 0, u = 0;
  1470. switch (BuiltinID) {
  1471. default: return false;
  1472. case AArch64::BI__builtin_arm_dmb:
  1473. case AArch64::BI__builtin_arm_dsb:
  1474. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  1475. }
  1476. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1477. }
  1478. // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
  1479. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  1480. // ordering for DSP is unspecified. MSA is ordered by the data format used
  1481. // by the underlying instruction i.e., df/m, df/n and then by size.
  1482. //
  1483. // FIXME: The size tests here should instead be tablegen'd along with the
  1484. // definitions from include/clang/Basic/BuiltinsMips.def.
  1485. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  1486. // be too.
  1487. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1488. unsigned i = 0, l = 0, u = 0, m = 0;
  1489. switch (BuiltinID) {
  1490. default: return false;
  1491. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  1492. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  1493. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  1494. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  1495. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  1496. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  1497. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  1498. // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
  1499. // df/m field.
  1500. // These intrinsics take an unsigned 3 bit immediate.
  1501. case Mips::BI__builtin_msa_bclri_b:
  1502. case Mips::BI__builtin_msa_bnegi_b:
  1503. case Mips::BI__builtin_msa_bseti_b:
  1504. case Mips::BI__builtin_msa_sat_s_b:
  1505. case Mips::BI__builtin_msa_sat_u_b:
  1506. case Mips::BI__builtin_msa_slli_b:
  1507. case Mips::BI__builtin_msa_srai_b:
  1508. case Mips::BI__builtin_msa_srari_b:
  1509. case Mips::BI__builtin_msa_srli_b:
  1510. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  1511. case Mips::BI__builtin_msa_binsli_b:
  1512. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  1513. // These intrinsics take an unsigned 4 bit immediate.
  1514. case Mips::BI__builtin_msa_bclri_h:
  1515. case Mips::BI__builtin_msa_bnegi_h:
  1516. case Mips::BI__builtin_msa_bseti_h:
  1517. case Mips::BI__builtin_msa_sat_s_h:
  1518. case Mips::BI__builtin_msa_sat_u_h:
  1519. case Mips::BI__builtin_msa_slli_h:
  1520. case Mips::BI__builtin_msa_srai_h:
  1521. case Mips::BI__builtin_msa_srari_h:
  1522. case Mips::BI__builtin_msa_srli_h:
  1523. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  1524. case Mips::BI__builtin_msa_binsli_h:
  1525. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  1526. // These intrinsics take an unsigned 5 bit immedate.
  1527. // The first block of intrinsics actually have an unsigned 5 bit field,
  1528. // not a df/n field.
  1529. case Mips::BI__builtin_msa_clei_u_b:
  1530. case Mips::BI__builtin_msa_clei_u_h:
  1531. case Mips::BI__builtin_msa_clei_u_w:
  1532. case Mips::BI__builtin_msa_clei_u_d:
  1533. case Mips::BI__builtin_msa_clti_u_b:
  1534. case Mips::BI__builtin_msa_clti_u_h:
  1535. case Mips::BI__builtin_msa_clti_u_w:
  1536. case Mips::BI__builtin_msa_clti_u_d:
  1537. case Mips::BI__builtin_msa_maxi_u_b:
  1538. case Mips::BI__builtin_msa_maxi_u_h:
  1539. case Mips::BI__builtin_msa_maxi_u_w:
  1540. case Mips::BI__builtin_msa_maxi_u_d:
  1541. case Mips::BI__builtin_msa_mini_u_b:
  1542. case Mips::BI__builtin_msa_mini_u_h:
  1543. case Mips::BI__builtin_msa_mini_u_w:
  1544. case Mips::BI__builtin_msa_mini_u_d:
  1545. case Mips::BI__builtin_msa_addvi_b:
  1546. case Mips::BI__builtin_msa_addvi_h:
  1547. case Mips::BI__builtin_msa_addvi_w:
  1548. case Mips::BI__builtin_msa_addvi_d:
  1549. case Mips::BI__builtin_msa_bclri_w:
  1550. case Mips::BI__builtin_msa_bnegi_w:
  1551. case Mips::BI__builtin_msa_bseti_w:
  1552. case Mips::BI__builtin_msa_sat_s_w:
  1553. case Mips::BI__builtin_msa_sat_u_w:
  1554. case Mips::BI__builtin_msa_slli_w:
  1555. case Mips::BI__builtin_msa_srai_w:
  1556. case Mips::BI__builtin_msa_srari_w:
  1557. case Mips::BI__builtin_msa_srli_w:
  1558. case Mips::BI__builtin_msa_srlri_w:
  1559. case Mips::BI__builtin_msa_subvi_b:
  1560. case Mips::BI__builtin_msa_subvi_h:
  1561. case Mips::BI__builtin_msa_subvi_w:
  1562. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  1563. case Mips::BI__builtin_msa_binsli_w:
  1564. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  1565. // These intrinsics take an unsigned 6 bit immediate.
  1566. case Mips::BI__builtin_msa_bclri_d:
  1567. case Mips::BI__builtin_msa_bnegi_d:
  1568. case Mips::BI__builtin_msa_bseti_d:
  1569. case Mips::BI__builtin_msa_sat_s_d:
  1570. case Mips::BI__builtin_msa_sat_u_d:
  1571. case Mips::BI__builtin_msa_slli_d:
  1572. case Mips::BI__builtin_msa_srai_d:
  1573. case Mips::BI__builtin_msa_srari_d:
  1574. case Mips::BI__builtin_msa_srli_d:
  1575. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  1576. case Mips::BI__builtin_msa_binsli_d:
  1577. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  1578. // These intrinsics take a signed 5 bit immediate.
  1579. case Mips::BI__builtin_msa_ceqi_b:
  1580. case Mips::BI__builtin_msa_ceqi_h:
  1581. case Mips::BI__builtin_msa_ceqi_w:
  1582. case Mips::BI__builtin_msa_ceqi_d:
  1583. case Mips::BI__builtin_msa_clti_s_b:
  1584. case Mips::BI__builtin_msa_clti_s_h:
  1585. case Mips::BI__builtin_msa_clti_s_w:
  1586. case Mips::BI__builtin_msa_clti_s_d:
  1587. case Mips::BI__builtin_msa_clei_s_b:
  1588. case Mips::BI__builtin_msa_clei_s_h:
  1589. case Mips::BI__builtin_msa_clei_s_w:
  1590. case Mips::BI__builtin_msa_clei_s_d:
  1591. case Mips::BI__builtin_msa_maxi_s_b:
  1592. case Mips::BI__builtin_msa_maxi_s_h:
  1593. case Mips::BI__builtin_msa_maxi_s_w:
  1594. case Mips::BI__builtin_msa_maxi_s_d:
  1595. case Mips::BI__builtin_msa_mini_s_b:
  1596. case Mips::BI__builtin_msa_mini_s_h:
  1597. case Mips::BI__builtin_msa_mini_s_w:
  1598. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  1599. // These intrinsics take an unsigned 8 bit immediate.
  1600. case Mips::BI__builtin_msa_andi_b:
  1601. case Mips::BI__builtin_msa_nori_b:
  1602. case Mips::BI__builtin_msa_ori_b:
  1603. case Mips::BI__builtin_msa_shf_b:
  1604. case Mips::BI__builtin_msa_shf_h:
  1605. case Mips::BI__builtin_msa_shf_w:
  1606. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  1607. case Mips::BI__builtin_msa_bseli_b:
  1608. case Mips::BI__builtin_msa_bmnzi_b:
  1609. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  1610. // df/n format
  1611. // These intrinsics take an unsigned 4 bit immediate.
  1612. case Mips::BI__builtin_msa_copy_s_b:
  1613. case Mips::BI__builtin_msa_copy_u_b:
  1614. case Mips::BI__builtin_msa_insve_b:
  1615. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  1616. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  1617. // These intrinsics take an unsigned 3 bit immediate.
  1618. case Mips::BI__builtin_msa_copy_s_h:
  1619. case Mips::BI__builtin_msa_copy_u_h:
  1620. case Mips::BI__builtin_msa_insve_h:
  1621. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  1622. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  1623. // These intrinsics take an unsigned 2 bit immediate.
  1624. case Mips::BI__builtin_msa_copy_s_w:
  1625. case Mips::BI__builtin_msa_copy_u_w:
  1626. case Mips::BI__builtin_msa_insve_w:
  1627. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  1628. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  1629. // These intrinsics take an unsigned 1 bit immediate.
  1630. case Mips::BI__builtin_msa_copy_s_d:
  1631. case Mips::BI__builtin_msa_copy_u_d:
  1632. case Mips::BI__builtin_msa_insve_d:
  1633. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  1634. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  1635. // Memory offsets and immediate loads.
  1636. // These intrinsics take a signed 10 bit immediate.
  1637. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  1638. case Mips::BI__builtin_msa_ldi_h:
  1639. case Mips::BI__builtin_msa_ldi_w:
  1640. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  1641. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
  1642. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
  1643. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
  1644. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
  1645. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
  1646. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
  1647. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
  1648. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
  1649. }
  1650. if (!m)
  1651. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  1652. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  1653. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  1654. }
  1655. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1656. unsigned i = 0, l = 0, u = 0;
  1657. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  1658. BuiltinID == PPC::BI__builtin_divdeu ||
  1659. BuiltinID == PPC::BI__builtin_bpermd;
  1660. bool IsTarget64Bit = Context.getTargetInfo()
  1661. .getTypeWidth(Context
  1662. .getTargetInfo()
  1663. .getIntPtrType()) == 64;
  1664. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  1665. BuiltinID == PPC::BI__builtin_divweu ||
  1666. BuiltinID == PPC::BI__builtin_divde ||
  1667. BuiltinID == PPC::BI__builtin_divdeu;
  1668. if (Is64BitBltin && !IsTarget64Bit)
  1669. return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
  1670. << TheCall->getSourceRange();
  1671. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  1672. (BuiltinID == PPC::BI__builtin_bpermd &&
  1673. !Context.getTargetInfo().hasFeature("bpermd")))
  1674. return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
  1675. << TheCall->getSourceRange();
  1676. switch (BuiltinID) {
  1677. default: return false;
  1678. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  1679. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  1680. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1681. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  1682. case PPC::BI__builtin_tbegin:
  1683. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  1684. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  1685. case PPC::BI__builtin_tabortwc:
  1686. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  1687. case PPC::BI__builtin_tabortwci:
  1688. case PPC::BI__builtin_tabortdci:
  1689. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  1690. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  1691. case PPC::BI__builtin_vsx_xxpermdi:
  1692. case PPC::BI__builtin_vsx_xxsldwi:
  1693. return SemaBuiltinVSX(TheCall);
  1694. }
  1695. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  1696. }
  1697. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  1698. CallExpr *TheCall) {
  1699. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  1700. Expr *Arg = TheCall->getArg(0);
  1701. llvm::APSInt AbortCode(32);
  1702. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  1703. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  1704. return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
  1705. << Arg->getSourceRange();
  1706. }
  1707. // For intrinsics which take an immediate value as part of the instruction,
  1708. // range check them here.
  1709. unsigned i = 0, l = 0, u = 0;
  1710. switch (BuiltinID) {
  1711. default: return false;
  1712. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  1713. case SystemZ::BI__builtin_s390_verimb:
  1714. case SystemZ::BI__builtin_s390_verimh:
  1715. case SystemZ::BI__builtin_s390_verimf:
  1716. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  1717. case SystemZ::BI__builtin_s390_vfaeb:
  1718. case SystemZ::BI__builtin_s390_vfaeh:
  1719. case SystemZ::BI__builtin_s390_vfaef:
  1720. case SystemZ::BI__builtin_s390_vfaebs:
  1721. case SystemZ::BI__builtin_s390_vfaehs:
  1722. case SystemZ::BI__builtin_s390_vfaefs:
  1723. case SystemZ::BI__builtin_s390_vfaezb:
  1724. case SystemZ::BI__builtin_s390_vfaezh:
  1725. case SystemZ::BI__builtin_s390_vfaezf:
  1726. case SystemZ::BI__builtin_s390_vfaezbs:
  1727. case SystemZ::BI__builtin_s390_vfaezhs:
  1728. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  1729. case SystemZ::BI__builtin_s390_vfisb:
  1730. case SystemZ::BI__builtin_s390_vfidb:
  1731. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  1732. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  1733. case SystemZ::BI__builtin_s390_vftcisb:
  1734. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  1735. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  1736. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  1737. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  1738. case SystemZ::BI__builtin_s390_vstrcb:
  1739. case SystemZ::BI__builtin_s390_vstrch:
  1740. case SystemZ::BI__builtin_s390_vstrcf:
  1741. case SystemZ::BI__builtin_s390_vstrczb:
  1742. case SystemZ::BI__builtin_s390_vstrczh:
  1743. case SystemZ::BI__builtin_s390_vstrczf:
  1744. case SystemZ::BI__builtin_s390_vstrcbs:
  1745. case SystemZ::BI__builtin_s390_vstrchs:
  1746. case SystemZ::BI__builtin_s390_vstrcfs:
  1747. case SystemZ::BI__builtin_s390_vstrczbs:
  1748. case SystemZ::BI__builtin_s390_vstrczhs:
  1749. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  1750. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  1751. case SystemZ::BI__builtin_s390_vfminsb:
  1752. case SystemZ::BI__builtin_s390_vfmaxsb:
  1753. case SystemZ::BI__builtin_s390_vfmindb:
  1754. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  1755. }
  1756. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  1757. }
  1758. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  1759. /// This checks that the target supports __builtin_cpu_supports and
  1760. /// that the string argument is constant and valid.
  1761. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  1762. Expr *Arg = TheCall->getArg(0);
  1763. // Check if the argument is a string literal.
  1764. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  1765. return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  1766. << Arg->getSourceRange();
  1767. // Check the contents of the string.
  1768. StringRef Feature =
  1769. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  1770. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  1771. return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
  1772. << Arg->getSourceRange();
  1773. return false;
  1774. }
  1775. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  1776. /// This checks that the target supports __builtin_cpu_is and
  1777. /// that the string argument is constant and valid.
  1778. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  1779. Expr *Arg = TheCall->getArg(0);
  1780. // Check if the argument is a string literal.
  1781. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  1782. return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  1783. << Arg->getSourceRange();
  1784. // Check the contents of the string.
  1785. StringRef Feature =
  1786. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  1787. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  1788. return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
  1789. << Arg->getSourceRange();
  1790. return false;
  1791. }
  1792. // Check if the rounding mode is legal.
  1793. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  1794. // Indicates if this instruction has rounding control or just SAE.
  1795. bool HasRC = false;
  1796. unsigned ArgNum = 0;
  1797. switch (BuiltinID) {
  1798. default:
  1799. return false;
  1800. case X86::BI__builtin_ia32_vcvttsd2si32:
  1801. case X86::BI__builtin_ia32_vcvttsd2si64:
  1802. case X86::BI__builtin_ia32_vcvttsd2usi32:
  1803. case X86::BI__builtin_ia32_vcvttsd2usi64:
  1804. case X86::BI__builtin_ia32_vcvttss2si32:
  1805. case X86::BI__builtin_ia32_vcvttss2si64:
  1806. case X86::BI__builtin_ia32_vcvttss2usi32:
  1807. case X86::BI__builtin_ia32_vcvttss2usi64:
  1808. ArgNum = 1;
  1809. break;
  1810. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  1811. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  1812. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  1813. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  1814. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  1815. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  1816. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  1817. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  1818. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  1819. case X86::BI__builtin_ia32_exp2pd_mask:
  1820. case X86::BI__builtin_ia32_exp2ps_mask:
  1821. case X86::BI__builtin_ia32_getexppd512_mask:
  1822. case X86::BI__builtin_ia32_getexpps512_mask:
  1823. case X86::BI__builtin_ia32_rcp28pd_mask:
  1824. case X86::BI__builtin_ia32_rcp28ps_mask:
  1825. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  1826. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  1827. case X86::BI__builtin_ia32_vcomisd:
  1828. case X86::BI__builtin_ia32_vcomiss:
  1829. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  1830. ArgNum = 3;
  1831. break;
  1832. case X86::BI__builtin_ia32_cmppd512_mask:
  1833. case X86::BI__builtin_ia32_cmpps512_mask:
  1834. case X86::BI__builtin_ia32_cmpsd_mask:
  1835. case X86::BI__builtin_ia32_cmpss_mask:
  1836. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  1837. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  1838. case X86::BI__builtin_ia32_getexpss128_round_mask:
  1839. case X86::BI__builtin_ia32_maxpd512_mask:
  1840. case X86::BI__builtin_ia32_maxps512_mask:
  1841. case X86::BI__builtin_ia32_maxsd_round_mask:
  1842. case X86::BI__builtin_ia32_maxss_round_mask:
  1843. case X86::BI__builtin_ia32_minpd512_mask:
  1844. case X86::BI__builtin_ia32_minps512_mask:
  1845. case X86::BI__builtin_ia32_minsd_round_mask:
  1846. case X86::BI__builtin_ia32_minss_round_mask:
  1847. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  1848. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  1849. case X86::BI__builtin_ia32_reducepd512_mask:
  1850. case X86::BI__builtin_ia32_reduceps512_mask:
  1851. case X86::BI__builtin_ia32_rndscalepd_mask:
  1852. case X86::BI__builtin_ia32_rndscaleps_mask:
  1853. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  1854. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  1855. ArgNum = 4;
  1856. break;
  1857. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  1858. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  1859. case X86::BI__builtin_ia32_fixupimmps512_mask:
  1860. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  1861. case X86::BI__builtin_ia32_fixupimmsd_mask:
  1862. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  1863. case X86::BI__builtin_ia32_fixupimmss_mask:
  1864. case X86::BI__builtin_ia32_fixupimmss_maskz:
  1865. case X86::BI__builtin_ia32_rangepd512_mask:
  1866. case X86::BI__builtin_ia32_rangeps512_mask:
  1867. case X86::BI__builtin_ia32_rangesd128_round_mask:
  1868. case X86::BI__builtin_ia32_rangess128_round_mask:
  1869. case X86::BI__builtin_ia32_reducesd_mask:
  1870. case X86::BI__builtin_ia32_reducess_mask:
  1871. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  1872. case X86::BI__builtin_ia32_rndscaless_round_mask:
  1873. ArgNum = 5;
  1874. break;
  1875. case X86::BI__builtin_ia32_vcvtsd2si64:
  1876. case X86::BI__builtin_ia32_vcvtsd2si32:
  1877. case X86::BI__builtin_ia32_vcvtsd2usi32:
  1878. case X86::BI__builtin_ia32_vcvtsd2usi64:
  1879. case X86::BI__builtin_ia32_vcvtss2si32:
  1880. case X86::BI__builtin_ia32_vcvtss2si64:
  1881. case X86::BI__builtin_ia32_vcvtss2usi32:
  1882. case X86::BI__builtin_ia32_vcvtss2usi64:
  1883. ArgNum = 1;
  1884. HasRC = true;
  1885. break;
  1886. case X86::BI__builtin_ia32_cvtsi2sd64:
  1887. case X86::BI__builtin_ia32_cvtsi2ss32:
  1888. case X86::BI__builtin_ia32_cvtsi2ss64:
  1889. case X86::BI__builtin_ia32_cvtusi2sd64:
  1890. case X86::BI__builtin_ia32_cvtusi2ss32:
  1891. case X86::BI__builtin_ia32_cvtusi2ss64:
  1892. ArgNum = 2;
  1893. HasRC = true;
  1894. break;
  1895. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  1896. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  1897. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  1898. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  1899. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  1900. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  1901. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  1902. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  1903. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  1904. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  1905. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  1906. case X86::BI__builtin_ia32_sqrtpd512_mask:
  1907. case X86::BI__builtin_ia32_sqrtps512_mask:
  1908. ArgNum = 3;
  1909. HasRC = true;
  1910. break;
  1911. case X86::BI__builtin_ia32_addpd512_mask:
  1912. case X86::BI__builtin_ia32_addps512_mask:
  1913. case X86::BI__builtin_ia32_divpd512_mask:
  1914. case X86::BI__builtin_ia32_divps512_mask:
  1915. case X86::BI__builtin_ia32_mulpd512_mask:
  1916. case X86::BI__builtin_ia32_mulps512_mask:
  1917. case X86::BI__builtin_ia32_subpd512_mask:
  1918. case X86::BI__builtin_ia32_subps512_mask:
  1919. case X86::BI__builtin_ia32_addss_round_mask:
  1920. case X86::BI__builtin_ia32_addsd_round_mask:
  1921. case X86::BI__builtin_ia32_divss_round_mask:
  1922. case X86::BI__builtin_ia32_divsd_round_mask:
  1923. case X86::BI__builtin_ia32_mulss_round_mask:
  1924. case X86::BI__builtin_ia32_mulsd_round_mask:
  1925. case X86::BI__builtin_ia32_subss_round_mask:
  1926. case X86::BI__builtin_ia32_subsd_round_mask:
  1927. case X86::BI__builtin_ia32_scalefpd512_mask:
  1928. case X86::BI__builtin_ia32_scalefps512_mask:
  1929. case X86::BI__builtin_ia32_scalefsd_round_mask:
  1930. case X86::BI__builtin_ia32_scalefss_round_mask:
  1931. case X86::BI__builtin_ia32_getmantpd512_mask:
  1932. case X86::BI__builtin_ia32_getmantps512_mask:
  1933. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  1934. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  1935. case X86::BI__builtin_ia32_sqrtss_round_mask:
  1936. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  1937. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  1938. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  1939. case X86::BI__builtin_ia32_vfmaddps512_mask:
  1940. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  1941. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  1942. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  1943. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  1944. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  1945. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  1946. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  1947. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  1948. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  1949. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  1950. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  1951. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  1952. case X86::BI__builtin_ia32_vfnmaddpd512_mask:
  1953. case X86::BI__builtin_ia32_vfnmaddps512_mask:
  1954. case X86::BI__builtin_ia32_vfnmsubpd512_mask:
  1955. case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
  1956. case X86::BI__builtin_ia32_vfnmsubps512_mask:
  1957. case X86::BI__builtin_ia32_vfnmsubps512_mask3:
  1958. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  1959. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  1960. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  1961. case X86::BI__builtin_ia32_vfmaddss3_mask:
  1962. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  1963. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  1964. ArgNum = 4;
  1965. HasRC = true;
  1966. break;
  1967. case X86::BI__builtin_ia32_getmantsd_round_mask:
  1968. case X86::BI__builtin_ia32_getmantss_round_mask:
  1969. ArgNum = 5;
  1970. HasRC = true;
  1971. break;
  1972. }
  1973. llvm::APSInt Result;
  1974. // We can't check the value of a dependent argument.
  1975. Expr *Arg = TheCall->getArg(ArgNum);
  1976. if (Arg->isTypeDependent() || Arg->isValueDependent())
  1977. return false;
  1978. // Check constant-ness first.
  1979. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  1980. return true;
  1981. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  1982. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  1983. // combined with ROUND_NO_EXC.
  1984. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  1985. Result == 8/*ROUND_NO_EXC*/ ||
  1986. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  1987. return false;
  1988. return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
  1989. << Arg->getSourceRange();
  1990. }
  1991. // Check if the gather/scatter scale is legal.
  1992. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  1993. CallExpr *TheCall) {
  1994. unsigned ArgNum = 0;
  1995. switch (BuiltinID) {
  1996. default:
  1997. return false;
  1998. case X86::BI__builtin_ia32_gatherpfdpd:
  1999. case X86::BI__builtin_ia32_gatherpfdps:
  2000. case X86::BI__builtin_ia32_gatherpfqpd:
  2001. case X86::BI__builtin_ia32_gatherpfqps:
  2002. case X86::BI__builtin_ia32_scatterpfdpd:
  2003. case X86::BI__builtin_ia32_scatterpfdps:
  2004. case X86::BI__builtin_ia32_scatterpfqpd:
  2005. case X86::BI__builtin_ia32_scatterpfqps:
  2006. ArgNum = 3;
  2007. break;
  2008. case X86::BI__builtin_ia32_gatherd_pd:
  2009. case X86::BI__builtin_ia32_gatherd_pd256:
  2010. case X86::BI__builtin_ia32_gatherq_pd:
  2011. case X86::BI__builtin_ia32_gatherq_pd256:
  2012. case X86::BI__builtin_ia32_gatherd_ps:
  2013. case X86::BI__builtin_ia32_gatherd_ps256:
  2014. case X86::BI__builtin_ia32_gatherq_ps:
  2015. case X86::BI__builtin_ia32_gatherq_ps256:
  2016. case X86::BI__builtin_ia32_gatherd_q:
  2017. case X86::BI__builtin_ia32_gatherd_q256:
  2018. case X86::BI__builtin_ia32_gatherq_q:
  2019. case X86::BI__builtin_ia32_gatherq_q256:
  2020. case X86::BI__builtin_ia32_gatherd_d:
  2021. case X86::BI__builtin_ia32_gatherd_d256:
  2022. case X86::BI__builtin_ia32_gatherq_d:
  2023. case X86::BI__builtin_ia32_gatherq_d256:
  2024. case X86::BI__builtin_ia32_gather3div2df:
  2025. case X86::BI__builtin_ia32_gather3div2di:
  2026. case X86::BI__builtin_ia32_gather3div4df:
  2027. case X86::BI__builtin_ia32_gather3div4di:
  2028. case X86::BI__builtin_ia32_gather3div4sf:
  2029. case X86::BI__builtin_ia32_gather3div4si:
  2030. case X86::BI__builtin_ia32_gather3div8sf:
  2031. case X86::BI__builtin_ia32_gather3div8si:
  2032. case X86::BI__builtin_ia32_gather3siv2df:
  2033. case X86::BI__builtin_ia32_gather3siv2di:
  2034. case X86::BI__builtin_ia32_gather3siv4df:
  2035. case X86::BI__builtin_ia32_gather3siv4di:
  2036. case X86::BI__builtin_ia32_gather3siv4sf:
  2037. case X86::BI__builtin_ia32_gather3siv4si:
  2038. case X86::BI__builtin_ia32_gather3siv8sf:
  2039. case X86::BI__builtin_ia32_gather3siv8si:
  2040. case X86::BI__builtin_ia32_gathersiv8df:
  2041. case X86::BI__builtin_ia32_gathersiv16sf:
  2042. case X86::BI__builtin_ia32_gatherdiv8df:
  2043. case X86::BI__builtin_ia32_gatherdiv16sf:
  2044. case X86::BI__builtin_ia32_gathersiv8di:
  2045. case X86::BI__builtin_ia32_gathersiv16si:
  2046. case X86::BI__builtin_ia32_gatherdiv8di:
  2047. case X86::BI__builtin_ia32_gatherdiv16si:
  2048. case X86::BI__builtin_ia32_scatterdiv2df:
  2049. case X86::BI__builtin_ia32_scatterdiv2di:
  2050. case X86::BI__builtin_ia32_scatterdiv4df:
  2051. case X86::BI__builtin_ia32_scatterdiv4di:
  2052. case X86::BI__builtin_ia32_scatterdiv4sf:
  2053. case X86::BI__builtin_ia32_scatterdiv4si:
  2054. case X86::BI__builtin_ia32_scatterdiv8sf:
  2055. case X86::BI__builtin_ia32_scatterdiv8si:
  2056. case X86::BI__builtin_ia32_scattersiv2df:
  2057. case X86::BI__builtin_ia32_scattersiv2di:
  2058. case X86::BI__builtin_ia32_scattersiv4df:
  2059. case X86::BI__builtin_ia32_scattersiv4di:
  2060. case X86::BI__builtin_ia32_scattersiv4sf:
  2061. case X86::BI__builtin_ia32_scattersiv4si:
  2062. case X86::BI__builtin_ia32_scattersiv8sf:
  2063. case X86::BI__builtin_ia32_scattersiv8si:
  2064. case X86::BI__builtin_ia32_scattersiv8df:
  2065. case X86::BI__builtin_ia32_scattersiv16sf:
  2066. case X86::BI__builtin_ia32_scatterdiv8df:
  2067. case X86::BI__builtin_ia32_scatterdiv16sf:
  2068. case X86::BI__builtin_ia32_scattersiv8di:
  2069. case X86::BI__builtin_ia32_scattersiv16si:
  2070. case X86::BI__builtin_ia32_scatterdiv8di:
  2071. case X86::BI__builtin_ia32_scatterdiv16si:
  2072. ArgNum = 4;
  2073. break;
  2074. }
  2075. llvm::APSInt Result;
  2076. // We can't check the value of a dependent argument.
  2077. Expr *Arg = TheCall->getArg(ArgNum);
  2078. if (Arg->isTypeDependent() || Arg->isValueDependent())
  2079. return false;
  2080. // Check constant-ness first.
  2081. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  2082. return true;
  2083. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  2084. return false;
  2085. return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
  2086. << Arg->getSourceRange();
  2087. }
  2088. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2089. if (BuiltinID == X86::BI__builtin_cpu_supports)
  2090. return SemaBuiltinCpuSupports(*this, TheCall);
  2091. if (BuiltinID == X86::BI__builtin_cpu_is)
  2092. return SemaBuiltinCpuIs(*this, TheCall);
  2093. // If the intrinsic has rounding or SAE make sure its valid.
  2094. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  2095. return true;
  2096. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  2097. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  2098. return true;
  2099. // For intrinsics which take an immediate value as part of the instruction,
  2100. // range check them here.
  2101. int i = 0, l = 0, u = 0;
  2102. switch (BuiltinID) {
  2103. default:
  2104. return false;
  2105. case X86::BI_mm_prefetch:
  2106. i = 1; l = 0; u = 3;
  2107. break;
  2108. case X86::BI__builtin_ia32_sha1rnds4:
  2109. case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
  2110. case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
  2111. case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
  2112. case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
  2113. i = 2; l = 0; u = 3;
  2114. break;
  2115. case X86::BI__builtin_ia32_vpermil2pd:
  2116. case X86::BI__builtin_ia32_vpermil2pd256:
  2117. case X86::BI__builtin_ia32_vpermil2ps:
  2118. case X86::BI__builtin_ia32_vpermil2ps256:
  2119. i = 3; l = 0; u = 3;
  2120. break;
  2121. case X86::BI__builtin_ia32_cmpb128_mask:
  2122. case X86::BI__builtin_ia32_cmpw128_mask:
  2123. case X86::BI__builtin_ia32_cmpd128_mask:
  2124. case X86::BI__builtin_ia32_cmpq128_mask:
  2125. case X86::BI__builtin_ia32_cmpb256_mask:
  2126. case X86::BI__builtin_ia32_cmpw256_mask:
  2127. case X86::BI__builtin_ia32_cmpd256_mask:
  2128. case X86::BI__builtin_ia32_cmpq256_mask:
  2129. case X86::BI__builtin_ia32_cmpb512_mask:
  2130. case X86::BI__builtin_ia32_cmpw512_mask:
  2131. case X86::BI__builtin_ia32_cmpd512_mask:
  2132. case X86::BI__builtin_ia32_cmpq512_mask:
  2133. case X86::BI__builtin_ia32_ucmpb128_mask:
  2134. case X86::BI__builtin_ia32_ucmpw128_mask:
  2135. case X86::BI__builtin_ia32_ucmpd128_mask:
  2136. case X86::BI__builtin_ia32_ucmpq128_mask:
  2137. case X86::BI__builtin_ia32_ucmpb256_mask:
  2138. case X86::BI__builtin_ia32_ucmpw256_mask:
  2139. case X86::BI__builtin_ia32_ucmpd256_mask:
  2140. case X86::BI__builtin_ia32_ucmpq256_mask:
  2141. case X86::BI__builtin_ia32_ucmpb512_mask:
  2142. case X86::BI__builtin_ia32_ucmpw512_mask:
  2143. case X86::BI__builtin_ia32_ucmpd512_mask:
  2144. case X86::BI__builtin_ia32_ucmpq512_mask:
  2145. case X86::BI__builtin_ia32_vpcomub:
  2146. case X86::BI__builtin_ia32_vpcomuw:
  2147. case X86::BI__builtin_ia32_vpcomud:
  2148. case X86::BI__builtin_ia32_vpcomuq:
  2149. case X86::BI__builtin_ia32_vpcomb:
  2150. case X86::BI__builtin_ia32_vpcomw:
  2151. case X86::BI__builtin_ia32_vpcomd:
  2152. case X86::BI__builtin_ia32_vpcomq:
  2153. i = 2; l = 0; u = 7;
  2154. break;
  2155. case X86::BI__builtin_ia32_roundps:
  2156. case X86::BI__builtin_ia32_roundpd:
  2157. case X86::BI__builtin_ia32_roundps256:
  2158. case X86::BI__builtin_ia32_roundpd256:
  2159. i = 1; l = 0; u = 15;
  2160. break;
  2161. case X86::BI__builtin_ia32_roundss:
  2162. case X86::BI__builtin_ia32_roundsd:
  2163. case X86::BI__builtin_ia32_rangepd128_mask:
  2164. case X86::BI__builtin_ia32_rangepd256_mask:
  2165. case X86::BI__builtin_ia32_rangepd512_mask:
  2166. case X86::BI__builtin_ia32_rangeps128_mask:
  2167. case X86::BI__builtin_ia32_rangeps256_mask:
  2168. case X86::BI__builtin_ia32_rangeps512_mask:
  2169. case X86::BI__builtin_ia32_getmantsd_round_mask:
  2170. case X86::BI__builtin_ia32_getmantss_round_mask:
  2171. i = 2; l = 0; u = 15;
  2172. break;
  2173. case X86::BI__builtin_ia32_cmpps:
  2174. case X86::BI__builtin_ia32_cmpss:
  2175. case X86::BI__builtin_ia32_cmppd:
  2176. case X86::BI__builtin_ia32_cmpsd:
  2177. case X86::BI__builtin_ia32_cmpps256:
  2178. case X86::BI__builtin_ia32_cmppd256:
  2179. case X86::BI__builtin_ia32_cmpps128_mask:
  2180. case X86::BI__builtin_ia32_cmppd128_mask:
  2181. case X86::BI__builtin_ia32_cmpps256_mask:
  2182. case X86::BI__builtin_ia32_cmppd256_mask:
  2183. case X86::BI__builtin_ia32_cmpps512_mask:
  2184. case X86::BI__builtin_ia32_cmppd512_mask:
  2185. case X86::BI__builtin_ia32_cmpsd_mask:
  2186. case X86::BI__builtin_ia32_cmpss_mask:
  2187. i = 2; l = 0; u = 31;
  2188. break;
  2189. case X86::BI__builtin_ia32_xabort:
  2190. i = 0; l = -128; u = 255;
  2191. break;
  2192. case X86::BI__builtin_ia32_pshufw:
  2193. case X86::BI__builtin_ia32_aeskeygenassist128:
  2194. i = 1; l = -128; u = 255;
  2195. break;
  2196. case X86::BI__builtin_ia32_vcvtps2ph:
  2197. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  2198. case X86::BI__builtin_ia32_vcvtps2ph256:
  2199. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  2200. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  2201. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  2202. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  2203. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  2204. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  2205. case X86::BI__builtin_ia32_rndscaleps_mask:
  2206. case X86::BI__builtin_ia32_rndscalepd_mask:
  2207. case X86::BI__builtin_ia32_reducepd128_mask:
  2208. case X86::BI__builtin_ia32_reducepd256_mask:
  2209. case X86::BI__builtin_ia32_reducepd512_mask:
  2210. case X86::BI__builtin_ia32_reduceps128_mask:
  2211. case X86::BI__builtin_ia32_reduceps256_mask:
  2212. case X86::BI__builtin_ia32_reduceps512_mask:
  2213. case X86::BI__builtin_ia32_prold512_mask:
  2214. case X86::BI__builtin_ia32_prolq512_mask:
  2215. case X86::BI__builtin_ia32_prold128_mask:
  2216. case X86::BI__builtin_ia32_prold256_mask:
  2217. case X86::BI__builtin_ia32_prolq128_mask:
  2218. case X86::BI__builtin_ia32_prolq256_mask:
  2219. case X86::BI__builtin_ia32_prord128_mask:
  2220. case X86::BI__builtin_ia32_prord256_mask:
  2221. case X86::BI__builtin_ia32_prorq128_mask:
  2222. case X86::BI__builtin_ia32_prorq256_mask:
  2223. case X86::BI__builtin_ia32_fpclasspd128_mask:
  2224. case X86::BI__builtin_ia32_fpclasspd256_mask:
  2225. case X86::BI__builtin_ia32_fpclassps128_mask:
  2226. case X86::BI__builtin_ia32_fpclassps256_mask:
  2227. case X86::BI__builtin_ia32_fpclassps512_mask:
  2228. case X86::BI__builtin_ia32_fpclasspd512_mask:
  2229. case X86::BI__builtin_ia32_fpclasssd_mask:
  2230. case X86::BI__builtin_ia32_fpclassss_mask:
  2231. i = 1; l = 0; u = 255;
  2232. break;
  2233. case X86::BI__builtin_ia32_palignr:
  2234. case X86::BI__builtin_ia32_insertps128:
  2235. case X86::BI__builtin_ia32_dpps:
  2236. case X86::BI__builtin_ia32_dppd:
  2237. case X86::BI__builtin_ia32_dpps256:
  2238. case X86::BI__builtin_ia32_mpsadbw128:
  2239. case X86::BI__builtin_ia32_mpsadbw256:
  2240. case X86::BI__builtin_ia32_pcmpistrm128:
  2241. case X86::BI__builtin_ia32_pcmpistri128:
  2242. case X86::BI__builtin_ia32_pcmpistria128:
  2243. case X86::BI__builtin_ia32_pcmpistric128:
  2244. case X86::BI__builtin_ia32_pcmpistrio128:
  2245. case X86::BI__builtin_ia32_pcmpistris128:
  2246. case X86::BI__builtin_ia32_pcmpistriz128:
  2247. case X86::BI__builtin_ia32_pclmulqdq128:
  2248. case X86::BI__builtin_ia32_vperm2f128_pd256:
  2249. case X86::BI__builtin_ia32_vperm2f128_ps256:
  2250. case X86::BI__builtin_ia32_vperm2f128_si256:
  2251. case X86::BI__builtin_ia32_permti256:
  2252. i = 2; l = -128; u = 255;
  2253. break;
  2254. case X86::BI__builtin_ia32_palignr128:
  2255. case X86::BI__builtin_ia32_palignr256:
  2256. case X86::BI__builtin_ia32_palignr512_mask:
  2257. case X86::BI__builtin_ia32_vcomisd:
  2258. case X86::BI__builtin_ia32_vcomiss:
  2259. case X86::BI__builtin_ia32_shuf_f32x4_mask:
  2260. case X86::BI__builtin_ia32_shuf_f64x2_mask:
  2261. case X86::BI__builtin_ia32_shuf_i32x4_mask:
  2262. case X86::BI__builtin_ia32_shuf_i64x2_mask:
  2263. case X86::BI__builtin_ia32_dbpsadbw128_mask:
  2264. case X86::BI__builtin_ia32_dbpsadbw256_mask:
  2265. case X86::BI__builtin_ia32_dbpsadbw512_mask:
  2266. i = 2; l = 0; u = 255;
  2267. break;
  2268. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  2269. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  2270. case X86::BI__builtin_ia32_fixupimmps512_mask:
  2271. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  2272. case X86::BI__builtin_ia32_fixupimmsd_mask:
  2273. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  2274. case X86::BI__builtin_ia32_fixupimmss_mask:
  2275. case X86::BI__builtin_ia32_fixupimmss_maskz:
  2276. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  2277. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  2278. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  2279. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  2280. case X86::BI__builtin_ia32_fixupimmps128_mask:
  2281. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  2282. case X86::BI__builtin_ia32_fixupimmps256_mask:
  2283. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  2284. case X86::BI__builtin_ia32_pternlogd512_mask:
  2285. case X86::BI__builtin_ia32_pternlogd512_maskz:
  2286. case X86::BI__builtin_ia32_pternlogq512_mask:
  2287. case X86::BI__builtin_ia32_pternlogq512_maskz:
  2288. case X86::BI__builtin_ia32_pternlogd128_mask:
  2289. case X86::BI__builtin_ia32_pternlogd128_maskz:
  2290. case X86::BI__builtin_ia32_pternlogd256_mask:
  2291. case X86::BI__builtin_ia32_pternlogd256_maskz:
  2292. case X86::BI__builtin_ia32_pternlogq128_mask:
  2293. case X86::BI__builtin_ia32_pternlogq128_maskz:
  2294. case X86::BI__builtin_ia32_pternlogq256_mask:
  2295. case X86::BI__builtin_ia32_pternlogq256_maskz:
  2296. i = 3; l = 0; u = 255;
  2297. break;
  2298. case X86::BI__builtin_ia32_gatherpfdpd:
  2299. case X86::BI__builtin_ia32_gatherpfdps:
  2300. case X86::BI__builtin_ia32_gatherpfqpd:
  2301. case X86::BI__builtin_ia32_gatherpfqps:
  2302. case X86::BI__builtin_ia32_scatterpfdpd:
  2303. case X86::BI__builtin_ia32_scatterpfdps:
  2304. case X86::BI__builtin_ia32_scatterpfqpd:
  2305. case X86::BI__builtin_ia32_scatterpfqps:
  2306. i = 4; l = 2; u = 3;
  2307. break;
  2308. case X86::BI__builtin_ia32_pcmpestrm128:
  2309. case X86::BI__builtin_ia32_pcmpestri128:
  2310. case X86::BI__builtin_ia32_pcmpestria128:
  2311. case X86::BI__builtin_ia32_pcmpestric128:
  2312. case X86::BI__builtin_ia32_pcmpestrio128:
  2313. case X86::BI__builtin_ia32_pcmpestris128:
  2314. case X86::BI__builtin_ia32_pcmpestriz128:
  2315. i = 4; l = -128; u = 255;
  2316. break;
  2317. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  2318. case X86::BI__builtin_ia32_rndscaless_round_mask:
  2319. i = 4; l = 0; u = 255;
  2320. break;
  2321. }
  2322. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2323. }
  2324. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  2325. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  2326. /// Returns true when the format fits the function and the FormatStringInfo has
  2327. /// been populated.
  2328. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  2329. FormatStringInfo *FSI) {
  2330. FSI->HasVAListArg = Format->getFirstArg() == 0;
  2331. FSI->FormatIdx = Format->getFormatIdx() - 1;
  2332. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  2333. // The way the format attribute works in GCC, the implicit this argument
  2334. // of member functions is counted. However, it doesn't appear in our own
  2335. // lists, so decrement format_idx in that case.
  2336. if (IsCXXMember) {
  2337. if(FSI->FormatIdx == 0)
  2338. return false;
  2339. --FSI->FormatIdx;
  2340. if (FSI->FirstDataArg != 0)
  2341. --FSI->FirstDataArg;
  2342. }
  2343. return true;
  2344. }
  2345. /// Checks if a the given expression evaluates to null.
  2346. ///
  2347. /// \brief Returns true if the value evaluates to null.
  2348. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  2349. // If the expression has non-null type, it doesn't evaluate to null.
  2350. if (auto nullability
  2351. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  2352. if (*nullability == NullabilityKind::NonNull)
  2353. return false;
  2354. }
  2355. // As a special case, transparent unions initialized with zero are
  2356. // considered null for the purposes of the nonnull attribute.
  2357. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  2358. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  2359. if (const CompoundLiteralExpr *CLE =
  2360. dyn_cast<CompoundLiteralExpr>(Expr))
  2361. if (const InitListExpr *ILE =
  2362. dyn_cast<InitListExpr>(CLE->getInitializer()))
  2363. Expr = ILE->getInit(0);
  2364. }
  2365. bool Result;
  2366. return (!Expr->isValueDependent() &&
  2367. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  2368. !Result);
  2369. }
  2370. static void CheckNonNullArgument(Sema &S,
  2371. const Expr *ArgExpr,
  2372. SourceLocation CallSiteLoc) {
  2373. if (CheckNonNullExpr(S, ArgExpr))
  2374. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  2375. S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
  2376. }
  2377. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  2378. FormatStringInfo FSI;
  2379. if ((GetFormatStringType(Format) == FST_NSString) &&
  2380. getFormatStringInfo(Format, false, &FSI)) {
  2381. Idx = FSI.FormatIdx;
  2382. return true;
  2383. }
  2384. return false;
  2385. }
  2386. /// \brief Diagnose use of %s directive in an NSString which is being passed
  2387. /// as formatting string to formatting method.
  2388. static void
  2389. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  2390. const NamedDecl *FDecl,
  2391. Expr **Args,
  2392. unsigned NumArgs) {
  2393. unsigned Idx = 0;
  2394. bool Format = false;
  2395. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  2396. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  2397. Idx = 2;
  2398. Format = true;
  2399. }
  2400. else
  2401. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  2402. if (S.GetFormatNSStringIdx(I, Idx)) {
  2403. Format = true;
  2404. break;
  2405. }
  2406. }
  2407. if (!Format || NumArgs <= Idx)
  2408. return;
  2409. const Expr *FormatExpr = Args[Idx];
  2410. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  2411. FormatExpr = CSCE->getSubExpr();
  2412. const StringLiteral *FormatString;
  2413. if (const ObjCStringLiteral *OSL =
  2414. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  2415. FormatString = OSL->getString();
  2416. else
  2417. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  2418. if (!FormatString)
  2419. return;
  2420. if (S.FormatStringHasSArg(FormatString)) {
  2421. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  2422. << "%s" << 1 << 1;
  2423. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  2424. << FDecl->getDeclName();
  2425. }
  2426. }
  2427. /// Determine whether the given type has a non-null nullability annotation.
  2428. static bool isNonNullType(ASTContext &ctx, QualType type) {
  2429. if (auto nullability = type->getNullability(ctx))
  2430. return *nullability == NullabilityKind::NonNull;
  2431. return false;
  2432. }
  2433. static void CheckNonNullArguments(Sema &S,
  2434. const NamedDecl *FDecl,
  2435. const FunctionProtoType *Proto,
  2436. ArrayRef<const Expr *> Args,
  2437. SourceLocation CallSiteLoc) {
  2438. assert((FDecl || Proto) && "Need a function declaration or prototype");
  2439. // Check the attributes attached to the method/function itself.
  2440. llvm::SmallBitVector NonNullArgs;
  2441. if (FDecl) {
  2442. // Handle the nonnull attribute on the function/method declaration itself.
  2443. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  2444. if (!NonNull->args_size()) {
  2445. // Easy case: all pointer arguments are nonnull.
  2446. for (const auto *Arg : Args)
  2447. if (S.isValidPointerAttrType(Arg->getType()))
  2448. CheckNonNullArgument(S, Arg, CallSiteLoc);
  2449. return;
  2450. }
  2451. for (unsigned Val : NonNull->args()) {
  2452. if (Val >= Args.size())
  2453. continue;
  2454. if (NonNullArgs.empty())
  2455. NonNullArgs.resize(Args.size());
  2456. NonNullArgs.set(Val);
  2457. }
  2458. }
  2459. }
  2460. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  2461. // Handle the nonnull attribute on the parameters of the
  2462. // function/method.
  2463. ArrayRef<ParmVarDecl*> parms;
  2464. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  2465. parms = FD->parameters();
  2466. else
  2467. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  2468. unsigned ParamIndex = 0;
  2469. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  2470. I != E; ++I, ++ParamIndex) {
  2471. const ParmVarDecl *PVD = *I;
  2472. if (PVD->hasAttr<NonNullAttr>() ||
  2473. isNonNullType(S.Context, PVD->getType())) {
  2474. if (NonNullArgs.empty())
  2475. NonNullArgs.resize(Args.size());
  2476. NonNullArgs.set(ParamIndex);
  2477. }
  2478. }
  2479. } else {
  2480. // If we have a non-function, non-method declaration but no
  2481. // function prototype, try to dig out the function prototype.
  2482. if (!Proto) {
  2483. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  2484. QualType type = VD->getType().getNonReferenceType();
  2485. if (auto pointerType = type->getAs<PointerType>())
  2486. type = pointerType->getPointeeType();
  2487. else if (auto blockType = type->getAs<BlockPointerType>())
  2488. type = blockType->getPointeeType();
  2489. // FIXME: data member pointers?
  2490. // Dig out the function prototype, if there is one.
  2491. Proto = type->getAs<FunctionProtoType>();
  2492. }
  2493. }
  2494. // Fill in non-null argument information from the nullability
  2495. // information on the parameter types (if we have them).
  2496. if (Proto) {
  2497. unsigned Index = 0;
  2498. for (auto paramType : Proto->getParamTypes()) {
  2499. if (isNonNullType(S.Context, paramType)) {
  2500. if (NonNullArgs.empty())
  2501. NonNullArgs.resize(Args.size());
  2502. NonNullArgs.set(Index);
  2503. }
  2504. ++Index;
  2505. }
  2506. }
  2507. }
  2508. // Check for non-null arguments.
  2509. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  2510. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  2511. if (NonNullArgs[ArgIndex])
  2512. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  2513. }
  2514. }
  2515. /// Handles the checks for format strings, non-POD arguments to vararg
  2516. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  2517. /// attributes.
  2518. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  2519. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  2520. bool IsMemberFunction, SourceLocation Loc,
  2521. SourceRange Range, VariadicCallType CallType) {
  2522. // FIXME: We should check as much as we can in the template definition.
  2523. if (CurContext->isDependentContext())
  2524. return;
  2525. // Printf and scanf checking.
  2526. llvm::SmallBitVector CheckedVarArgs;
  2527. if (FDecl) {
  2528. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  2529. // Only create vector if there are format attributes.
  2530. CheckedVarArgs.resize(Args.size());
  2531. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  2532. CheckedVarArgs);
  2533. }
  2534. }
  2535. // Refuse POD arguments that weren't caught by the format string
  2536. // checks above.
  2537. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  2538. if (CallType != VariadicDoesNotApply &&
  2539. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  2540. unsigned NumParams = Proto ? Proto->getNumParams()
  2541. : FDecl && isa<FunctionDecl>(FDecl)
  2542. ? cast<FunctionDecl>(FDecl)->getNumParams()
  2543. : FDecl && isa<ObjCMethodDecl>(FDecl)
  2544. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  2545. : 0;
  2546. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  2547. // Args[ArgIdx] can be null in malformed code.
  2548. if (const Expr *Arg = Args[ArgIdx]) {
  2549. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  2550. checkVariadicArgument(Arg, CallType);
  2551. }
  2552. }
  2553. }
  2554. if (FDecl || Proto) {
  2555. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  2556. // Type safety checking.
  2557. if (FDecl) {
  2558. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  2559. CheckArgumentWithTypeTag(I, Args, Loc);
  2560. }
  2561. }
  2562. if (FD)
  2563. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  2564. }
  2565. /// CheckConstructorCall - Check a constructor call for correctness and safety
  2566. /// properties not enforced by the C type system.
  2567. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  2568. ArrayRef<const Expr *> Args,
  2569. const FunctionProtoType *Proto,
  2570. SourceLocation Loc) {
  2571. VariadicCallType CallType =
  2572. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  2573. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  2574. Loc, SourceRange(), CallType);
  2575. }
  2576. /// CheckFunctionCall - Check a direct function call for various correctness
  2577. /// and safety properties not strictly enforced by the C type system.
  2578. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  2579. const FunctionProtoType *Proto) {
  2580. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  2581. isa<CXXMethodDecl>(FDecl);
  2582. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  2583. IsMemberOperatorCall;
  2584. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  2585. TheCall->getCallee());
  2586. Expr** Args = TheCall->getArgs();
  2587. unsigned NumArgs = TheCall->getNumArgs();
  2588. Expr *ImplicitThis = nullptr;
  2589. if (IsMemberOperatorCall) {
  2590. // If this is a call to a member operator, hide the first argument
  2591. // from checkCall.
  2592. // FIXME: Our choice of AST representation here is less than ideal.
  2593. ImplicitThis = Args[0];
  2594. ++Args;
  2595. --NumArgs;
  2596. } else if (IsMemberFunction)
  2597. ImplicitThis =
  2598. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  2599. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  2600. IsMemberFunction, TheCall->getRParenLoc(),
  2601. TheCall->getCallee()->getSourceRange(), CallType);
  2602. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  2603. // None of the checks below are needed for functions that don't have
  2604. // simple names (e.g., C++ conversion functions).
  2605. if (!FnInfo)
  2606. return false;
  2607. CheckAbsoluteValueFunction(TheCall, FDecl);
  2608. CheckMaxUnsignedZero(TheCall, FDecl);
  2609. if (getLangOpts().ObjC1)
  2610. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  2611. unsigned CMId = FDecl->getMemoryFunctionKind();
  2612. if (CMId == 0)
  2613. return false;
  2614. // Handle memory setting and copying functions.
  2615. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  2616. CheckStrlcpycatArguments(TheCall, FnInfo);
  2617. else if (CMId == Builtin::BIstrncat)
  2618. CheckStrncatArguments(TheCall, FnInfo);
  2619. else
  2620. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  2621. return false;
  2622. }
  2623. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  2624. ArrayRef<const Expr *> Args) {
  2625. VariadicCallType CallType =
  2626. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  2627. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  2628. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  2629. CallType);
  2630. return false;
  2631. }
  2632. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  2633. const FunctionProtoType *Proto) {
  2634. QualType Ty;
  2635. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  2636. Ty = V->getType().getNonReferenceType();
  2637. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  2638. Ty = F->getType().getNonReferenceType();
  2639. else
  2640. return false;
  2641. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  2642. !Ty->isFunctionProtoType())
  2643. return false;
  2644. VariadicCallType CallType;
  2645. if (!Proto || !Proto->isVariadic()) {
  2646. CallType = VariadicDoesNotApply;
  2647. } else if (Ty->isBlockPointerType()) {
  2648. CallType = VariadicBlock;
  2649. } else { // Ty->isFunctionPointerType()
  2650. CallType = VariadicFunction;
  2651. }
  2652. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  2653. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  2654. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  2655. TheCall->getCallee()->getSourceRange(), CallType);
  2656. return false;
  2657. }
  2658. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  2659. /// such as function pointers returned from functions.
  2660. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  2661. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  2662. TheCall->getCallee());
  2663. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  2664. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  2665. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  2666. TheCall->getCallee()->getSourceRange(), CallType);
  2667. return false;
  2668. }
  2669. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  2670. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  2671. return false;
  2672. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  2673. switch (Op) {
  2674. case AtomicExpr::AO__c11_atomic_init:
  2675. case AtomicExpr::AO__opencl_atomic_init:
  2676. llvm_unreachable("There is no ordering argument for an init");
  2677. case AtomicExpr::AO__c11_atomic_load:
  2678. case AtomicExpr::AO__opencl_atomic_load:
  2679. case AtomicExpr::AO__atomic_load_n:
  2680. case AtomicExpr::AO__atomic_load:
  2681. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  2682. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  2683. case AtomicExpr::AO__c11_atomic_store:
  2684. case AtomicExpr::AO__opencl_atomic_store:
  2685. case AtomicExpr::AO__atomic_store:
  2686. case AtomicExpr::AO__atomic_store_n:
  2687. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  2688. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  2689. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  2690. default:
  2691. return true;
  2692. }
  2693. }
  2694. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  2695. AtomicExpr::AtomicOp Op) {
  2696. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  2697. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  2698. // All the non-OpenCL operations take one of the following forms.
  2699. // The OpenCL operations take the __c11 forms with one extra argument for
  2700. // synchronization scope.
  2701. enum {
  2702. // C __c11_atomic_init(A *, C)
  2703. Init,
  2704. // C __c11_atomic_load(A *, int)
  2705. Load,
  2706. // void __atomic_load(A *, CP, int)
  2707. LoadCopy,
  2708. // void __atomic_store(A *, CP, int)
  2709. Copy,
  2710. // C __c11_atomic_add(A *, M, int)
  2711. Arithmetic,
  2712. // C __atomic_exchange_n(A *, CP, int)
  2713. Xchg,
  2714. // void __atomic_exchange(A *, C *, CP, int)
  2715. GNUXchg,
  2716. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  2717. C11CmpXchg,
  2718. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  2719. GNUCmpXchg
  2720. } Form = Init;
  2721. const unsigned NumForm = GNUCmpXchg + 1;
  2722. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  2723. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  2724. // where:
  2725. // C is an appropriate type,
  2726. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  2727. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  2728. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  2729. // the int parameters are for orderings.
  2730. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  2731. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  2732. "need to update code for modified forms");
  2733. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  2734. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  2735. AtomicExpr::AO__atomic_load,
  2736. "need to update code for modified C11 atomics");
  2737. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  2738. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  2739. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  2740. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  2741. IsOpenCL;
  2742. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  2743. Op == AtomicExpr::AO__atomic_store_n ||
  2744. Op == AtomicExpr::AO__atomic_exchange_n ||
  2745. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  2746. bool IsAddSub = false;
  2747. switch (Op) {
  2748. case AtomicExpr::AO__c11_atomic_init:
  2749. case AtomicExpr::AO__opencl_atomic_init:
  2750. Form = Init;
  2751. break;
  2752. case AtomicExpr::AO__c11_atomic_load:
  2753. case AtomicExpr::AO__opencl_atomic_load:
  2754. case AtomicExpr::AO__atomic_load_n:
  2755. Form = Load;
  2756. break;
  2757. case AtomicExpr::AO__atomic_load:
  2758. Form = LoadCopy;
  2759. break;
  2760. case AtomicExpr::AO__c11_atomic_store:
  2761. case AtomicExpr::AO__opencl_atomic_store:
  2762. case AtomicExpr::AO__atomic_store:
  2763. case AtomicExpr::AO__atomic_store_n:
  2764. Form = Copy;
  2765. break;
  2766. case AtomicExpr::AO__c11_atomic_fetch_add:
  2767. case AtomicExpr::AO__c11_atomic_fetch_sub:
  2768. case AtomicExpr::AO__opencl_atomic_fetch_add:
  2769. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  2770. case AtomicExpr::AO__opencl_atomic_fetch_min:
  2771. case AtomicExpr::AO__opencl_atomic_fetch_max:
  2772. case AtomicExpr::AO__atomic_fetch_add:
  2773. case AtomicExpr::AO__atomic_fetch_sub:
  2774. case AtomicExpr::AO__atomic_add_fetch:
  2775. case AtomicExpr::AO__atomic_sub_fetch:
  2776. IsAddSub = true;
  2777. // Fall through.
  2778. case AtomicExpr::AO__c11_atomic_fetch_and:
  2779. case AtomicExpr::AO__c11_atomic_fetch_or:
  2780. case AtomicExpr::AO__c11_atomic_fetch_xor:
  2781. case AtomicExpr::AO__opencl_atomic_fetch_and:
  2782. case AtomicExpr::AO__opencl_atomic_fetch_or:
  2783. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  2784. case AtomicExpr::AO__atomic_fetch_and:
  2785. case AtomicExpr::AO__atomic_fetch_or:
  2786. case AtomicExpr::AO__atomic_fetch_xor:
  2787. case AtomicExpr::AO__atomic_fetch_nand:
  2788. case AtomicExpr::AO__atomic_and_fetch:
  2789. case AtomicExpr::AO__atomic_or_fetch:
  2790. case AtomicExpr::AO__atomic_xor_fetch:
  2791. case AtomicExpr::AO__atomic_nand_fetch:
  2792. Form = Arithmetic;
  2793. break;
  2794. case AtomicExpr::AO__c11_atomic_exchange:
  2795. case AtomicExpr::AO__opencl_atomic_exchange:
  2796. case AtomicExpr::AO__atomic_exchange_n:
  2797. Form = Xchg;
  2798. break;
  2799. case AtomicExpr::AO__atomic_exchange:
  2800. Form = GNUXchg;
  2801. break;
  2802. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  2803. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  2804. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  2805. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  2806. Form = C11CmpXchg;
  2807. break;
  2808. case AtomicExpr::AO__atomic_compare_exchange:
  2809. case AtomicExpr::AO__atomic_compare_exchange_n:
  2810. Form = GNUCmpXchg;
  2811. break;
  2812. }
  2813. unsigned AdjustedNumArgs = NumArgs[Form];
  2814. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  2815. ++AdjustedNumArgs;
  2816. // Check we have the right number of arguments.
  2817. if (TheCall->getNumArgs() < AdjustedNumArgs) {
  2818. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  2819. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  2820. << TheCall->getCallee()->getSourceRange();
  2821. return ExprError();
  2822. } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
  2823. Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
  2824. diag::err_typecheck_call_too_many_args)
  2825. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  2826. << TheCall->getCallee()->getSourceRange();
  2827. return ExprError();
  2828. }
  2829. // Inspect the first argument of the atomic operation.
  2830. Expr *Ptr = TheCall->getArg(0);
  2831. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  2832. if (ConvertedPtr.isInvalid())
  2833. return ExprError();
  2834. Ptr = ConvertedPtr.get();
  2835. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  2836. if (!pointerType) {
  2837. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  2838. << Ptr->getType() << Ptr->getSourceRange();
  2839. return ExprError();
  2840. }
  2841. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  2842. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  2843. QualType ValType = AtomTy; // 'C'
  2844. if (IsC11) {
  2845. if (!AtomTy->isAtomicType()) {
  2846. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  2847. << Ptr->getType() << Ptr->getSourceRange();
  2848. return ExprError();
  2849. }
  2850. if (AtomTy.isConstQualified() ||
  2851. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  2852. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
  2853. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  2854. << Ptr->getSourceRange();
  2855. return ExprError();
  2856. }
  2857. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  2858. } else if (Form != Load && Form != LoadCopy) {
  2859. if (ValType.isConstQualified()) {
  2860. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
  2861. << Ptr->getType() << Ptr->getSourceRange();
  2862. return ExprError();
  2863. }
  2864. }
  2865. // For an arithmetic operation, the implied arithmetic must be well-formed.
  2866. if (Form == Arithmetic) {
  2867. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  2868. if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
  2869. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  2870. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  2871. return ExprError();
  2872. }
  2873. if (!IsAddSub && !ValType->isIntegerType()) {
  2874. Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
  2875. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  2876. return ExprError();
  2877. }
  2878. if (IsC11 && ValType->isPointerType() &&
  2879. RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
  2880. diag::err_incomplete_type)) {
  2881. return ExprError();
  2882. }
  2883. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  2884. // For __atomic_*_n operations, the value type must be a scalar integral or
  2885. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  2886. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  2887. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  2888. return ExprError();
  2889. }
  2890. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  2891. !AtomTy->isScalarType()) {
  2892. // For GNU atomics, require a trivially-copyable type. This is not part of
  2893. // the GNU atomics specification, but we enforce it for sanity.
  2894. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
  2895. << Ptr->getType() << Ptr->getSourceRange();
  2896. return ExprError();
  2897. }
  2898. switch (ValType.getObjCLifetime()) {
  2899. case Qualifiers::OCL_None:
  2900. case Qualifiers::OCL_ExplicitNone:
  2901. // okay
  2902. break;
  2903. case Qualifiers::OCL_Weak:
  2904. case Qualifiers::OCL_Strong:
  2905. case Qualifiers::OCL_Autoreleasing:
  2906. // FIXME: Can this happen? By this point, ValType should be known
  2907. // to be trivially copyable.
  2908. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  2909. << ValType << Ptr->getSourceRange();
  2910. return ExprError();
  2911. }
  2912. // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
  2913. // volatile-ness of the pointee-type inject itself into the result or the
  2914. // other operands. Similarly atomic_load can take a pointer to a const 'A'.
  2915. ValType.removeLocalVolatile();
  2916. ValType.removeLocalConst();
  2917. QualType ResultType = ValType;
  2918. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  2919. Form == Init)
  2920. ResultType = Context.VoidTy;
  2921. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  2922. ResultType = Context.BoolTy;
  2923. // The type of a parameter passed 'by value'. In the GNU atomics, such
  2924. // arguments are actually passed as pointers.
  2925. QualType ByValType = ValType; // 'CP'
  2926. if (!IsC11 && !IsN)
  2927. ByValType = Ptr->getType();
  2928. // The first argument --- the pointer --- has a fixed type; we
  2929. // deduce the types of the rest of the arguments accordingly. Walk
  2930. // the remaining arguments, converting them to the deduced value type.
  2931. for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
  2932. QualType Ty;
  2933. if (i < NumVals[Form] + 1) {
  2934. switch (i) {
  2935. case 1:
  2936. // The second argument is the non-atomic operand. For arithmetic, this
  2937. // is always passed by value, and for a compare_exchange it is always
  2938. // passed by address. For the rest, GNU uses by-address and C11 uses
  2939. // by-value.
  2940. assert(Form != Load);
  2941. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  2942. Ty = ValType;
  2943. else if (Form == Copy || Form == Xchg)
  2944. Ty = ByValType;
  2945. else if (Form == Arithmetic)
  2946. Ty = Context.getPointerDiffType();
  2947. else {
  2948. Expr *ValArg = TheCall->getArg(i);
  2949. // Treat this argument as _Nonnull as we want to show a warning if
  2950. // NULL is passed into it.
  2951. CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
  2952. LangAS AS = LangAS::Default;
  2953. // Keep address space of non-atomic pointer type.
  2954. if (const PointerType *PtrTy =
  2955. ValArg->getType()->getAs<PointerType>()) {
  2956. AS = PtrTy->getPointeeType().getAddressSpace();
  2957. }
  2958. Ty = Context.getPointerType(
  2959. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  2960. }
  2961. break;
  2962. case 2:
  2963. // The third argument to compare_exchange / GNU exchange is a
  2964. // (pointer to a) desired value.
  2965. Ty = ByValType;
  2966. break;
  2967. case 3:
  2968. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  2969. Ty = Context.BoolTy;
  2970. break;
  2971. }
  2972. } else {
  2973. // The order(s) and scope are always converted to int.
  2974. Ty = Context.IntTy;
  2975. }
  2976. InitializedEntity Entity =
  2977. InitializedEntity::InitializeParameter(Context, Ty, false);
  2978. ExprResult Arg = TheCall->getArg(i);
  2979. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  2980. if (Arg.isInvalid())
  2981. return true;
  2982. TheCall->setArg(i, Arg.get());
  2983. }
  2984. // Permute the arguments into a 'consistent' order.
  2985. SmallVector<Expr*, 5> SubExprs;
  2986. SubExprs.push_back(Ptr);
  2987. switch (Form) {
  2988. case Init:
  2989. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  2990. SubExprs.push_back(TheCall->getArg(1)); // Val1
  2991. break;
  2992. case Load:
  2993. SubExprs.push_back(TheCall->getArg(1)); // Order
  2994. break;
  2995. case LoadCopy:
  2996. case Copy:
  2997. case Arithmetic:
  2998. case Xchg:
  2999. SubExprs.push_back(TheCall->getArg(2)); // Order
  3000. SubExprs.push_back(TheCall->getArg(1)); // Val1
  3001. break;
  3002. case GNUXchg:
  3003. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  3004. SubExprs.push_back(TheCall->getArg(3)); // Order
  3005. SubExprs.push_back(TheCall->getArg(1)); // Val1
  3006. SubExprs.push_back(TheCall->getArg(2)); // Val2
  3007. break;
  3008. case C11CmpXchg:
  3009. SubExprs.push_back(TheCall->getArg(3)); // Order
  3010. SubExprs.push_back(TheCall->getArg(1)); // Val1
  3011. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  3012. SubExprs.push_back(TheCall->getArg(2)); // Val2
  3013. break;
  3014. case GNUCmpXchg:
  3015. SubExprs.push_back(TheCall->getArg(4)); // Order
  3016. SubExprs.push_back(TheCall->getArg(1)); // Val1
  3017. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  3018. SubExprs.push_back(TheCall->getArg(2)); // Val2
  3019. SubExprs.push_back(TheCall->getArg(3)); // Weak
  3020. break;
  3021. }
  3022. if (SubExprs.size() >= 2 && Form != Init) {
  3023. llvm::APSInt Result(32);
  3024. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  3025. !isValidOrderingForOp(Result.getSExtValue(), Op))
  3026. Diag(SubExprs[1]->getLocStart(),
  3027. diag::warn_atomic_op_has_invalid_memory_order)
  3028. << SubExprs[1]->getSourceRange();
  3029. }
  3030. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  3031. auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
  3032. llvm::APSInt Result(32);
  3033. if (Scope->isIntegerConstantExpr(Result, Context) &&
  3034. !ScopeModel->isValid(Result.getZExtValue())) {
  3035. Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
  3036. << Scope->getSourceRange();
  3037. }
  3038. SubExprs.push_back(Scope);
  3039. }
  3040. AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  3041. SubExprs, ResultType, Op,
  3042. TheCall->getRParenLoc());
  3043. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  3044. Op == AtomicExpr::AO__c11_atomic_store ||
  3045. Op == AtomicExpr::AO__opencl_atomic_load ||
  3046. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  3047. Context.AtomicUsesUnsupportedLibcall(AE))
  3048. Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
  3049. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  3050. Op == AtomicExpr::AO__opencl_atomic_load)
  3051. ? 0 : 1);
  3052. return AE;
  3053. }
  3054. /// checkBuiltinArgument - Given a call to a builtin function, perform
  3055. /// normal type-checking on the given argument, updating the call in
  3056. /// place. This is useful when a builtin function requires custom
  3057. /// type-checking for some of its arguments but not necessarily all of
  3058. /// them.
  3059. ///
  3060. /// Returns true on error.
  3061. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  3062. FunctionDecl *Fn = E->getDirectCallee();
  3063. assert(Fn && "builtin call without direct callee!");
  3064. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  3065. InitializedEntity Entity =
  3066. InitializedEntity::InitializeParameter(S.Context, Param);
  3067. ExprResult Arg = E->getArg(0);
  3068. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  3069. if (Arg.isInvalid())
  3070. return true;
  3071. E->setArg(ArgIndex, Arg.get());
  3072. return false;
  3073. }
  3074. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  3075. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  3076. /// type of its first argument. The main ActOnCallExpr routines have already
  3077. /// promoted the types of arguments because all of these calls are prototyped as
  3078. /// void(...).
  3079. ///
  3080. /// This function goes through and does final semantic checking for these
  3081. /// builtins,
  3082. ExprResult
  3083. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  3084. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  3085. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  3086. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  3087. // Ensure that we have at least one argument to do type inference from.
  3088. if (TheCall->getNumArgs() < 1) {
  3089. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  3090. << 0 << 1 << TheCall->getNumArgs()
  3091. << TheCall->getCallee()->getSourceRange();
  3092. return ExprError();
  3093. }
  3094. // Inspect the first argument of the atomic builtin. This should always be
  3095. // a pointer type, whose element is an integral scalar or pointer type.
  3096. // Because it is a pointer type, we don't have to worry about any implicit
  3097. // casts here.
  3098. // FIXME: We don't allow floating point scalars as input.
  3099. Expr *FirstArg = TheCall->getArg(0);
  3100. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  3101. if (FirstArgResult.isInvalid())
  3102. return ExprError();
  3103. FirstArg = FirstArgResult.get();
  3104. TheCall->setArg(0, FirstArg);
  3105. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  3106. if (!pointerType) {
  3107. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  3108. << FirstArg->getType() << FirstArg->getSourceRange();
  3109. return ExprError();
  3110. }
  3111. QualType ValType = pointerType->getPointeeType();
  3112. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  3113. !ValType->isBlockPointerType()) {
  3114. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  3115. << FirstArg->getType() << FirstArg->getSourceRange();
  3116. return ExprError();
  3117. }
  3118. switch (ValType.getObjCLifetime()) {
  3119. case Qualifiers::OCL_None:
  3120. case Qualifiers::OCL_ExplicitNone:
  3121. // okay
  3122. break;
  3123. case Qualifiers::OCL_Weak:
  3124. case Qualifiers::OCL_Strong:
  3125. case Qualifiers::OCL_Autoreleasing:
  3126. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  3127. << ValType << FirstArg->getSourceRange();
  3128. return ExprError();
  3129. }
  3130. // Strip any qualifiers off ValType.
  3131. ValType = ValType.getUnqualifiedType();
  3132. // The majority of builtins return a value, but a few have special return
  3133. // types, so allow them to override appropriately below.
  3134. QualType ResultType = ValType;
  3135. // We need to figure out which concrete builtin this maps onto. For example,
  3136. // __sync_fetch_and_add with a 2 byte object turns into
  3137. // __sync_fetch_and_add_2.
  3138. #define BUILTIN_ROW(x) \
  3139. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  3140. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  3141. static const unsigned BuiltinIndices[][5] = {
  3142. BUILTIN_ROW(__sync_fetch_and_add),
  3143. BUILTIN_ROW(__sync_fetch_and_sub),
  3144. BUILTIN_ROW(__sync_fetch_and_or),
  3145. BUILTIN_ROW(__sync_fetch_and_and),
  3146. BUILTIN_ROW(__sync_fetch_and_xor),
  3147. BUILTIN_ROW(__sync_fetch_and_nand),
  3148. BUILTIN_ROW(__sync_add_and_fetch),
  3149. BUILTIN_ROW(__sync_sub_and_fetch),
  3150. BUILTIN_ROW(__sync_and_and_fetch),
  3151. BUILTIN_ROW(__sync_or_and_fetch),
  3152. BUILTIN_ROW(__sync_xor_and_fetch),
  3153. BUILTIN_ROW(__sync_nand_and_fetch),
  3154. BUILTIN_ROW(__sync_val_compare_and_swap),
  3155. BUILTIN_ROW(__sync_bool_compare_and_swap),
  3156. BUILTIN_ROW(__sync_lock_test_and_set),
  3157. BUILTIN_ROW(__sync_lock_release),
  3158. BUILTIN_ROW(__sync_swap)
  3159. };
  3160. #undef BUILTIN_ROW
  3161. // Determine the index of the size.
  3162. unsigned SizeIndex;
  3163. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  3164. case 1: SizeIndex = 0; break;
  3165. case 2: SizeIndex = 1; break;
  3166. case 4: SizeIndex = 2; break;
  3167. case 8: SizeIndex = 3; break;
  3168. case 16: SizeIndex = 4; break;
  3169. default:
  3170. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  3171. << FirstArg->getType() << FirstArg->getSourceRange();
  3172. return ExprError();
  3173. }
  3174. // Each of these builtins has one pointer argument, followed by some number of
  3175. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  3176. // that we ignore. Find out which row of BuiltinIndices to read from as well
  3177. // as the number of fixed args.
  3178. unsigned BuiltinID = FDecl->getBuiltinID();
  3179. unsigned BuiltinIndex, NumFixed = 1;
  3180. bool WarnAboutSemanticsChange = false;
  3181. switch (BuiltinID) {
  3182. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  3183. case Builtin::BI__sync_fetch_and_add:
  3184. case Builtin::BI__sync_fetch_and_add_1:
  3185. case Builtin::BI__sync_fetch_and_add_2:
  3186. case Builtin::BI__sync_fetch_and_add_4:
  3187. case Builtin::BI__sync_fetch_and_add_8:
  3188. case Builtin::BI__sync_fetch_and_add_16:
  3189. BuiltinIndex = 0;
  3190. break;
  3191. case Builtin::BI__sync_fetch_and_sub:
  3192. case Builtin::BI__sync_fetch_and_sub_1:
  3193. case Builtin::BI__sync_fetch_and_sub_2:
  3194. case Builtin::BI__sync_fetch_and_sub_4:
  3195. case Builtin::BI__sync_fetch_and_sub_8:
  3196. case Builtin::BI__sync_fetch_and_sub_16:
  3197. BuiltinIndex = 1;
  3198. break;
  3199. case Builtin::BI__sync_fetch_and_or:
  3200. case Builtin::BI__sync_fetch_and_or_1:
  3201. case Builtin::BI__sync_fetch_and_or_2:
  3202. case Builtin::BI__sync_fetch_and_or_4:
  3203. case Builtin::BI__sync_fetch_and_or_8:
  3204. case Builtin::BI__sync_fetch_and_or_16:
  3205. BuiltinIndex = 2;
  3206. break;
  3207. case Builtin::BI__sync_fetch_and_and:
  3208. case Builtin::BI__sync_fetch_and_and_1:
  3209. case Builtin::BI__sync_fetch_and_and_2:
  3210. case Builtin::BI__sync_fetch_and_and_4:
  3211. case Builtin::BI__sync_fetch_and_and_8:
  3212. case Builtin::BI__sync_fetch_and_and_16:
  3213. BuiltinIndex = 3;
  3214. break;
  3215. case Builtin::BI__sync_fetch_and_xor:
  3216. case Builtin::BI__sync_fetch_and_xor_1:
  3217. case Builtin::BI__sync_fetch_and_xor_2:
  3218. case Builtin::BI__sync_fetch_and_xor_4:
  3219. case Builtin::BI__sync_fetch_and_xor_8:
  3220. case Builtin::BI__sync_fetch_and_xor_16:
  3221. BuiltinIndex = 4;
  3222. break;
  3223. case Builtin::BI__sync_fetch_and_nand:
  3224. case Builtin::BI__sync_fetch_and_nand_1:
  3225. case Builtin::BI__sync_fetch_and_nand_2:
  3226. case Builtin::BI__sync_fetch_and_nand_4:
  3227. case Builtin::BI__sync_fetch_and_nand_8:
  3228. case Builtin::BI__sync_fetch_and_nand_16:
  3229. BuiltinIndex = 5;
  3230. WarnAboutSemanticsChange = true;
  3231. break;
  3232. case Builtin::BI__sync_add_and_fetch:
  3233. case Builtin::BI__sync_add_and_fetch_1:
  3234. case Builtin::BI__sync_add_and_fetch_2:
  3235. case Builtin::BI__sync_add_and_fetch_4:
  3236. case Builtin::BI__sync_add_and_fetch_8:
  3237. case Builtin::BI__sync_add_and_fetch_16:
  3238. BuiltinIndex = 6;
  3239. break;
  3240. case Builtin::BI__sync_sub_and_fetch:
  3241. case Builtin::BI__sync_sub_and_fetch_1:
  3242. case Builtin::BI__sync_sub_and_fetch_2:
  3243. case Builtin::BI__sync_sub_and_fetch_4:
  3244. case Builtin::BI__sync_sub_and_fetch_8:
  3245. case Builtin::BI__sync_sub_and_fetch_16:
  3246. BuiltinIndex = 7;
  3247. break;
  3248. case Builtin::BI__sync_and_and_fetch:
  3249. case Builtin::BI__sync_and_and_fetch_1:
  3250. case Builtin::BI__sync_and_and_fetch_2:
  3251. case Builtin::BI__sync_and_and_fetch_4:
  3252. case Builtin::BI__sync_and_and_fetch_8:
  3253. case Builtin::BI__sync_and_and_fetch_16:
  3254. BuiltinIndex = 8;
  3255. break;
  3256. case Builtin::BI__sync_or_and_fetch:
  3257. case Builtin::BI__sync_or_and_fetch_1:
  3258. case Builtin::BI__sync_or_and_fetch_2:
  3259. case Builtin::BI__sync_or_and_fetch_4:
  3260. case Builtin::BI__sync_or_and_fetch_8:
  3261. case Builtin::BI__sync_or_and_fetch_16:
  3262. BuiltinIndex = 9;
  3263. break;
  3264. case Builtin::BI__sync_xor_and_fetch:
  3265. case Builtin::BI__sync_xor_and_fetch_1:
  3266. case Builtin::BI__sync_xor_and_fetch_2:
  3267. case Builtin::BI__sync_xor_and_fetch_4:
  3268. case Builtin::BI__sync_xor_and_fetch_8:
  3269. case Builtin::BI__sync_xor_and_fetch_16:
  3270. BuiltinIndex = 10;
  3271. break;
  3272. case Builtin::BI__sync_nand_and_fetch:
  3273. case Builtin::BI__sync_nand_and_fetch_1:
  3274. case Builtin::BI__sync_nand_and_fetch_2:
  3275. case Builtin::BI__sync_nand_and_fetch_4:
  3276. case Builtin::BI__sync_nand_and_fetch_8:
  3277. case Builtin::BI__sync_nand_and_fetch_16:
  3278. BuiltinIndex = 11;
  3279. WarnAboutSemanticsChange = true;
  3280. break;
  3281. case Builtin::BI__sync_val_compare_and_swap:
  3282. case Builtin::BI__sync_val_compare_and_swap_1:
  3283. case Builtin::BI__sync_val_compare_and_swap_2:
  3284. case Builtin::BI__sync_val_compare_and_swap_4:
  3285. case Builtin::BI__sync_val_compare_and_swap_8:
  3286. case Builtin::BI__sync_val_compare_and_swap_16:
  3287. BuiltinIndex = 12;
  3288. NumFixed = 2;
  3289. break;
  3290. case Builtin::BI__sync_bool_compare_and_swap:
  3291. case Builtin::BI__sync_bool_compare_and_swap_1:
  3292. case Builtin::BI__sync_bool_compare_and_swap_2:
  3293. case Builtin::BI__sync_bool_compare_and_swap_4:
  3294. case Builtin::BI__sync_bool_compare_and_swap_8:
  3295. case Builtin::BI__sync_bool_compare_and_swap_16:
  3296. BuiltinIndex = 13;
  3297. NumFixed = 2;
  3298. ResultType = Context.BoolTy;
  3299. break;
  3300. case Builtin::BI__sync_lock_test_and_set:
  3301. case Builtin::BI__sync_lock_test_and_set_1:
  3302. case Builtin::BI__sync_lock_test_and_set_2:
  3303. case Builtin::BI__sync_lock_test_and_set_4:
  3304. case Builtin::BI__sync_lock_test_and_set_8:
  3305. case Builtin::BI__sync_lock_test_and_set_16:
  3306. BuiltinIndex = 14;
  3307. break;
  3308. case Builtin::BI__sync_lock_release:
  3309. case Builtin::BI__sync_lock_release_1:
  3310. case Builtin::BI__sync_lock_release_2:
  3311. case Builtin::BI__sync_lock_release_4:
  3312. case Builtin::BI__sync_lock_release_8:
  3313. case Builtin::BI__sync_lock_release_16:
  3314. BuiltinIndex = 15;
  3315. NumFixed = 0;
  3316. ResultType = Context.VoidTy;
  3317. break;
  3318. case Builtin::BI__sync_swap:
  3319. case Builtin::BI__sync_swap_1:
  3320. case Builtin::BI__sync_swap_2:
  3321. case Builtin::BI__sync_swap_4:
  3322. case Builtin::BI__sync_swap_8:
  3323. case Builtin::BI__sync_swap_16:
  3324. BuiltinIndex = 16;
  3325. break;
  3326. }
  3327. // Now that we know how many fixed arguments we expect, first check that we
  3328. // have at least that many.
  3329. if (TheCall->getNumArgs() < 1+NumFixed) {
  3330. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  3331. << 0 << 1+NumFixed << TheCall->getNumArgs()
  3332. << TheCall->getCallee()->getSourceRange();
  3333. return ExprError();
  3334. }
  3335. if (WarnAboutSemanticsChange) {
  3336. Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
  3337. << TheCall->getCallee()->getSourceRange();
  3338. }
  3339. // Get the decl for the concrete builtin from this, we can tell what the
  3340. // concrete integer type we should convert to is.
  3341. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  3342. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  3343. FunctionDecl *NewBuiltinDecl;
  3344. if (NewBuiltinID == BuiltinID)
  3345. NewBuiltinDecl = FDecl;
  3346. else {
  3347. // Perform builtin lookup to avoid redeclaring it.
  3348. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  3349. LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
  3350. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  3351. assert(Res.getFoundDecl());
  3352. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  3353. if (!NewBuiltinDecl)
  3354. return ExprError();
  3355. }
  3356. // The first argument --- the pointer --- has a fixed type; we
  3357. // deduce the types of the rest of the arguments accordingly. Walk
  3358. // the remaining arguments, converting them to the deduced value type.
  3359. for (unsigned i = 0; i != NumFixed; ++i) {
  3360. ExprResult Arg = TheCall->getArg(i+1);
  3361. // GCC does an implicit conversion to the pointer or integer ValType. This
  3362. // can fail in some cases (1i -> int**), check for this error case now.
  3363. // Initialize the argument.
  3364. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  3365. ValType, /*consume*/ false);
  3366. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  3367. if (Arg.isInvalid())
  3368. return ExprError();
  3369. // Okay, we have something that *can* be converted to the right type. Check
  3370. // to see if there is a potentially weird extension going on here. This can
  3371. // happen when you do an atomic operation on something like an char* and
  3372. // pass in 42. The 42 gets converted to char. This is even more strange
  3373. // for things like 45.123 -> char, etc.
  3374. // FIXME: Do this check.
  3375. TheCall->setArg(i+1, Arg.get());
  3376. }
  3377. ASTContext& Context = this->getASTContext();
  3378. // Create a new DeclRefExpr to refer to the new decl.
  3379. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  3380. Context,
  3381. DRE->getQualifierLoc(),
  3382. SourceLocation(),
  3383. NewBuiltinDecl,
  3384. /*enclosing*/ false,
  3385. DRE->getLocation(),
  3386. Context.BuiltinFnTy,
  3387. DRE->getValueKind());
  3388. // Set the callee in the CallExpr.
  3389. // FIXME: This loses syntactic information.
  3390. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  3391. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  3392. CK_BuiltinFnToFnPtr);
  3393. TheCall->setCallee(PromotedCall.get());
  3394. // Change the result type of the call to match the original value type. This
  3395. // is arbitrary, but the codegen for these builtins ins design to handle it
  3396. // gracefully.
  3397. TheCall->setType(ResultType);
  3398. return TheCallResult;
  3399. }
  3400. /// SemaBuiltinNontemporalOverloaded - We have a call to
  3401. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  3402. /// overloaded function based on the pointer type of its last argument.
  3403. ///
  3404. /// This function goes through and does final semantic checking for these
  3405. /// builtins.
  3406. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  3407. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  3408. DeclRefExpr *DRE =
  3409. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  3410. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  3411. unsigned BuiltinID = FDecl->getBuiltinID();
  3412. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  3413. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  3414. "Unexpected nontemporal load/store builtin!");
  3415. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  3416. unsigned numArgs = isStore ? 2 : 1;
  3417. // Ensure that we have the proper number of arguments.
  3418. if (checkArgCount(*this, TheCall, numArgs))
  3419. return ExprError();
  3420. // Inspect the last argument of the nontemporal builtin. This should always
  3421. // be a pointer type, from which we imply the type of the memory access.
  3422. // Because it is a pointer type, we don't have to worry about any implicit
  3423. // casts here.
  3424. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  3425. ExprResult PointerArgResult =
  3426. DefaultFunctionArrayLvalueConversion(PointerArg);
  3427. if (PointerArgResult.isInvalid())
  3428. return ExprError();
  3429. PointerArg = PointerArgResult.get();
  3430. TheCall->setArg(numArgs - 1, PointerArg);
  3431. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  3432. if (!pointerType) {
  3433. Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
  3434. << PointerArg->getType() << PointerArg->getSourceRange();
  3435. return ExprError();
  3436. }
  3437. QualType ValType = pointerType->getPointeeType();
  3438. // Strip any qualifiers off ValType.
  3439. ValType = ValType.getUnqualifiedType();
  3440. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  3441. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  3442. !ValType->isVectorType()) {
  3443. Diag(DRE->getLocStart(),
  3444. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  3445. << PointerArg->getType() << PointerArg->getSourceRange();
  3446. return ExprError();
  3447. }
  3448. if (!isStore) {
  3449. TheCall->setType(ValType);
  3450. return TheCallResult;
  3451. }
  3452. ExprResult ValArg = TheCall->getArg(0);
  3453. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  3454. Context, ValType, /*consume*/ false);
  3455. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  3456. if (ValArg.isInvalid())
  3457. return ExprError();
  3458. TheCall->setArg(0, ValArg.get());
  3459. TheCall->setType(Context.VoidTy);
  3460. return TheCallResult;
  3461. }
  3462. /// CheckObjCString - Checks that the argument to the builtin
  3463. /// CFString constructor is correct
  3464. /// Note: It might also make sense to do the UTF-16 conversion here (would
  3465. /// simplify the backend).
  3466. bool Sema::CheckObjCString(Expr *Arg) {
  3467. Arg = Arg->IgnoreParenCasts();
  3468. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  3469. if (!Literal || !Literal->isAscii()) {
  3470. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  3471. << Arg->getSourceRange();
  3472. return true;
  3473. }
  3474. if (Literal->containsNonAsciiOrNull()) {
  3475. StringRef String = Literal->getString();
  3476. unsigned NumBytes = String.size();
  3477. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  3478. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  3479. llvm::UTF16 *ToPtr = &ToBuf[0];
  3480. llvm::ConversionResult Result =
  3481. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  3482. ToPtr + NumBytes, llvm::strictConversion);
  3483. // Check for conversion failure.
  3484. if (Result != llvm::conversionOK)
  3485. Diag(Arg->getLocStart(),
  3486. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  3487. }
  3488. return false;
  3489. }
  3490. /// CheckObjCString - Checks that the format string argument to the os_log()
  3491. /// and os_trace() functions is correct, and converts it to const char *.
  3492. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  3493. Arg = Arg->IgnoreParenCasts();
  3494. auto *Literal = dyn_cast<StringLiteral>(Arg);
  3495. if (!Literal) {
  3496. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  3497. Literal = ObjcLiteral->getString();
  3498. }
  3499. }
  3500. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  3501. return ExprError(
  3502. Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
  3503. << Arg->getSourceRange());
  3504. }
  3505. ExprResult Result(Literal);
  3506. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  3507. InitializedEntity Entity =
  3508. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  3509. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  3510. return Result;
  3511. }
  3512. /// Check that the user is calling the appropriate va_start builtin for the
  3513. /// target and calling convention.
  3514. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  3515. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  3516. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  3517. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  3518. bool IsWindows = TT.isOSWindows();
  3519. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  3520. if (IsX64 || IsAArch64) {
  3521. CallingConv CC = CC_C;
  3522. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  3523. CC = FD->getType()->getAs<FunctionType>()->getCallConv();
  3524. if (IsMSVAStart) {
  3525. // Don't allow this in System V ABI functions.
  3526. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  3527. return S.Diag(Fn->getLocStart(),
  3528. diag::err_ms_va_start_used_in_sysv_function);
  3529. } else {
  3530. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  3531. // On x64 Windows, don't allow this in System V ABI functions.
  3532. // (Yes, that means there's no corresponding way to support variadic
  3533. // System V ABI functions on Windows.)
  3534. if ((IsWindows && CC == CC_X86_64SysV) ||
  3535. (!IsWindows && CC == CC_Win64))
  3536. return S.Diag(Fn->getLocStart(),
  3537. diag::err_va_start_used_in_wrong_abi_function)
  3538. << !IsWindows;
  3539. }
  3540. return false;
  3541. }
  3542. if (IsMSVAStart)
  3543. return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
  3544. return false;
  3545. }
  3546. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  3547. ParmVarDecl **LastParam = nullptr) {
  3548. // Determine whether the current function, block, or obj-c method is variadic
  3549. // and get its parameter list.
  3550. bool IsVariadic = false;
  3551. ArrayRef<ParmVarDecl *> Params;
  3552. DeclContext *Caller = S.CurContext;
  3553. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  3554. IsVariadic = Block->isVariadic();
  3555. Params = Block->parameters();
  3556. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  3557. IsVariadic = FD->isVariadic();
  3558. Params = FD->parameters();
  3559. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  3560. IsVariadic = MD->isVariadic();
  3561. // FIXME: This isn't correct for methods (results in bogus warning).
  3562. Params = MD->parameters();
  3563. } else if (isa<CapturedDecl>(Caller)) {
  3564. // We don't support va_start in a CapturedDecl.
  3565. S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
  3566. return true;
  3567. } else {
  3568. // This must be some other declcontext that parses exprs.
  3569. S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
  3570. return true;
  3571. }
  3572. if (!IsVariadic) {
  3573. S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
  3574. return true;
  3575. }
  3576. if (LastParam)
  3577. *LastParam = Params.empty() ? nullptr : Params.back();
  3578. return false;
  3579. }
  3580. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  3581. /// for validity. Emit an error and return true on failure; return false
  3582. /// on success.
  3583. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  3584. Expr *Fn = TheCall->getCallee();
  3585. if (checkVAStartABI(*this, BuiltinID, Fn))
  3586. return true;
  3587. if (TheCall->getNumArgs() > 2) {
  3588. Diag(TheCall->getArg(2)->getLocStart(),
  3589. diag::err_typecheck_call_too_many_args)
  3590. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  3591. << Fn->getSourceRange()
  3592. << SourceRange(TheCall->getArg(2)->getLocStart(),
  3593. (*(TheCall->arg_end()-1))->getLocEnd());
  3594. return true;
  3595. }
  3596. if (TheCall->getNumArgs() < 2) {
  3597. return Diag(TheCall->getLocEnd(),
  3598. diag::err_typecheck_call_too_few_args_at_least)
  3599. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  3600. }
  3601. // Type-check the first argument normally.
  3602. if (checkBuiltinArgument(*this, TheCall, 0))
  3603. return true;
  3604. // Check that the current function is variadic, and get its last parameter.
  3605. ParmVarDecl *LastParam;
  3606. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  3607. return true;
  3608. // Verify that the second argument to the builtin is the last argument of the
  3609. // current function or method.
  3610. bool SecondArgIsLastNamedArgument = false;
  3611. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  3612. // These are valid if SecondArgIsLastNamedArgument is false after the next
  3613. // block.
  3614. QualType Type;
  3615. SourceLocation ParamLoc;
  3616. bool IsCRegister = false;
  3617. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  3618. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  3619. SecondArgIsLastNamedArgument = PV == LastParam;
  3620. Type = PV->getType();
  3621. ParamLoc = PV->getLocation();
  3622. IsCRegister =
  3623. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  3624. }
  3625. }
  3626. if (!SecondArgIsLastNamedArgument)
  3627. Diag(TheCall->getArg(1)->getLocStart(),
  3628. diag::warn_second_arg_of_va_start_not_last_named_param);
  3629. else if (IsCRegister || Type->isReferenceType() ||
  3630. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  3631. // Promotable integers are UB, but enumerations need a bit of
  3632. // extra checking to see what their promotable type actually is.
  3633. if (!Type->isPromotableIntegerType())
  3634. return false;
  3635. if (!Type->isEnumeralType())
  3636. return true;
  3637. const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
  3638. return !(ED &&
  3639. Context.typesAreCompatible(ED->getPromotionType(), Type));
  3640. }()) {
  3641. unsigned Reason = 0;
  3642. if (Type->isReferenceType()) Reason = 1;
  3643. else if (IsCRegister) Reason = 2;
  3644. Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
  3645. Diag(ParamLoc, diag::note_parameter_type) << Type;
  3646. }
  3647. TheCall->setType(Context.VoidTy);
  3648. return false;
  3649. }
  3650. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  3651. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  3652. // const char *named_addr);
  3653. Expr *Func = Call->getCallee();
  3654. if (Call->getNumArgs() < 3)
  3655. return Diag(Call->getLocEnd(),
  3656. diag::err_typecheck_call_too_few_args_at_least)
  3657. << 0 /*function call*/ << 3 << Call->getNumArgs();
  3658. // Type-check the first argument normally.
  3659. if (checkBuiltinArgument(*this, Call, 0))
  3660. return true;
  3661. // Check that the current function is variadic.
  3662. if (checkVAStartIsInVariadicFunction(*this, Func))
  3663. return true;
  3664. // __va_start on Windows does not validate the parameter qualifiers
  3665. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  3666. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  3667. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  3668. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  3669. const QualType &ConstCharPtrTy =
  3670. Context.getPointerType(Context.CharTy.withConst());
  3671. if (!Arg1Ty->isPointerType() ||
  3672. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  3673. Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
  3674. << Arg1->getType() << ConstCharPtrTy
  3675. << 1 /* different class */
  3676. << 0 /* qualifier difference */
  3677. << 3 /* parameter mismatch */
  3678. << 2 << Arg1->getType() << ConstCharPtrTy;
  3679. const QualType SizeTy = Context.getSizeType();
  3680. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  3681. Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
  3682. << Arg2->getType() << SizeTy
  3683. << 1 /* different class */
  3684. << 0 /* qualifier difference */
  3685. << 3 /* parameter mismatch */
  3686. << 3 << Arg2->getType() << SizeTy;
  3687. return false;
  3688. }
  3689. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  3690. /// friends. This is declared to take (...), so we have to check everything.
  3691. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  3692. if (TheCall->getNumArgs() < 2)
  3693. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  3694. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  3695. if (TheCall->getNumArgs() > 2)
  3696. return Diag(TheCall->getArg(2)->getLocStart(),
  3697. diag::err_typecheck_call_too_many_args)
  3698. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  3699. << SourceRange(TheCall->getArg(2)->getLocStart(),
  3700. (*(TheCall->arg_end()-1))->getLocEnd());
  3701. ExprResult OrigArg0 = TheCall->getArg(0);
  3702. ExprResult OrigArg1 = TheCall->getArg(1);
  3703. // Do standard promotions between the two arguments, returning their common
  3704. // type.
  3705. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  3706. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  3707. return true;
  3708. // Make sure any conversions are pushed back into the call; this is
  3709. // type safe since unordered compare builtins are declared as "_Bool
  3710. // foo(...)".
  3711. TheCall->setArg(0, OrigArg0.get());
  3712. TheCall->setArg(1, OrigArg1.get());
  3713. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  3714. return false;
  3715. // If the common type isn't a real floating type, then the arguments were
  3716. // invalid for this operation.
  3717. if (Res.isNull() || !Res->isRealFloatingType())
  3718. return Diag(OrigArg0.get()->getLocStart(),
  3719. diag::err_typecheck_call_invalid_ordered_compare)
  3720. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  3721. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  3722. return false;
  3723. }
  3724. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  3725. /// __builtin_isnan and friends. This is declared to take (...), so we have
  3726. /// to check everything. We expect the last argument to be a floating point
  3727. /// value.
  3728. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  3729. if (TheCall->getNumArgs() < NumArgs)
  3730. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  3731. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  3732. if (TheCall->getNumArgs() > NumArgs)
  3733. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  3734. diag::err_typecheck_call_too_many_args)
  3735. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  3736. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  3737. (*(TheCall->arg_end()-1))->getLocEnd());
  3738. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  3739. if (OrigArg->isTypeDependent())
  3740. return false;
  3741. // This operation requires a non-_Complex floating-point number.
  3742. if (!OrigArg->getType()->isRealFloatingType())
  3743. return Diag(OrigArg->getLocStart(),
  3744. diag::err_typecheck_call_invalid_unary_fp)
  3745. << OrigArg->getType() << OrigArg->getSourceRange();
  3746. // If this is an implicit conversion from float -> float or double, remove it.
  3747. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  3748. // Only remove standard FloatCasts, leaving other casts inplace
  3749. if (Cast->getCastKind() == CK_FloatingCast) {
  3750. Expr *CastArg = Cast->getSubExpr();
  3751. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  3752. assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  3753. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
  3754. "promotion from float to either float or double is the only expected cast here");
  3755. Cast->setSubExpr(nullptr);
  3756. TheCall->setArg(NumArgs-1, CastArg);
  3757. }
  3758. }
  3759. }
  3760. return false;
  3761. }
  3762. // Customized Sema Checking for VSX builtins that have the following signature:
  3763. // vector [...] builtinName(vector [...], vector [...], const int);
  3764. // Which takes the same type of vectors (any legal vector type) for the first
  3765. // two arguments and takes compile time constant for the third argument.
  3766. // Example builtins are :
  3767. // vector double vec_xxpermdi(vector double, vector double, int);
  3768. // vector short vec_xxsldwi(vector short, vector short, int);
  3769. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  3770. unsigned ExpectedNumArgs = 3;
  3771. if (TheCall->getNumArgs() < ExpectedNumArgs)
  3772. return Diag(TheCall->getLocEnd(),
  3773. diag::err_typecheck_call_too_few_args_at_least)
  3774. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  3775. << TheCall->getSourceRange();
  3776. if (TheCall->getNumArgs() > ExpectedNumArgs)
  3777. return Diag(TheCall->getLocEnd(),
  3778. diag::err_typecheck_call_too_many_args_at_most)
  3779. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  3780. << TheCall->getSourceRange();
  3781. // Check the third argument is a compile time constant
  3782. llvm::APSInt Value;
  3783. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  3784. return Diag(TheCall->getLocStart(),
  3785. diag::err_vsx_builtin_nonconstant_argument)
  3786. << 3 /* argument index */ << TheCall->getDirectCallee()
  3787. << SourceRange(TheCall->getArg(2)->getLocStart(),
  3788. TheCall->getArg(2)->getLocEnd());
  3789. QualType Arg1Ty = TheCall->getArg(0)->getType();
  3790. QualType Arg2Ty = TheCall->getArg(1)->getType();
  3791. // Check the type of argument 1 and argument 2 are vectors.
  3792. SourceLocation BuiltinLoc = TheCall->getLocStart();
  3793. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  3794. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  3795. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  3796. << TheCall->getDirectCallee()
  3797. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3798. TheCall->getArg(1)->getLocEnd());
  3799. }
  3800. // Check the first two arguments are the same type.
  3801. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  3802. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  3803. << TheCall->getDirectCallee()
  3804. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3805. TheCall->getArg(1)->getLocEnd());
  3806. }
  3807. // When default clang type checking is turned off and the customized type
  3808. // checking is used, the returning type of the function must be explicitly
  3809. // set. Otherwise it is _Bool by default.
  3810. TheCall->setType(Arg1Ty);
  3811. return false;
  3812. }
  3813. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  3814. // This is declared to take (...), so we have to check everything.
  3815. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  3816. if (TheCall->getNumArgs() < 2)
  3817. return ExprError(Diag(TheCall->getLocEnd(),
  3818. diag::err_typecheck_call_too_few_args_at_least)
  3819. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  3820. << TheCall->getSourceRange());
  3821. // Determine which of the following types of shufflevector we're checking:
  3822. // 1) unary, vector mask: (lhs, mask)
  3823. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  3824. QualType resType = TheCall->getArg(0)->getType();
  3825. unsigned numElements = 0;
  3826. if (!TheCall->getArg(0)->isTypeDependent() &&
  3827. !TheCall->getArg(1)->isTypeDependent()) {
  3828. QualType LHSType = TheCall->getArg(0)->getType();
  3829. QualType RHSType = TheCall->getArg(1)->getType();
  3830. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  3831. return ExprError(Diag(TheCall->getLocStart(),
  3832. diag::err_vec_builtin_non_vector)
  3833. << TheCall->getDirectCallee()
  3834. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3835. TheCall->getArg(1)->getLocEnd()));
  3836. numElements = LHSType->getAs<VectorType>()->getNumElements();
  3837. unsigned numResElements = TheCall->getNumArgs() - 2;
  3838. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  3839. // with mask. If so, verify that RHS is an integer vector type with the
  3840. // same number of elts as lhs.
  3841. if (TheCall->getNumArgs() == 2) {
  3842. if (!RHSType->hasIntegerRepresentation() ||
  3843. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  3844. return ExprError(Diag(TheCall->getLocStart(),
  3845. diag::err_vec_builtin_incompatible_vector)
  3846. << TheCall->getDirectCallee()
  3847. << SourceRange(TheCall->getArg(1)->getLocStart(),
  3848. TheCall->getArg(1)->getLocEnd()));
  3849. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  3850. return ExprError(Diag(TheCall->getLocStart(),
  3851. diag::err_vec_builtin_incompatible_vector)
  3852. << TheCall->getDirectCallee()
  3853. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3854. TheCall->getArg(1)->getLocEnd()));
  3855. } else if (numElements != numResElements) {
  3856. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  3857. resType = Context.getVectorType(eltType, numResElements,
  3858. VectorType::GenericVector);
  3859. }
  3860. }
  3861. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  3862. if (TheCall->getArg(i)->isTypeDependent() ||
  3863. TheCall->getArg(i)->isValueDependent())
  3864. continue;
  3865. llvm::APSInt Result(32);
  3866. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  3867. return ExprError(Diag(TheCall->getLocStart(),
  3868. diag::err_shufflevector_nonconstant_argument)
  3869. << TheCall->getArg(i)->getSourceRange());
  3870. // Allow -1 which will be translated to undef in the IR.
  3871. if (Result.isSigned() && Result.isAllOnesValue())
  3872. continue;
  3873. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  3874. return ExprError(Diag(TheCall->getLocStart(),
  3875. diag::err_shufflevector_argument_too_large)
  3876. << TheCall->getArg(i)->getSourceRange());
  3877. }
  3878. SmallVector<Expr*, 32> exprs;
  3879. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  3880. exprs.push_back(TheCall->getArg(i));
  3881. TheCall->setArg(i, nullptr);
  3882. }
  3883. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  3884. TheCall->getCallee()->getLocStart(),
  3885. TheCall->getRParenLoc());
  3886. }
  3887. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  3888. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  3889. SourceLocation BuiltinLoc,
  3890. SourceLocation RParenLoc) {
  3891. ExprValueKind VK = VK_RValue;
  3892. ExprObjectKind OK = OK_Ordinary;
  3893. QualType DstTy = TInfo->getType();
  3894. QualType SrcTy = E->getType();
  3895. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  3896. return ExprError(Diag(BuiltinLoc,
  3897. diag::err_convertvector_non_vector)
  3898. << E->getSourceRange());
  3899. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  3900. return ExprError(Diag(BuiltinLoc,
  3901. diag::err_convertvector_non_vector_type));
  3902. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  3903. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  3904. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  3905. if (SrcElts != DstElts)
  3906. return ExprError(Diag(BuiltinLoc,
  3907. diag::err_convertvector_incompatible_vector)
  3908. << E->getSourceRange());
  3909. }
  3910. return new (Context)
  3911. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  3912. }
  3913. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  3914. // This is declared to take (const void*, ...) and can take two
  3915. // optional constant int args.
  3916. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  3917. unsigned NumArgs = TheCall->getNumArgs();
  3918. if (NumArgs > 3)
  3919. return Diag(TheCall->getLocEnd(),
  3920. diag::err_typecheck_call_too_many_args_at_most)
  3921. << 0 /*function call*/ << 3 << NumArgs
  3922. << TheCall->getSourceRange();
  3923. // Argument 0 is checked for us and the remaining arguments must be
  3924. // constant integers.
  3925. for (unsigned i = 1; i != NumArgs; ++i)
  3926. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  3927. return true;
  3928. return false;
  3929. }
  3930. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  3931. // __assume does not evaluate its arguments, and should warn if its argument
  3932. // has side effects.
  3933. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  3934. Expr *Arg = TheCall->getArg(0);
  3935. if (Arg->isInstantiationDependent()) return false;
  3936. if (Arg->HasSideEffects(Context))
  3937. Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
  3938. << Arg->getSourceRange()
  3939. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  3940. return false;
  3941. }
  3942. /// Handle __builtin_alloca_with_align. This is declared
  3943. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  3944. /// than 8.
  3945. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  3946. // The alignment must be a constant integer.
  3947. Expr *Arg = TheCall->getArg(1);
  3948. // We can't check the value of a dependent argument.
  3949. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  3950. if (const auto *UE =
  3951. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  3952. if (UE->getKind() == UETT_AlignOf)
  3953. Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
  3954. << Arg->getSourceRange();
  3955. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  3956. if (!Result.isPowerOf2())
  3957. return Diag(TheCall->getLocStart(),
  3958. diag::err_alignment_not_power_of_two)
  3959. << Arg->getSourceRange();
  3960. if (Result < Context.getCharWidth())
  3961. return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
  3962. << (unsigned)Context.getCharWidth()
  3963. << Arg->getSourceRange();
  3964. if (Result > std::numeric_limits<int32_t>::max())
  3965. return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
  3966. << std::numeric_limits<int32_t>::max()
  3967. << Arg->getSourceRange();
  3968. }
  3969. return false;
  3970. }
  3971. /// Handle __builtin_assume_aligned. This is declared
  3972. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  3973. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  3974. unsigned NumArgs = TheCall->getNumArgs();
  3975. if (NumArgs > 3)
  3976. return Diag(TheCall->getLocEnd(),
  3977. diag::err_typecheck_call_too_many_args_at_most)
  3978. << 0 /*function call*/ << 3 << NumArgs
  3979. << TheCall->getSourceRange();
  3980. // The alignment must be a constant integer.
  3981. Expr *Arg = TheCall->getArg(1);
  3982. // We can't check the value of a dependent argument.
  3983. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  3984. llvm::APSInt Result;
  3985. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  3986. return true;
  3987. if (!Result.isPowerOf2())
  3988. return Diag(TheCall->getLocStart(),
  3989. diag::err_alignment_not_power_of_two)
  3990. << Arg->getSourceRange();
  3991. }
  3992. if (NumArgs > 2) {
  3993. ExprResult Arg(TheCall->getArg(2));
  3994. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  3995. Context.getSizeType(), false);
  3996. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  3997. if (Arg.isInvalid()) return true;
  3998. TheCall->setArg(2, Arg.get());
  3999. }
  4000. return false;
  4001. }
  4002. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  4003. unsigned BuiltinID =
  4004. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  4005. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  4006. unsigned NumArgs = TheCall->getNumArgs();
  4007. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  4008. if (NumArgs < NumRequiredArgs) {
  4009. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  4010. << 0 /* function call */ << NumRequiredArgs << NumArgs
  4011. << TheCall->getSourceRange();
  4012. }
  4013. if (NumArgs >= NumRequiredArgs + 0x100) {
  4014. return Diag(TheCall->getLocEnd(),
  4015. diag::err_typecheck_call_too_many_args_at_most)
  4016. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  4017. << TheCall->getSourceRange();
  4018. }
  4019. unsigned i = 0;
  4020. // For formatting call, check buffer arg.
  4021. if (!IsSizeCall) {
  4022. ExprResult Arg(TheCall->getArg(i));
  4023. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4024. Context, Context.VoidPtrTy, false);
  4025. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4026. if (Arg.isInvalid())
  4027. return true;
  4028. TheCall->setArg(i, Arg.get());
  4029. i++;
  4030. }
  4031. // Check string literal arg.
  4032. unsigned FormatIdx = i;
  4033. {
  4034. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  4035. if (Arg.isInvalid())
  4036. return true;
  4037. TheCall->setArg(i, Arg.get());
  4038. i++;
  4039. }
  4040. // Make sure variadic args are scalar.
  4041. unsigned FirstDataArg = i;
  4042. while (i < NumArgs) {
  4043. ExprResult Arg = DefaultVariadicArgumentPromotion(
  4044. TheCall->getArg(i), VariadicFunction, nullptr);
  4045. if (Arg.isInvalid())
  4046. return true;
  4047. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  4048. if (ArgSize.getQuantity() >= 0x100) {
  4049. return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
  4050. << i << (int)ArgSize.getQuantity() << 0xff
  4051. << TheCall->getSourceRange();
  4052. }
  4053. TheCall->setArg(i, Arg.get());
  4054. i++;
  4055. }
  4056. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  4057. // call to avoid duplicate diagnostics.
  4058. if (!IsSizeCall) {
  4059. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  4060. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  4061. bool Success = CheckFormatArguments(
  4062. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  4063. VariadicFunction, TheCall->getLocStart(), SourceRange(),
  4064. CheckedVarArgs);
  4065. if (!Success)
  4066. return true;
  4067. }
  4068. if (IsSizeCall) {
  4069. TheCall->setType(Context.getSizeType());
  4070. } else {
  4071. TheCall->setType(Context.VoidPtrTy);
  4072. }
  4073. return false;
  4074. }
  4075. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  4076. /// TheCall is a constant expression.
  4077. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  4078. llvm::APSInt &Result) {
  4079. Expr *Arg = TheCall->getArg(ArgNum);
  4080. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4081. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4082. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  4083. if (!Arg->isIntegerConstantExpr(Result, Context))
  4084. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  4085. << FDecl->getDeclName() << Arg->getSourceRange();
  4086. return false;
  4087. }
  4088. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  4089. /// TheCall is a constant expression in the range [Low, High].
  4090. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  4091. int Low, int High) {
  4092. llvm::APSInt Result;
  4093. // We can't check the value of a dependent argument.
  4094. Expr *Arg = TheCall->getArg(ArgNum);
  4095. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4096. return false;
  4097. // Check constant-ness first.
  4098. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4099. return true;
  4100. if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
  4101. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  4102. << Low << High << Arg->getSourceRange();
  4103. return false;
  4104. }
  4105. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  4106. /// TheCall is a constant expression is a multiple of Num..
  4107. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  4108. unsigned Num) {
  4109. llvm::APSInt Result;
  4110. // We can't check the value of a dependent argument.
  4111. Expr *Arg = TheCall->getArg(ArgNum);
  4112. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4113. return false;
  4114. // Check constant-ness first.
  4115. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4116. return true;
  4117. if (Result.getSExtValue() % Num != 0)
  4118. return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
  4119. << Num << Arg->getSourceRange();
  4120. return false;
  4121. }
  4122. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  4123. /// TheCall is an ARM/AArch64 special register string literal.
  4124. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  4125. int ArgNum, unsigned ExpectedFieldNum,
  4126. bool AllowName) {
  4127. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  4128. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  4129. BuiltinID == ARM::BI__builtin_arm_rsr ||
  4130. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  4131. BuiltinID == ARM::BI__builtin_arm_wsr ||
  4132. BuiltinID == ARM::BI__builtin_arm_wsrp;
  4133. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  4134. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  4135. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  4136. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  4137. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  4138. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  4139. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  4140. // We can't check the value of a dependent argument.
  4141. Expr *Arg = TheCall->getArg(ArgNum);
  4142. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4143. return false;
  4144. // Check if the argument is a string literal.
  4145. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  4146. return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  4147. << Arg->getSourceRange();
  4148. // Check the type of special register given.
  4149. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  4150. SmallVector<StringRef, 6> Fields;
  4151. Reg.split(Fields, ":");
  4152. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  4153. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  4154. << Arg->getSourceRange();
  4155. // If the string is the name of a register then we cannot check that it is
  4156. // valid here but if the string is of one the forms described in ACLE then we
  4157. // can check that the supplied fields are integers and within the valid
  4158. // ranges.
  4159. if (Fields.size() > 1) {
  4160. bool FiveFields = Fields.size() == 5;
  4161. bool ValidString = true;
  4162. if (IsARMBuiltin) {
  4163. ValidString &= Fields[0].startswith_lower("cp") ||
  4164. Fields[0].startswith_lower("p");
  4165. if (ValidString)
  4166. Fields[0] =
  4167. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  4168. ValidString &= Fields[2].startswith_lower("c");
  4169. if (ValidString)
  4170. Fields[2] = Fields[2].drop_front(1);
  4171. if (FiveFields) {
  4172. ValidString &= Fields[3].startswith_lower("c");
  4173. if (ValidString)
  4174. Fields[3] = Fields[3].drop_front(1);
  4175. }
  4176. }
  4177. SmallVector<int, 5> Ranges;
  4178. if (FiveFields)
  4179. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  4180. else
  4181. Ranges.append({15, 7, 15});
  4182. for (unsigned i=0; i<Fields.size(); ++i) {
  4183. int IntField;
  4184. ValidString &= !Fields[i].getAsInteger(10, IntField);
  4185. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  4186. }
  4187. if (!ValidString)
  4188. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  4189. << Arg->getSourceRange();
  4190. } else if (IsAArch64Builtin && Fields.size() == 1) {
  4191. // If the register name is one of those that appear in the condition below
  4192. // and the special register builtin being used is one of the write builtins,
  4193. // then we require that the argument provided for writing to the register
  4194. // is an integer constant expression. This is because it will be lowered to
  4195. // an MSR (immediate) instruction, so we need to know the immediate at
  4196. // compile time.
  4197. if (TheCall->getNumArgs() != 2)
  4198. return false;
  4199. std::string RegLower = Reg.lower();
  4200. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  4201. RegLower != "pan" && RegLower != "uao")
  4202. return false;
  4203. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  4204. }
  4205. return false;
  4206. }
  4207. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  4208. /// This checks that the target supports __builtin_longjmp and
  4209. /// that val is a constant 1.
  4210. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  4211. if (!Context.getTargetInfo().hasSjLjLowering())
  4212. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
  4213. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  4214. Expr *Arg = TheCall->getArg(1);
  4215. llvm::APSInt Result;
  4216. // TODO: This is less than ideal. Overload this to take a value.
  4217. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  4218. return true;
  4219. if (Result != 1)
  4220. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  4221. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  4222. return false;
  4223. }
  4224. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  4225. /// This checks that the target supports __builtin_setjmp.
  4226. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  4227. if (!Context.getTargetInfo().hasSjLjLowering())
  4228. return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
  4229. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  4230. return false;
  4231. }
  4232. namespace {
  4233. class UncoveredArgHandler {
  4234. enum { Unknown = -1, AllCovered = -2 };
  4235. signed FirstUncoveredArg = Unknown;
  4236. SmallVector<const Expr *, 4> DiagnosticExprs;
  4237. public:
  4238. UncoveredArgHandler() = default;
  4239. bool hasUncoveredArg() const {
  4240. return (FirstUncoveredArg >= 0);
  4241. }
  4242. unsigned getUncoveredArg() const {
  4243. assert(hasUncoveredArg() && "no uncovered argument");
  4244. return FirstUncoveredArg;
  4245. }
  4246. void setAllCovered() {
  4247. // A string has been found with all arguments covered, so clear out
  4248. // the diagnostics.
  4249. DiagnosticExprs.clear();
  4250. FirstUncoveredArg = AllCovered;
  4251. }
  4252. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  4253. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  4254. // Don't update if a previous string covers all arguments.
  4255. if (FirstUncoveredArg == AllCovered)
  4256. return;
  4257. // UncoveredArgHandler tracks the highest uncovered argument index
  4258. // and with it all the strings that match this index.
  4259. if (NewFirstUncoveredArg == FirstUncoveredArg)
  4260. DiagnosticExprs.push_back(StrExpr);
  4261. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  4262. DiagnosticExprs.clear();
  4263. DiagnosticExprs.push_back(StrExpr);
  4264. FirstUncoveredArg = NewFirstUncoveredArg;
  4265. }
  4266. }
  4267. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  4268. };
  4269. enum StringLiteralCheckType {
  4270. SLCT_NotALiteral,
  4271. SLCT_UncheckedLiteral,
  4272. SLCT_CheckedLiteral
  4273. };
  4274. } // namespace
  4275. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  4276. BinaryOperatorKind BinOpKind,
  4277. bool AddendIsRight) {
  4278. unsigned BitWidth = Offset.getBitWidth();
  4279. unsigned AddendBitWidth = Addend.getBitWidth();
  4280. // There might be negative interim results.
  4281. if (Addend.isUnsigned()) {
  4282. Addend = Addend.zext(++AddendBitWidth);
  4283. Addend.setIsSigned(true);
  4284. }
  4285. // Adjust the bit width of the APSInts.
  4286. if (AddendBitWidth > BitWidth) {
  4287. Offset = Offset.sext(AddendBitWidth);
  4288. BitWidth = AddendBitWidth;
  4289. } else if (BitWidth > AddendBitWidth) {
  4290. Addend = Addend.sext(BitWidth);
  4291. }
  4292. bool Ov = false;
  4293. llvm::APSInt ResOffset = Offset;
  4294. if (BinOpKind == BO_Add)
  4295. ResOffset = Offset.sadd_ov(Addend, Ov);
  4296. else {
  4297. assert(AddendIsRight && BinOpKind == BO_Sub &&
  4298. "operator must be add or sub with addend on the right");
  4299. ResOffset = Offset.ssub_ov(Addend, Ov);
  4300. }
  4301. // We add an offset to a pointer here so we should support an offset as big as
  4302. // possible.
  4303. if (Ov) {
  4304. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  4305. "index (intermediate) result too big");
  4306. Offset = Offset.sext(2 * BitWidth);
  4307. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  4308. return;
  4309. }
  4310. Offset = ResOffset;
  4311. }
  4312. namespace {
  4313. // This is a wrapper class around StringLiteral to support offsetted string
  4314. // literals as format strings. It takes the offset into account when returning
  4315. // the string and its length or the source locations to display notes correctly.
  4316. class FormatStringLiteral {
  4317. const StringLiteral *FExpr;
  4318. int64_t Offset;
  4319. public:
  4320. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  4321. : FExpr(fexpr), Offset(Offset) {}
  4322. StringRef getString() const {
  4323. return FExpr->getString().drop_front(Offset);
  4324. }
  4325. unsigned getByteLength() const {
  4326. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  4327. }
  4328. unsigned getLength() const { return FExpr->getLength() - Offset; }
  4329. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  4330. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  4331. QualType getType() const { return FExpr->getType(); }
  4332. bool isAscii() const { return FExpr->isAscii(); }
  4333. bool isWide() const { return FExpr->isWide(); }
  4334. bool isUTF8() const { return FExpr->isUTF8(); }
  4335. bool isUTF16() const { return FExpr->isUTF16(); }
  4336. bool isUTF32() const { return FExpr->isUTF32(); }
  4337. bool isPascal() const { return FExpr->isPascal(); }
  4338. SourceLocation getLocationOfByte(
  4339. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  4340. const TargetInfo &Target, unsigned *StartToken = nullptr,
  4341. unsigned *StartTokenByteOffset = nullptr) const {
  4342. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  4343. StartToken, StartTokenByteOffset);
  4344. }
  4345. SourceLocation getLocStart() const LLVM_READONLY {
  4346. return FExpr->getLocStart().getLocWithOffset(Offset);
  4347. }
  4348. SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
  4349. };
  4350. } // namespace
  4351. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  4352. const Expr *OrigFormatExpr,
  4353. ArrayRef<const Expr *> Args,
  4354. bool HasVAListArg, unsigned format_idx,
  4355. unsigned firstDataArg,
  4356. Sema::FormatStringType Type,
  4357. bool inFunctionCall,
  4358. Sema::VariadicCallType CallType,
  4359. llvm::SmallBitVector &CheckedVarArgs,
  4360. UncoveredArgHandler &UncoveredArg);
  4361. // Determine if an expression is a string literal or constant string.
  4362. // If this function returns false on the arguments to a function expecting a
  4363. // format string, we will usually need to emit a warning.
  4364. // True string literals are then checked by CheckFormatString.
  4365. static StringLiteralCheckType
  4366. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  4367. bool HasVAListArg, unsigned format_idx,
  4368. unsigned firstDataArg, Sema::FormatStringType Type,
  4369. Sema::VariadicCallType CallType, bool InFunctionCall,
  4370. llvm::SmallBitVector &CheckedVarArgs,
  4371. UncoveredArgHandler &UncoveredArg,
  4372. llvm::APSInt Offset) {
  4373. tryAgain:
  4374. assert(Offset.isSigned() && "invalid offset");
  4375. if (E->isTypeDependent() || E->isValueDependent())
  4376. return SLCT_NotALiteral;
  4377. E = E->IgnoreParenCasts();
  4378. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  4379. // Technically -Wformat-nonliteral does not warn about this case.
  4380. // The behavior of printf and friends in this case is implementation
  4381. // dependent. Ideally if the format string cannot be null then
  4382. // it should have a 'nonnull' attribute in the function prototype.
  4383. return SLCT_UncheckedLiteral;
  4384. switch (E->getStmtClass()) {
  4385. case Stmt::BinaryConditionalOperatorClass:
  4386. case Stmt::ConditionalOperatorClass: {
  4387. // The expression is a literal if both sub-expressions were, and it was
  4388. // completely checked only if both sub-expressions were checked.
  4389. const AbstractConditionalOperator *C =
  4390. cast<AbstractConditionalOperator>(E);
  4391. // Determine whether it is necessary to check both sub-expressions, for
  4392. // example, because the condition expression is a constant that can be
  4393. // evaluated at compile time.
  4394. bool CheckLeft = true, CheckRight = true;
  4395. bool Cond;
  4396. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
  4397. if (Cond)
  4398. CheckRight = false;
  4399. else
  4400. CheckLeft = false;
  4401. }
  4402. // We need to maintain the offsets for the right and the left hand side
  4403. // separately to check if every possible indexed expression is a valid
  4404. // string literal. They might have different offsets for different string
  4405. // literals in the end.
  4406. StringLiteralCheckType Left;
  4407. if (!CheckLeft)
  4408. Left = SLCT_UncheckedLiteral;
  4409. else {
  4410. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  4411. HasVAListArg, format_idx, firstDataArg,
  4412. Type, CallType, InFunctionCall,
  4413. CheckedVarArgs, UncoveredArg, Offset);
  4414. if (Left == SLCT_NotALiteral || !CheckRight) {
  4415. return Left;
  4416. }
  4417. }
  4418. StringLiteralCheckType Right =
  4419. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  4420. HasVAListArg, format_idx, firstDataArg,
  4421. Type, CallType, InFunctionCall, CheckedVarArgs,
  4422. UncoveredArg, Offset);
  4423. return (CheckLeft && Left < Right) ? Left : Right;
  4424. }
  4425. case Stmt::ImplicitCastExprClass:
  4426. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  4427. goto tryAgain;
  4428. case Stmt::OpaqueValueExprClass:
  4429. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  4430. E = src;
  4431. goto tryAgain;
  4432. }
  4433. return SLCT_NotALiteral;
  4434. case Stmt::PredefinedExprClass:
  4435. // While __func__, etc., are technically not string literals, they
  4436. // cannot contain format specifiers and thus are not a security
  4437. // liability.
  4438. return SLCT_UncheckedLiteral;
  4439. case Stmt::DeclRefExprClass: {
  4440. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  4441. // As an exception, do not flag errors for variables binding to
  4442. // const string literals.
  4443. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  4444. bool isConstant = false;
  4445. QualType T = DR->getType();
  4446. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  4447. isConstant = AT->getElementType().isConstant(S.Context);
  4448. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  4449. isConstant = T.isConstant(S.Context) &&
  4450. PT->getPointeeType().isConstant(S.Context);
  4451. } else if (T->isObjCObjectPointerType()) {
  4452. // In ObjC, there is usually no "const ObjectPointer" type,
  4453. // so don't check if the pointee type is constant.
  4454. isConstant = T.isConstant(S.Context);
  4455. }
  4456. if (isConstant) {
  4457. if (const Expr *Init = VD->getAnyInitializer()) {
  4458. // Look through initializers like const char c[] = { "foo" }
  4459. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  4460. if (InitList->isStringLiteralInit())
  4461. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  4462. }
  4463. return checkFormatStringExpr(S, Init, Args,
  4464. HasVAListArg, format_idx,
  4465. firstDataArg, Type, CallType,
  4466. /*InFunctionCall*/ false, CheckedVarArgs,
  4467. UncoveredArg, Offset);
  4468. }
  4469. }
  4470. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  4471. // special check to see if the format string is a function parameter
  4472. // of the function calling the printf function. If the function
  4473. // has an attribute indicating it is a printf-like function, then we
  4474. // should suppress warnings concerning non-literals being used in a call
  4475. // to a vprintf function. For example:
  4476. //
  4477. // void
  4478. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  4479. // va_list ap;
  4480. // va_start(ap, fmt);
  4481. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  4482. // ...
  4483. // }
  4484. if (HasVAListArg) {
  4485. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  4486. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  4487. int PVIndex = PV->getFunctionScopeIndex() + 1;
  4488. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  4489. // adjust for implicit parameter
  4490. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  4491. if (MD->isInstance())
  4492. ++PVIndex;
  4493. // We also check if the formats are compatible.
  4494. // We can't pass a 'scanf' string to a 'printf' function.
  4495. if (PVIndex == PVFormat->getFormatIdx() &&
  4496. Type == S.GetFormatStringType(PVFormat))
  4497. return SLCT_UncheckedLiteral;
  4498. }
  4499. }
  4500. }
  4501. }
  4502. }
  4503. return SLCT_NotALiteral;
  4504. }
  4505. case Stmt::CallExprClass:
  4506. case Stmt::CXXMemberCallExprClass: {
  4507. const CallExpr *CE = cast<CallExpr>(E);
  4508. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  4509. if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
  4510. unsigned ArgIndex = FA->getFormatIdx();
  4511. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  4512. if (MD->isInstance())
  4513. --ArgIndex;
  4514. const Expr *Arg = CE->getArg(ArgIndex - 1);
  4515. return checkFormatStringExpr(S, Arg, Args,
  4516. HasVAListArg, format_idx, firstDataArg,
  4517. Type, CallType, InFunctionCall,
  4518. CheckedVarArgs, UncoveredArg, Offset);
  4519. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  4520. unsigned BuiltinID = FD->getBuiltinID();
  4521. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  4522. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  4523. const Expr *Arg = CE->getArg(0);
  4524. return checkFormatStringExpr(S, Arg, Args,
  4525. HasVAListArg, format_idx,
  4526. firstDataArg, Type, CallType,
  4527. InFunctionCall, CheckedVarArgs,
  4528. UncoveredArg, Offset);
  4529. }
  4530. }
  4531. }
  4532. return SLCT_NotALiteral;
  4533. }
  4534. case Stmt::ObjCMessageExprClass: {
  4535. const auto *ME = cast<ObjCMessageExpr>(E);
  4536. if (const auto *ND = ME->getMethodDecl()) {
  4537. if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
  4538. unsigned ArgIndex = FA->getFormatIdx();
  4539. const Expr *Arg = ME->getArg(ArgIndex - 1);
  4540. return checkFormatStringExpr(
  4541. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  4542. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  4543. }
  4544. }
  4545. return SLCT_NotALiteral;
  4546. }
  4547. case Stmt::ObjCStringLiteralClass:
  4548. case Stmt::StringLiteralClass: {
  4549. const StringLiteral *StrE = nullptr;
  4550. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  4551. StrE = ObjCFExpr->getString();
  4552. else
  4553. StrE = cast<StringLiteral>(E);
  4554. if (StrE) {
  4555. if (Offset.isNegative() || Offset > StrE->getLength()) {
  4556. // TODO: It would be better to have an explicit warning for out of
  4557. // bounds literals.
  4558. return SLCT_NotALiteral;
  4559. }
  4560. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  4561. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  4562. firstDataArg, Type, InFunctionCall, CallType,
  4563. CheckedVarArgs, UncoveredArg);
  4564. return SLCT_CheckedLiteral;
  4565. }
  4566. return SLCT_NotALiteral;
  4567. }
  4568. case Stmt::BinaryOperatorClass: {
  4569. llvm::APSInt LResult;
  4570. llvm::APSInt RResult;
  4571. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  4572. // A string literal + an int offset is still a string literal.
  4573. if (BinOp->isAdditiveOp()) {
  4574. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
  4575. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
  4576. if (LIsInt != RIsInt) {
  4577. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  4578. if (LIsInt) {
  4579. if (BinOpKind == BO_Add) {
  4580. sumOffsets(Offset, LResult, BinOpKind, RIsInt);
  4581. E = BinOp->getRHS();
  4582. goto tryAgain;
  4583. }
  4584. } else {
  4585. sumOffsets(Offset, RResult, BinOpKind, RIsInt);
  4586. E = BinOp->getLHS();
  4587. goto tryAgain;
  4588. }
  4589. }
  4590. }
  4591. return SLCT_NotALiteral;
  4592. }
  4593. case Stmt::UnaryOperatorClass: {
  4594. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  4595. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  4596. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  4597. llvm::APSInt IndexResult;
  4598. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
  4599. sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
  4600. E = ASE->getBase();
  4601. goto tryAgain;
  4602. }
  4603. }
  4604. return SLCT_NotALiteral;
  4605. }
  4606. default:
  4607. return SLCT_NotALiteral;
  4608. }
  4609. }
  4610. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  4611. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  4612. .Case("scanf", FST_Scanf)
  4613. .Cases("printf", "printf0", FST_Printf)
  4614. .Cases("NSString", "CFString", FST_NSString)
  4615. .Case("strftime", FST_Strftime)
  4616. .Case("strfmon", FST_Strfmon)
  4617. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  4618. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  4619. .Case("os_trace", FST_OSLog)
  4620. .Case("os_log", FST_OSLog)
  4621. .Default(FST_Unknown);
  4622. }
  4623. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  4624. /// functions) for correct use of format strings.
  4625. /// Returns true if a format string has been fully checked.
  4626. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  4627. ArrayRef<const Expr *> Args,
  4628. bool IsCXXMember,
  4629. VariadicCallType CallType,
  4630. SourceLocation Loc, SourceRange Range,
  4631. llvm::SmallBitVector &CheckedVarArgs) {
  4632. FormatStringInfo FSI;
  4633. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  4634. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  4635. FSI.FirstDataArg, GetFormatStringType(Format),
  4636. CallType, Loc, Range, CheckedVarArgs);
  4637. return false;
  4638. }
  4639. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  4640. bool HasVAListArg, unsigned format_idx,
  4641. unsigned firstDataArg, FormatStringType Type,
  4642. VariadicCallType CallType,
  4643. SourceLocation Loc, SourceRange Range,
  4644. llvm::SmallBitVector &CheckedVarArgs) {
  4645. // CHECK: printf/scanf-like function is called with no format string.
  4646. if (format_idx >= Args.size()) {
  4647. Diag(Loc, diag::warn_missing_format_string) << Range;
  4648. return false;
  4649. }
  4650. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  4651. // CHECK: format string is not a string literal.
  4652. //
  4653. // Dynamically generated format strings are difficult to
  4654. // automatically vet at compile time. Requiring that format strings
  4655. // are string literals: (1) permits the checking of format strings by
  4656. // the compiler and thereby (2) can practically remove the source of
  4657. // many format string exploits.
  4658. // Format string can be either ObjC string (e.g. @"%d") or
  4659. // C string (e.g. "%d")
  4660. // ObjC string uses the same format specifiers as C string, so we can use
  4661. // the same format string checking logic for both ObjC and C strings.
  4662. UncoveredArgHandler UncoveredArg;
  4663. StringLiteralCheckType CT =
  4664. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  4665. format_idx, firstDataArg, Type, CallType,
  4666. /*IsFunctionCall*/ true, CheckedVarArgs,
  4667. UncoveredArg,
  4668. /*no string offset*/ llvm::APSInt(64, false) = 0);
  4669. // Generate a diagnostic where an uncovered argument is detected.
  4670. if (UncoveredArg.hasUncoveredArg()) {
  4671. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  4672. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  4673. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  4674. }
  4675. if (CT != SLCT_NotALiteral)
  4676. // Literal format string found, check done!
  4677. return CT == SLCT_CheckedLiteral;
  4678. // Strftime is particular as it always uses a single 'time' argument,
  4679. // so it is safe to pass a non-literal string.
  4680. if (Type == FST_Strftime)
  4681. return false;
  4682. // Do not emit diag when the string param is a macro expansion and the
  4683. // format is either NSString or CFString. This is a hack to prevent
  4684. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  4685. // which are usually used in place of NS and CF string literals.
  4686. SourceLocation FormatLoc = Args[format_idx]->getLocStart();
  4687. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  4688. return false;
  4689. // If there are no arguments specified, warn with -Wformat-security, otherwise
  4690. // warn only with -Wformat-nonliteral.
  4691. if (Args.size() == firstDataArg) {
  4692. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  4693. << OrigFormatExpr->getSourceRange();
  4694. switch (Type) {
  4695. default:
  4696. break;
  4697. case FST_Kprintf:
  4698. case FST_FreeBSDKPrintf:
  4699. case FST_Printf:
  4700. Diag(FormatLoc, diag::note_format_security_fixit)
  4701. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  4702. break;
  4703. case FST_NSString:
  4704. Diag(FormatLoc, diag::note_format_security_fixit)
  4705. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  4706. break;
  4707. }
  4708. } else {
  4709. Diag(FormatLoc, diag::warn_format_nonliteral)
  4710. << OrigFormatExpr->getSourceRange();
  4711. }
  4712. return false;
  4713. }
  4714. namespace {
  4715. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  4716. protected:
  4717. Sema &S;
  4718. const FormatStringLiteral *FExpr;
  4719. const Expr *OrigFormatExpr;
  4720. const Sema::FormatStringType FSType;
  4721. const unsigned FirstDataArg;
  4722. const unsigned NumDataArgs;
  4723. const char *Beg; // Start of format string.
  4724. const bool HasVAListArg;
  4725. ArrayRef<const Expr *> Args;
  4726. unsigned FormatIdx;
  4727. llvm::SmallBitVector CoveredArgs;
  4728. bool usesPositionalArgs = false;
  4729. bool atFirstArg = true;
  4730. bool inFunctionCall;
  4731. Sema::VariadicCallType CallType;
  4732. llvm::SmallBitVector &CheckedVarArgs;
  4733. UncoveredArgHandler &UncoveredArg;
  4734. public:
  4735. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  4736. const Expr *origFormatExpr,
  4737. const Sema::FormatStringType type, unsigned firstDataArg,
  4738. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  4739. ArrayRef<const Expr *> Args, unsigned formatIdx,
  4740. bool inFunctionCall, Sema::VariadicCallType callType,
  4741. llvm::SmallBitVector &CheckedVarArgs,
  4742. UncoveredArgHandler &UncoveredArg)
  4743. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  4744. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  4745. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  4746. inFunctionCall(inFunctionCall), CallType(callType),
  4747. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  4748. CoveredArgs.resize(numDataArgs);
  4749. CoveredArgs.reset();
  4750. }
  4751. void DoneProcessing();
  4752. void HandleIncompleteSpecifier(const char *startSpecifier,
  4753. unsigned specifierLen) override;
  4754. void HandleInvalidLengthModifier(
  4755. const analyze_format_string::FormatSpecifier &FS,
  4756. const analyze_format_string::ConversionSpecifier &CS,
  4757. const char *startSpecifier, unsigned specifierLen,
  4758. unsigned DiagID);
  4759. void HandleNonStandardLengthModifier(
  4760. const analyze_format_string::FormatSpecifier &FS,
  4761. const char *startSpecifier, unsigned specifierLen);
  4762. void HandleNonStandardConversionSpecifier(
  4763. const analyze_format_string::ConversionSpecifier &CS,
  4764. const char *startSpecifier, unsigned specifierLen);
  4765. void HandlePosition(const char *startPos, unsigned posLen) override;
  4766. void HandleInvalidPosition(const char *startSpecifier,
  4767. unsigned specifierLen,
  4768. analyze_format_string::PositionContext p) override;
  4769. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  4770. void HandleNullChar(const char *nullCharacter) override;
  4771. template <typename Range>
  4772. static void
  4773. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  4774. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  4775. bool IsStringLocation, Range StringRange,
  4776. ArrayRef<FixItHint> Fixit = None);
  4777. protected:
  4778. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  4779. const char *startSpec,
  4780. unsigned specifierLen,
  4781. const char *csStart, unsigned csLen);
  4782. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  4783. const char *startSpec,
  4784. unsigned specifierLen);
  4785. SourceRange getFormatStringRange();
  4786. CharSourceRange getSpecifierRange(const char *startSpecifier,
  4787. unsigned specifierLen);
  4788. SourceLocation getLocationOfByte(const char *x);
  4789. const Expr *getDataArg(unsigned i) const;
  4790. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  4791. const analyze_format_string::ConversionSpecifier &CS,
  4792. const char *startSpecifier, unsigned specifierLen,
  4793. unsigned argIndex);
  4794. template <typename Range>
  4795. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  4796. bool IsStringLocation, Range StringRange,
  4797. ArrayRef<FixItHint> Fixit = None);
  4798. };
  4799. } // namespace
  4800. SourceRange CheckFormatHandler::getFormatStringRange() {
  4801. return OrigFormatExpr->getSourceRange();
  4802. }
  4803. CharSourceRange CheckFormatHandler::
  4804. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  4805. SourceLocation Start = getLocationOfByte(startSpecifier);
  4806. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  4807. // Advance the end SourceLocation by one due to half-open ranges.
  4808. End = End.getLocWithOffset(1);
  4809. return CharSourceRange::getCharRange(Start, End);
  4810. }
  4811. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  4812. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  4813. S.getLangOpts(), S.Context.getTargetInfo());
  4814. }
  4815. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  4816. unsigned specifierLen){
  4817. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  4818. getLocationOfByte(startSpecifier),
  4819. /*IsStringLocation*/true,
  4820. getSpecifierRange(startSpecifier, specifierLen));
  4821. }
  4822. void CheckFormatHandler::HandleInvalidLengthModifier(
  4823. const analyze_format_string::FormatSpecifier &FS,
  4824. const analyze_format_string::ConversionSpecifier &CS,
  4825. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  4826. using namespace analyze_format_string;
  4827. const LengthModifier &LM = FS.getLengthModifier();
  4828. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  4829. // See if we know how to fix this length modifier.
  4830. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  4831. if (FixedLM) {
  4832. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  4833. getLocationOfByte(LM.getStart()),
  4834. /*IsStringLocation*/true,
  4835. getSpecifierRange(startSpecifier, specifierLen));
  4836. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  4837. << FixedLM->toString()
  4838. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  4839. } else {
  4840. FixItHint Hint;
  4841. if (DiagID == diag::warn_format_nonsensical_length)
  4842. Hint = FixItHint::CreateRemoval(LMRange);
  4843. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  4844. getLocationOfByte(LM.getStart()),
  4845. /*IsStringLocation*/true,
  4846. getSpecifierRange(startSpecifier, specifierLen),
  4847. Hint);
  4848. }
  4849. }
  4850. void CheckFormatHandler::HandleNonStandardLengthModifier(
  4851. const analyze_format_string::FormatSpecifier &FS,
  4852. const char *startSpecifier, unsigned specifierLen) {
  4853. using namespace analyze_format_string;
  4854. const LengthModifier &LM = FS.getLengthModifier();
  4855. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  4856. // See if we know how to fix this length modifier.
  4857. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  4858. if (FixedLM) {
  4859. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4860. << LM.toString() << 0,
  4861. getLocationOfByte(LM.getStart()),
  4862. /*IsStringLocation*/true,
  4863. getSpecifierRange(startSpecifier, specifierLen));
  4864. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  4865. << FixedLM->toString()
  4866. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  4867. } else {
  4868. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4869. << LM.toString() << 0,
  4870. getLocationOfByte(LM.getStart()),
  4871. /*IsStringLocation*/true,
  4872. getSpecifierRange(startSpecifier, specifierLen));
  4873. }
  4874. }
  4875. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  4876. const analyze_format_string::ConversionSpecifier &CS,
  4877. const char *startSpecifier, unsigned specifierLen) {
  4878. using namespace analyze_format_string;
  4879. // See if we know how to fix this conversion specifier.
  4880. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  4881. if (FixedCS) {
  4882. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4883. << CS.toString() << /*conversion specifier*/1,
  4884. getLocationOfByte(CS.getStart()),
  4885. /*IsStringLocation*/true,
  4886. getSpecifierRange(startSpecifier, specifierLen));
  4887. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  4888. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  4889. << FixedCS->toString()
  4890. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  4891. } else {
  4892. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4893. << CS.toString() << /*conversion specifier*/1,
  4894. getLocationOfByte(CS.getStart()),
  4895. /*IsStringLocation*/true,
  4896. getSpecifierRange(startSpecifier, specifierLen));
  4897. }
  4898. }
  4899. void CheckFormatHandler::HandlePosition(const char *startPos,
  4900. unsigned posLen) {
  4901. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  4902. getLocationOfByte(startPos),
  4903. /*IsStringLocation*/true,
  4904. getSpecifierRange(startPos, posLen));
  4905. }
  4906. void
  4907. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  4908. analyze_format_string::PositionContext p) {
  4909. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  4910. << (unsigned) p,
  4911. getLocationOfByte(startPos), /*IsStringLocation*/true,
  4912. getSpecifierRange(startPos, posLen));
  4913. }
  4914. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  4915. unsigned posLen) {
  4916. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  4917. getLocationOfByte(startPos),
  4918. /*IsStringLocation*/true,
  4919. getSpecifierRange(startPos, posLen));
  4920. }
  4921. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  4922. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  4923. // The presence of a null character is likely an error.
  4924. EmitFormatDiagnostic(
  4925. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  4926. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  4927. getFormatStringRange());
  4928. }
  4929. }
  4930. // Note that this may return NULL if there was an error parsing or building
  4931. // one of the argument expressions.
  4932. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  4933. return Args[FirstDataArg + i];
  4934. }
  4935. void CheckFormatHandler::DoneProcessing() {
  4936. // Does the number of data arguments exceed the number of
  4937. // format conversions in the format string?
  4938. if (!HasVAListArg) {
  4939. // Find any arguments that weren't covered.
  4940. CoveredArgs.flip();
  4941. signed notCoveredArg = CoveredArgs.find_first();
  4942. if (notCoveredArg >= 0) {
  4943. assert((unsigned)notCoveredArg < NumDataArgs);
  4944. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  4945. } else {
  4946. UncoveredArg.setAllCovered();
  4947. }
  4948. }
  4949. }
  4950. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  4951. const Expr *ArgExpr) {
  4952. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  4953. "Invalid state");
  4954. if (!ArgExpr)
  4955. return;
  4956. SourceLocation Loc = ArgExpr->getLocStart();
  4957. if (S.getSourceManager().isInSystemMacro(Loc))
  4958. return;
  4959. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  4960. for (auto E : DiagnosticExprs)
  4961. PDiag << E->getSourceRange();
  4962. CheckFormatHandler::EmitFormatDiagnostic(
  4963. S, IsFunctionCall, DiagnosticExprs[0],
  4964. PDiag, Loc, /*IsStringLocation*/false,
  4965. DiagnosticExprs[0]->getSourceRange());
  4966. }
  4967. bool
  4968. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  4969. SourceLocation Loc,
  4970. const char *startSpec,
  4971. unsigned specifierLen,
  4972. const char *csStart,
  4973. unsigned csLen) {
  4974. bool keepGoing = true;
  4975. if (argIndex < NumDataArgs) {
  4976. // Consider the argument coverered, even though the specifier doesn't
  4977. // make sense.
  4978. CoveredArgs.set(argIndex);
  4979. }
  4980. else {
  4981. // If argIndex exceeds the number of data arguments we
  4982. // don't issue a warning because that is just a cascade of warnings (and
  4983. // they may have intended '%%' anyway). We don't want to continue processing
  4984. // the format string after this point, however, as we will like just get
  4985. // gibberish when trying to match arguments.
  4986. keepGoing = false;
  4987. }
  4988. StringRef Specifier(csStart, csLen);
  4989. // If the specifier in non-printable, it could be the first byte of a UTF-8
  4990. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  4991. // hex value.
  4992. std::string CodePointStr;
  4993. if (!llvm::sys::locale::isPrint(*csStart)) {
  4994. llvm::UTF32 CodePoint;
  4995. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  4996. const llvm::UTF8 *E =
  4997. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  4998. llvm::ConversionResult Result =
  4999. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  5000. if (Result != llvm::conversionOK) {
  5001. unsigned char FirstChar = *csStart;
  5002. CodePoint = (llvm::UTF32)FirstChar;
  5003. }
  5004. llvm::raw_string_ostream OS(CodePointStr);
  5005. if (CodePoint < 256)
  5006. OS << "\\x" << llvm::format("%02x", CodePoint);
  5007. else if (CodePoint <= 0xFFFF)
  5008. OS << "\\u" << llvm::format("%04x", CodePoint);
  5009. else
  5010. OS << "\\U" << llvm::format("%08x", CodePoint);
  5011. OS.flush();
  5012. Specifier = CodePointStr;
  5013. }
  5014. EmitFormatDiagnostic(
  5015. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  5016. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  5017. return keepGoing;
  5018. }
  5019. void
  5020. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  5021. const char *startSpec,
  5022. unsigned specifierLen) {
  5023. EmitFormatDiagnostic(
  5024. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  5025. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  5026. }
  5027. bool
  5028. CheckFormatHandler::CheckNumArgs(
  5029. const analyze_format_string::FormatSpecifier &FS,
  5030. const analyze_format_string::ConversionSpecifier &CS,
  5031. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  5032. if (argIndex >= NumDataArgs) {
  5033. PartialDiagnostic PDiag = FS.usesPositionalArg()
  5034. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  5035. << (argIndex+1) << NumDataArgs)
  5036. : S.PDiag(diag::warn_printf_insufficient_data_args);
  5037. EmitFormatDiagnostic(
  5038. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  5039. getSpecifierRange(startSpecifier, specifierLen));
  5040. // Since more arguments than conversion tokens are given, by extension
  5041. // all arguments are covered, so mark this as so.
  5042. UncoveredArg.setAllCovered();
  5043. return false;
  5044. }
  5045. return true;
  5046. }
  5047. template<typename Range>
  5048. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  5049. SourceLocation Loc,
  5050. bool IsStringLocation,
  5051. Range StringRange,
  5052. ArrayRef<FixItHint> FixIt) {
  5053. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  5054. Loc, IsStringLocation, StringRange, FixIt);
  5055. }
  5056. /// \brief If the format string is not within the funcion call, emit a note
  5057. /// so that the function call and string are in diagnostic messages.
  5058. ///
  5059. /// \param InFunctionCall if true, the format string is within the function
  5060. /// call and only one diagnostic message will be produced. Otherwise, an
  5061. /// extra note will be emitted pointing to location of the format string.
  5062. ///
  5063. /// \param ArgumentExpr the expression that is passed as the format string
  5064. /// argument in the function call. Used for getting locations when two
  5065. /// diagnostics are emitted.
  5066. ///
  5067. /// \param PDiag the callee should already have provided any strings for the
  5068. /// diagnostic message. This function only adds locations and fixits
  5069. /// to diagnostics.
  5070. ///
  5071. /// \param Loc primary location for diagnostic. If two diagnostics are
  5072. /// required, one will be at Loc and a new SourceLocation will be created for
  5073. /// the other one.
  5074. ///
  5075. /// \param IsStringLocation if true, Loc points to the format string should be
  5076. /// used for the note. Otherwise, Loc points to the argument list and will
  5077. /// be used with PDiag.
  5078. ///
  5079. /// \param StringRange some or all of the string to highlight. This is
  5080. /// templated so it can accept either a CharSourceRange or a SourceRange.
  5081. ///
  5082. /// \param FixIt optional fix it hint for the format string.
  5083. template <typename Range>
  5084. void CheckFormatHandler::EmitFormatDiagnostic(
  5085. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  5086. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  5087. Range StringRange, ArrayRef<FixItHint> FixIt) {
  5088. if (InFunctionCall) {
  5089. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  5090. D << StringRange;
  5091. D << FixIt;
  5092. } else {
  5093. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  5094. << ArgumentExpr->getSourceRange();
  5095. const Sema::SemaDiagnosticBuilder &Note =
  5096. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  5097. diag::note_format_string_defined);
  5098. Note << StringRange;
  5099. Note << FixIt;
  5100. }
  5101. }
  5102. //===--- CHECK: Printf format string checking ------------------------------===//
  5103. namespace {
  5104. class CheckPrintfHandler : public CheckFormatHandler {
  5105. public:
  5106. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  5107. const Expr *origFormatExpr,
  5108. const Sema::FormatStringType type, unsigned firstDataArg,
  5109. unsigned numDataArgs, bool isObjC, const char *beg,
  5110. bool hasVAListArg, ArrayRef<const Expr *> Args,
  5111. unsigned formatIdx, bool inFunctionCall,
  5112. Sema::VariadicCallType CallType,
  5113. llvm::SmallBitVector &CheckedVarArgs,
  5114. UncoveredArgHandler &UncoveredArg)
  5115. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  5116. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  5117. inFunctionCall, CallType, CheckedVarArgs,
  5118. UncoveredArg) {}
  5119. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  5120. /// Returns true if '%@' specifiers are allowed in the format string.
  5121. bool allowsObjCArg() const {
  5122. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  5123. FSType == Sema::FST_OSTrace;
  5124. }
  5125. bool HandleInvalidPrintfConversionSpecifier(
  5126. const analyze_printf::PrintfSpecifier &FS,
  5127. const char *startSpecifier,
  5128. unsigned specifierLen) override;
  5129. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  5130. const char *startSpecifier,
  5131. unsigned specifierLen) override;
  5132. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  5133. const char *StartSpecifier,
  5134. unsigned SpecifierLen,
  5135. const Expr *E);
  5136. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  5137. const char *startSpecifier, unsigned specifierLen);
  5138. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  5139. const analyze_printf::OptionalAmount &Amt,
  5140. unsigned type,
  5141. const char *startSpecifier, unsigned specifierLen);
  5142. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  5143. const analyze_printf::OptionalFlag &flag,
  5144. const char *startSpecifier, unsigned specifierLen);
  5145. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  5146. const analyze_printf::OptionalFlag &ignoredFlag,
  5147. const analyze_printf::OptionalFlag &flag,
  5148. const char *startSpecifier, unsigned specifierLen);
  5149. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  5150. const Expr *E);
  5151. void HandleEmptyObjCModifierFlag(const char *startFlag,
  5152. unsigned flagLen) override;
  5153. void HandleInvalidObjCModifierFlag(const char *startFlag,
  5154. unsigned flagLen) override;
  5155. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  5156. const char *flagsEnd,
  5157. const char *conversionPosition)
  5158. override;
  5159. };
  5160. } // namespace
  5161. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  5162. const analyze_printf::PrintfSpecifier &FS,
  5163. const char *startSpecifier,
  5164. unsigned specifierLen) {
  5165. const analyze_printf::PrintfConversionSpecifier &CS =
  5166. FS.getConversionSpecifier();
  5167. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  5168. getLocationOfByte(CS.getStart()),
  5169. startSpecifier, specifierLen,
  5170. CS.getStart(), CS.getLength());
  5171. }
  5172. bool CheckPrintfHandler::HandleAmount(
  5173. const analyze_format_string::OptionalAmount &Amt,
  5174. unsigned k, const char *startSpecifier,
  5175. unsigned specifierLen) {
  5176. if (Amt.hasDataArgument()) {
  5177. if (!HasVAListArg) {
  5178. unsigned argIndex = Amt.getArgIndex();
  5179. if (argIndex >= NumDataArgs) {
  5180. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  5181. << k,
  5182. getLocationOfByte(Amt.getStart()),
  5183. /*IsStringLocation*/true,
  5184. getSpecifierRange(startSpecifier, specifierLen));
  5185. // Don't do any more checking. We will just emit
  5186. // spurious errors.
  5187. return false;
  5188. }
  5189. // Type check the data argument. It should be an 'int'.
  5190. // Although not in conformance with C99, we also allow the argument to be
  5191. // an 'unsigned int' as that is a reasonably safe case. GCC also
  5192. // doesn't emit a warning for that case.
  5193. CoveredArgs.set(argIndex);
  5194. const Expr *Arg = getDataArg(argIndex);
  5195. if (!Arg)
  5196. return false;
  5197. QualType T = Arg->getType();
  5198. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  5199. assert(AT.isValid());
  5200. if (!AT.matchesType(S.Context, T)) {
  5201. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  5202. << k << AT.getRepresentativeTypeName(S.Context)
  5203. << T << Arg->getSourceRange(),
  5204. getLocationOfByte(Amt.getStart()),
  5205. /*IsStringLocation*/true,
  5206. getSpecifierRange(startSpecifier, specifierLen));
  5207. // Don't do any more checking. We will just emit
  5208. // spurious errors.
  5209. return false;
  5210. }
  5211. }
  5212. }
  5213. return true;
  5214. }
  5215. void CheckPrintfHandler::HandleInvalidAmount(
  5216. const analyze_printf::PrintfSpecifier &FS,
  5217. const analyze_printf::OptionalAmount &Amt,
  5218. unsigned type,
  5219. const char *startSpecifier,
  5220. unsigned specifierLen) {
  5221. const analyze_printf::PrintfConversionSpecifier &CS =
  5222. FS.getConversionSpecifier();
  5223. FixItHint fixit =
  5224. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  5225. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  5226. Amt.getConstantLength()))
  5227. : FixItHint();
  5228. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  5229. << type << CS.toString(),
  5230. getLocationOfByte(Amt.getStart()),
  5231. /*IsStringLocation*/true,
  5232. getSpecifierRange(startSpecifier, specifierLen),
  5233. fixit);
  5234. }
  5235. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  5236. const analyze_printf::OptionalFlag &flag,
  5237. const char *startSpecifier,
  5238. unsigned specifierLen) {
  5239. // Warn about pointless flag with a fixit removal.
  5240. const analyze_printf::PrintfConversionSpecifier &CS =
  5241. FS.getConversionSpecifier();
  5242. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  5243. << flag.toString() << CS.toString(),
  5244. getLocationOfByte(flag.getPosition()),
  5245. /*IsStringLocation*/true,
  5246. getSpecifierRange(startSpecifier, specifierLen),
  5247. FixItHint::CreateRemoval(
  5248. getSpecifierRange(flag.getPosition(), 1)));
  5249. }
  5250. void CheckPrintfHandler::HandleIgnoredFlag(
  5251. const analyze_printf::PrintfSpecifier &FS,
  5252. const analyze_printf::OptionalFlag &ignoredFlag,
  5253. const analyze_printf::OptionalFlag &flag,
  5254. const char *startSpecifier,
  5255. unsigned specifierLen) {
  5256. // Warn about ignored flag with a fixit removal.
  5257. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  5258. << ignoredFlag.toString() << flag.toString(),
  5259. getLocationOfByte(ignoredFlag.getPosition()),
  5260. /*IsStringLocation*/true,
  5261. getSpecifierRange(startSpecifier, specifierLen),
  5262. FixItHint::CreateRemoval(
  5263. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  5264. }
  5265. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  5266. unsigned flagLen) {
  5267. // Warn about an empty flag.
  5268. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  5269. getLocationOfByte(startFlag),
  5270. /*IsStringLocation*/true,
  5271. getSpecifierRange(startFlag, flagLen));
  5272. }
  5273. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  5274. unsigned flagLen) {
  5275. // Warn about an invalid flag.
  5276. auto Range = getSpecifierRange(startFlag, flagLen);
  5277. StringRef flag(startFlag, flagLen);
  5278. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  5279. getLocationOfByte(startFlag),
  5280. /*IsStringLocation*/true,
  5281. Range, FixItHint::CreateRemoval(Range));
  5282. }
  5283. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  5284. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  5285. // Warn about using '[...]' without a '@' conversion.
  5286. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  5287. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  5288. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  5289. getLocationOfByte(conversionPosition),
  5290. /*IsStringLocation*/true,
  5291. Range, FixItHint::CreateRemoval(Range));
  5292. }
  5293. // Determines if the specified is a C++ class or struct containing
  5294. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  5295. // "c_str()").
  5296. template<typename MemberKind>
  5297. static llvm::SmallPtrSet<MemberKind*, 1>
  5298. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  5299. const RecordType *RT = Ty->getAs<RecordType>();
  5300. llvm::SmallPtrSet<MemberKind*, 1> Results;
  5301. if (!RT)
  5302. return Results;
  5303. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  5304. if (!RD || !RD->getDefinition())
  5305. return Results;
  5306. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  5307. Sema::LookupMemberName);
  5308. R.suppressDiagnostics();
  5309. // We just need to include all members of the right kind turned up by the
  5310. // filter, at this point.
  5311. if (S.LookupQualifiedName(R, RT->getDecl()))
  5312. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  5313. NamedDecl *decl = (*I)->getUnderlyingDecl();
  5314. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  5315. Results.insert(FK);
  5316. }
  5317. return Results;
  5318. }
  5319. /// Check if we could call '.c_str()' on an object.
  5320. ///
  5321. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  5322. /// allow the call, or if it would be ambiguous).
  5323. bool Sema::hasCStrMethod(const Expr *E) {
  5324. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  5325. MethodSet Results =
  5326. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  5327. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  5328. MI != ME; ++MI)
  5329. if ((*MI)->getMinRequiredArguments() == 0)
  5330. return true;
  5331. return false;
  5332. }
  5333. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  5334. // better diagnostic if so. AT is assumed to be valid.
  5335. // Returns true when a c_str() conversion method is found.
  5336. bool CheckPrintfHandler::checkForCStrMembers(
  5337. const analyze_printf::ArgType &AT, const Expr *E) {
  5338. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  5339. MethodSet Results =
  5340. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  5341. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  5342. MI != ME; ++MI) {
  5343. const CXXMethodDecl *Method = *MI;
  5344. if (Method->getMinRequiredArguments() == 0 &&
  5345. AT.matchesType(S.Context, Method->getReturnType())) {
  5346. // FIXME: Suggest parens if the expression needs them.
  5347. SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
  5348. S.Diag(E->getLocStart(), diag::note_printf_c_str)
  5349. << "c_str()"
  5350. << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  5351. return true;
  5352. }
  5353. }
  5354. return false;
  5355. }
  5356. bool
  5357. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  5358. &FS,
  5359. const char *startSpecifier,
  5360. unsigned specifierLen) {
  5361. using namespace analyze_format_string;
  5362. using namespace analyze_printf;
  5363. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  5364. if (FS.consumesDataArgument()) {
  5365. if (atFirstArg) {
  5366. atFirstArg = false;
  5367. usesPositionalArgs = FS.usesPositionalArg();
  5368. }
  5369. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  5370. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  5371. startSpecifier, specifierLen);
  5372. return false;
  5373. }
  5374. }
  5375. // First check if the field width, precision, and conversion specifier
  5376. // have matching data arguments.
  5377. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  5378. startSpecifier, specifierLen)) {
  5379. return false;
  5380. }
  5381. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  5382. startSpecifier, specifierLen)) {
  5383. return false;
  5384. }
  5385. if (!CS.consumesDataArgument()) {
  5386. // FIXME: Technically specifying a precision or field width here
  5387. // makes no sense. Worth issuing a warning at some point.
  5388. return true;
  5389. }
  5390. // Consume the argument.
  5391. unsigned argIndex = FS.getArgIndex();
  5392. if (argIndex < NumDataArgs) {
  5393. // The check to see if the argIndex is valid will come later.
  5394. // We set the bit here because we may exit early from this
  5395. // function if we encounter some other error.
  5396. CoveredArgs.set(argIndex);
  5397. }
  5398. // FreeBSD kernel extensions.
  5399. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  5400. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  5401. // We need at least two arguments.
  5402. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  5403. return false;
  5404. // Claim the second argument.
  5405. CoveredArgs.set(argIndex + 1);
  5406. // Type check the first argument (int for %b, pointer for %D)
  5407. const Expr *Ex = getDataArg(argIndex);
  5408. const analyze_printf::ArgType &AT =
  5409. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  5410. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  5411. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  5412. EmitFormatDiagnostic(
  5413. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  5414. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  5415. << false << Ex->getSourceRange(),
  5416. Ex->getLocStart(), /*IsStringLocation*/false,
  5417. getSpecifierRange(startSpecifier, specifierLen));
  5418. // Type check the second argument (char * for both %b and %D)
  5419. Ex = getDataArg(argIndex + 1);
  5420. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  5421. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  5422. EmitFormatDiagnostic(
  5423. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  5424. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  5425. << false << Ex->getSourceRange(),
  5426. Ex->getLocStart(), /*IsStringLocation*/false,
  5427. getSpecifierRange(startSpecifier, specifierLen));
  5428. return true;
  5429. }
  5430. // Check for using an Objective-C specific conversion specifier
  5431. // in a non-ObjC literal.
  5432. if (!allowsObjCArg() && CS.isObjCArg()) {
  5433. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  5434. specifierLen);
  5435. }
  5436. // %P can only be used with os_log.
  5437. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  5438. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  5439. specifierLen);
  5440. }
  5441. // %n is not allowed with os_log.
  5442. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  5443. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  5444. getLocationOfByte(CS.getStart()),
  5445. /*IsStringLocation*/ false,
  5446. getSpecifierRange(startSpecifier, specifierLen));
  5447. return true;
  5448. }
  5449. // Only scalars are allowed for os_trace.
  5450. if (FSType == Sema::FST_OSTrace &&
  5451. (CS.getKind() == ConversionSpecifier::PArg ||
  5452. CS.getKind() == ConversionSpecifier::sArg ||
  5453. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  5454. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  5455. specifierLen);
  5456. }
  5457. // Check for use of public/private annotation outside of os_log().
  5458. if (FSType != Sema::FST_OSLog) {
  5459. if (FS.isPublic().isSet()) {
  5460. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  5461. << "public",
  5462. getLocationOfByte(FS.isPublic().getPosition()),
  5463. /*IsStringLocation*/ false,
  5464. getSpecifierRange(startSpecifier, specifierLen));
  5465. }
  5466. if (FS.isPrivate().isSet()) {
  5467. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  5468. << "private",
  5469. getLocationOfByte(FS.isPrivate().getPosition()),
  5470. /*IsStringLocation*/ false,
  5471. getSpecifierRange(startSpecifier, specifierLen));
  5472. }
  5473. }
  5474. // Check for invalid use of field width
  5475. if (!FS.hasValidFieldWidth()) {
  5476. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  5477. startSpecifier, specifierLen);
  5478. }
  5479. // Check for invalid use of precision
  5480. if (!FS.hasValidPrecision()) {
  5481. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  5482. startSpecifier, specifierLen);
  5483. }
  5484. // Precision is mandatory for %P specifier.
  5485. if (CS.getKind() == ConversionSpecifier::PArg &&
  5486. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  5487. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  5488. getLocationOfByte(startSpecifier),
  5489. /*IsStringLocation*/ false,
  5490. getSpecifierRange(startSpecifier, specifierLen));
  5491. }
  5492. // Check each flag does not conflict with any other component.
  5493. if (!FS.hasValidThousandsGroupingPrefix())
  5494. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  5495. if (!FS.hasValidLeadingZeros())
  5496. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  5497. if (!FS.hasValidPlusPrefix())
  5498. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  5499. if (!FS.hasValidSpacePrefix())
  5500. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  5501. if (!FS.hasValidAlternativeForm())
  5502. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  5503. if (!FS.hasValidLeftJustified())
  5504. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  5505. // Check that flags are not ignored by another flag
  5506. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  5507. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  5508. startSpecifier, specifierLen);
  5509. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  5510. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  5511. startSpecifier, specifierLen);
  5512. // Check the length modifier is valid with the given conversion specifier.
  5513. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  5514. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5515. diag::warn_format_nonsensical_length);
  5516. else if (!FS.hasStandardLengthModifier())
  5517. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  5518. else if (!FS.hasStandardLengthConversionCombination())
  5519. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5520. diag::warn_format_non_standard_conversion_spec);
  5521. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  5522. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  5523. // The remaining checks depend on the data arguments.
  5524. if (HasVAListArg)
  5525. return true;
  5526. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  5527. return false;
  5528. const Expr *Arg = getDataArg(argIndex);
  5529. if (!Arg)
  5530. return true;
  5531. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  5532. }
  5533. static bool requiresParensToAddCast(const Expr *E) {
  5534. // FIXME: We should have a general way to reason about operator
  5535. // precedence and whether parens are actually needed here.
  5536. // Take care of a few common cases where they aren't.
  5537. const Expr *Inside = E->IgnoreImpCasts();
  5538. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  5539. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  5540. switch (Inside->getStmtClass()) {
  5541. case Stmt::ArraySubscriptExprClass:
  5542. case Stmt::CallExprClass:
  5543. case Stmt::CharacterLiteralClass:
  5544. case Stmt::CXXBoolLiteralExprClass:
  5545. case Stmt::DeclRefExprClass:
  5546. case Stmt::FloatingLiteralClass:
  5547. case Stmt::IntegerLiteralClass:
  5548. case Stmt::MemberExprClass:
  5549. case Stmt::ObjCArrayLiteralClass:
  5550. case Stmt::ObjCBoolLiteralExprClass:
  5551. case Stmt::ObjCBoxedExprClass:
  5552. case Stmt::ObjCDictionaryLiteralClass:
  5553. case Stmt::ObjCEncodeExprClass:
  5554. case Stmt::ObjCIvarRefExprClass:
  5555. case Stmt::ObjCMessageExprClass:
  5556. case Stmt::ObjCPropertyRefExprClass:
  5557. case Stmt::ObjCStringLiteralClass:
  5558. case Stmt::ObjCSubscriptRefExprClass:
  5559. case Stmt::ParenExprClass:
  5560. case Stmt::StringLiteralClass:
  5561. case Stmt::UnaryOperatorClass:
  5562. return false;
  5563. default:
  5564. return true;
  5565. }
  5566. }
  5567. static std::pair<QualType, StringRef>
  5568. shouldNotPrintDirectly(const ASTContext &Context,
  5569. QualType IntendedTy,
  5570. const Expr *E) {
  5571. // Use a 'while' to peel off layers of typedefs.
  5572. QualType TyTy = IntendedTy;
  5573. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  5574. StringRef Name = UserTy->getDecl()->getName();
  5575. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  5576. .Case("CFIndex", Context.getNSIntegerType())
  5577. .Case("NSInteger", Context.getNSIntegerType())
  5578. .Case("NSUInteger", Context.getNSUIntegerType())
  5579. .Case("SInt32", Context.IntTy)
  5580. .Case("UInt32", Context.UnsignedIntTy)
  5581. .Default(QualType());
  5582. if (!CastTy.isNull())
  5583. return std::make_pair(CastTy, Name);
  5584. TyTy = UserTy->desugar();
  5585. }
  5586. // Strip parens if necessary.
  5587. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  5588. return shouldNotPrintDirectly(Context,
  5589. PE->getSubExpr()->getType(),
  5590. PE->getSubExpr());
  5591. // If this is a conditional expression, then its result type is constructed
  5592. // via usual arithmetic conversions and thus there might be no necessary
  5593. // typedef sugar there. Recurse to operands to check for NSInteger &
  5594. // Co. usage condition.
  5595. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  5596. QualType TrueTy, FalseTy;
  5597. StringRef TrueName, FalseName;
  5598. std::tie(TrueTy, TrueName) =
  5599. shouldNotPrintDirectly(Context,
  5600. CO->getTrueExpr()->getType(),
  5601. CO->getTrueExpr());
  5602. std::tie(FalseTy, FalseName) =
  5603. shouldNotPrintDirectly(Context,
  5604. CO->getFalseExpr()->getType(),
  5605. CO->getFalseExpr());
  5606. if (TrueTy == FalseTy)
  5607. return std::make_pair(TrueTy, TrueName);
  5608. else if (TrueTy.isNull())
  5609. return std::make_pair(FalseTy, FalseName);
  5610. else if (FalseTy.isNull())
  5611. return std::make_pair(TrueTy, TrueName);
  5612. }
  5613. return std::make_pair(QualType(), StringRef());
  5614. }
  5615. bool
  5616. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  5617. const char *StartSpecifier,
  5618. unsigned SpecifierLen,
  5619. const Expr *E) {
  5620. using namespace analyze_format_string;
  5621. using namespace analyze_printf;
  5622. // Now type check the data expression that matches the
  5623. // format specifier.
  5624. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  5625. if (!AT.isValid())
  5626. return true;
  5627. QualType ExprTy = E->getType();
  5628. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  5629. ExprTy = TET->getUnderlyingExpr()->getType();
  5630. }
  5631. analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
  5632. if (match == analyze_printf::ArgType::Match) {
  5633. return true;
  5634. }
  5635. // Look through argument promotions for our error message's reported type.
  5636. // This includes the integral and floating promotions, but excludes array
  5637. // and function pointer decay; seeing that an argument intended to be a
  5638. // string has type 'char [6]' is probably more confusing than 'char *'.
  5639. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  5640. if (ICE->getCastKind() == CK_IntegralCast ||
  5641. ICE->getCastKind() == CK_FloatingCast) {
  5642. E = ICE->getSubExpr();
  5643. ExprTy = E->getType();
  5644. // Check if we didn't match because of an implicit cast from a 'char'
  5645. // or 'short' to an 'int'. This is done because printf is a varargs
  5646. // function.
  5647. if (ICE->getType() == S.Context.IntTy ||
  5648. ICE->getType() == S.Context.UnsignedIntTy) {
  5649. // All further checking is done on the subexpression.
  5650. if (AT.matchesType(S.Context, ExprTy))
  5651. return true;
  5652. }
  5653. }
  5654. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  5655. // Special case for 'a', which has type 'int' in C.
  5656. // Note, however, that we do /not/ want to treat multibyte constants like
  5657. // 'MooV' as characters! This form is deprecated but still exists.
  5658. if (ExprTy == S.Context.IntTy)
  5659. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  5660. ExprTy = S.Context.CharTy;
  5661. }
  5662. // Look through enums to their underlying type.
  5663. bool IsEnum = false;
  5664. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  5665. ExprTy = EnumTy->getDecl()->getIntegerType();
  5666. IsEnum = true;
  5667. }
  5668. // %C in an Objective-C context prints a unichar, not a wchar_t.
  5669. // If the argument is an integer of some kind, believe the %C and suggest
  5670. // a cast instead of changing the conversion specifier.
  5671. QualType IntendedTy = ExprTy;
  5672. if (isObjCContext() &&
  5673. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  5674. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  5675. !ExprTy->isCharType()) {
  5676. // 'unichar' is defined as a typedef of unsigned short, but we should
  5677. // prefer using the typedef if it is visible.
  5678. IntendedTy = S.Context.UnsignedShortTy;
  5679. // While we are here, check if the value is an IntegerLiteral that happens
  5680. // to be within the valid range.
  5681. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  5682. const llvm::APInt &V = IL->getValue();
  5683. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  5684. return true;
  5685. }
  5686. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
  5687. Sema::LookupOrdinaryName);
  5688. if (S.LookupName(Result, S.getCurScope())) {
  5689. NamedDecl *ND = Result.getFoundDecl();
  5690. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  5691. if (TD->getUnderlyingType() == IntendedTy)
  5692. IntendedTy = S.Context.getTypedefType(TD);
  5693. }
  5694. }
  5695. }
  5696. // Special-case some of Darwin's platform-independence types by suggesting
  5697. // casts to primitive types that are known to be large enough.
  5698. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  5699. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  5700. QualType CastTy;
  5701. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  5702. if (!CastTy.isNull()) {
  5703. IntendedTy = CastTy;
  5704. ShouldNotPrintDirectly = true;
  5705. }
  5706. }
  5707. // We may be able to offer a FixItHint if it is a supported type.
  5708. PrintfSpecifier fixedFS = FS;
  5709. bool success =
  5710. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  5711. if (success) {
  5712. // Get the fix string from the fixed format specifier
  5713. SmallString<16> buf;
  5714. llvm::raw_svector_ostream os(buf);
  5715. fixedFS.toString(os);
  5716. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  5717. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  5718. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  5719. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  5720. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  5721. }
  5722. // In this case, the specifier is wrong and should be changed to match
  5723. // the argument.
  5724. EmitFormatDiagnostic(S.PDiag(diag)
  5725. << AT.getRepresentativeTypeName(S.Context)
  5726. << IntendedTy << IsEnum << E->getSourceRange(),
  5727. E->getLocStart(),
  5728. /*IsStringLocation*/ false, SpecRange,
  5729. FixItHint::CreateReplacement(SpecRange, os.str()));
  5730. } else {
  5731. // The canonical type for formatting this value is different from the
  5732. // actual type of the expression. (This occurs, for example, with Darwin's
  5733. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  5734. // should be printed as 'long' for 64-bit compatibility.)
  5735. // Rather than emitting a normal format/argument mismatch, we want to
  5736. // add a cast to the recommended type (and correct the format string
  5737. // if necessary).
  5738. SmallString<16> CastBuf;
  5739. llvm::raw_svector_ostream CastFix(CastBuf);
  5740. CastFix << "(";
  5741. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  5742. CastFix << ")";
  5743. SmallVector<FixItHint,4> Hints;
  5744. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  5745. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  5746. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  5747. // If there's already a cast present, just replace it.
  5748. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  5749. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  5750. } else if (!requiresParensToAddCast(E)) {
  5751. // If the expression has high enough precedence,
  5752. // just write the C-style cast.
  5753. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  5754. CastFix.str()));
  5755. } else {
  5756. // Otherwise, add parens around the expression as well as the cast.
  5757. CastFix << "(";
  5758. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  5759. CastFix.str()));
  5760. SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
  5761. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  5762. }
  5763. if (ShouldNotPrintDirectly) {
  5764. // The expression has a type that should not be printed directly.
  5765. // We extract the name from the typedef because we don't want to show
  5766. // the underlying type in the diagnostic.
  5767. StringRef Name;
  5768. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  5769. Name = TypedefTy->getDecl()->getName();
  5770. else
  5771. Name = CastTyName;
  5772. EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
  5773. << Name << IntendedTy << IsEnum
  5774. << E->getSourceRange(),
  5775. E->getLocStart(), /*IsStringLocation=*/false,
  5776. SpecRange, Hints);
  5777. } else {
  5778. // In this case, the expression could be printed using a different
  5779. // specifier, but we've decided that the specifier is probably correct
  5780. // and we should cast instead. Just use the normal warning message.
  5781. EmitFormatDiagnostic(
  5782. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  5783. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  5784. << E->getSourceRange(),
  5785. E->getLocStart(), /*IsStringLocation*/false,
  5786. SpecRange, Hints);
  5787. }
  5788. }
  5789. } else {
  5790. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  5791. SpecifierLen);
  5792. // Since the warning for passing non-POD types to variadic functions
  5793. // was deferred until now, we emit a warning for non-POD
  5794. // arguments here.
  5795. switch (S.isValidVarArgType(ExprTy)) {
  5796. case Sema::VAK_Valid:
  5797. case Sema::VAK_ValidInCXX11: {
  5798. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  5799. if (match == analyze_printf::ArgType::NoMatchPedantic) {
  5800. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  5801. }
  5802. EmitFormatDiagnostic(
  5803. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  5804. << IsEnum << CSR << E->getSourceRange(),
  5805. E->getLocStart(), /*IsStringLocation*/ false, CSR);
  5806. break;
  5807. }
  5808. case Sema::VAK_Undefined:
  5809. case Sema::VAK_MSVCUndefined:
  5810. EmitFormatDiagnostic(
  5811. S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  5812. << S.getLangOpts().CPlusPlus11
  5813. << ExprTy
  5814. << CallType
  5815. << AT.getRepresentativeTypeName(S.Context)
  5816. << CSR
  5817. << E->getSourceRange(),
  5818. E->getLocStart(), /*IsStringLocation*/false, CSR);
  5819. checkForCStrMembers(AT, E);
  5820. break;
  5821. case Sema::VAK_Invalid:
  5822. if (ExprTy->isObjCObjectType())
  5823. EmitFormatDiagnostic(
  5824. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  5825. << S.getLangOpts().CPlusPlus11
  5826. << ExprTy
  5827. << CallType
  5828. << AT.getRepresentativeTypeName(S.Context)
  5829. << CSR
  5830. << E->getSourceRange(),
  5831. E->getLocStart(), /*IsStringLocation*/false, CSR);
  5832. else
  5833. // FIXME: If this is an initializer list, suggest removing the braces
  5834. // or inserting a cast to the target type.
  5835. S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
  5836. << isa<InitListExpr>(E) << ExprTy << CallType
  5837. << AT.getRepresentativeTypeName(S.Context)
  5838. << E->getSourceRange();
  5839. break;
  5840. }
  5841. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  5842. "format string specifier index out of range");
  5843. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  5844. }
  5845. return true;
  5846. }
  5847. //===--- CHECK: Scanf format string checking ------------------------------===//
  5848. namespace {
  5849. class CheckScanfHandler : public CheckFormatHandler {
  5850. public:
  5851. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  5852. const Expr *origFormatExpr, Sema::FormatStringType type,
  5853. unsigned firstDataArg, unsigned numDataArgs,
  5854. const char *beg, bool hasVAListArg,
  5855. ArrayRef<const Expr *> Args, unsigned formatIdx,
  5856. bool inFunctionCall, Sema::VariadicCallType CallType,
  5857. llvm::SmallBitVector &CheckedVarArgs,
  5858. UncoveredArgHandler &UncoveredArg)
  5859. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  5860. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  5861. inFunctionCall, CallType, CheckedVarArgs,
  5862. UncoveredArg) {}
  5863. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  5864. const char *startSpecifier,
  5865. unsigned specifierLen) override;
  5866. bool HandleInvalidScanfConversionSpecifier(
  5867. const analyze_scanf::ScanfSpecifier &FS,
  5868. const char *startSpecifier,
  5869. unsigned specifierLen) override;
  5870. void HandleIncompleteScanList(const char *start, const char *end) override;
  5871. };
  5872. } // namespace
  5873. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  5874. const char *end) {
  5875. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  5876. getLocationOfByte(end), /*IsStringLocation*/true,
  5877. getSpecifierRange(start, end - start));
  5878. }
  5879. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  5880. const analyze_scanf::ScanfSpecifier &FS,
  5881. const char *startSpecifier,
  5882. unsigned specifierLen) {
  5883. const analyze_scanf::ScanfConversionSpecifier &CS =
  5884. FS.getConversionSpecifier();
  5885. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  5886. getLocationOfByte(CS.getStart()),
  5887. startSpecifier, specifierLen,
  5888. CS.getStart(), CS.getLength());
  5889. }
  5890. bool CheckScanfHandler::HandleScanfSpecifier(
  5891. const analyze_scanf::ScanfSpecifier &FS,
  5892. const char *startSpecifier,
  5893. unsigned specifierLen) {
  5894. using namespace analyze_scanf;
  5895. using namespace analyze_format_string;
  5896. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  5897. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  5898. // be used to decide if we are using positional arguments consistently.
  5899. if (FS.consumesDataArgument()) {
  5900. if (atFirstArg) {
  5901. atFirstArg = false;
  5902. usesPositionalArgs = FS.usesPositionalArg();
  5903. }
  5904. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  5905. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  5906. startSpecifier, specifierLen);
  5907. return false;
  5908. }
  5909. }
  5910. // Check if the field with is non-zero.
  5911. const OptionalAmount &Amt = FS.getFieldWidth();
  5912. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  5913. if (Amt.getConstantAmount() == 0) {
  5914. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  5915. Amt.getConstantLength());
  5916. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  5917. getLocationOfByte(Amt.getStart()),
  5918. /*IsStringLocation*/true, R,
  5919. FixItHint::CreateRemoval(R));
  5920. }
  5921. }
  5922. if (!FS.consumesDataArgument()) {
  5923. // FIXME: Technically specifying a precision or field width here
  5924. // makes no sense. Worth issuing a warning at some point.
  5925. return true;
  5926. }
  5927. // Consume the argument.
  5928. unsigned argIndex = FS.getArgIndex();
  5929. if (argIndex < NumDataArgs) {
  5930. // The check to see if the argIndex is valid will come later.
  5931. // We set the bit here because we may exit early from this
  5932. // function if we encounter some other error.
  5933. CoveredArgs.set(argIndex);
  5934. }
  5935. // Check the length modifier is valid with the given conversion specifier.
  5936. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  5937. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5938. diag::warn_format_nonsensical_length);
  5939. else if (!FS.hasStandardLengthModifier())
  5940. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  5941. else if (!FS.hasStandardLengthConversionCombination())
  5942. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5943. diag::warn_format_non_standard_conversion_spec);
  5944. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  5945. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  5946. // The remaining checks depend on the data arguments.
  5947. if (HasVAListArg)
  5948. return true;
  5949. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  5950. return false;
  5951. // Check that the argument type matches the format specifier.
  5952. const Expr *Ex = getDataArg(argIndex);
  5953. if (!Ex)
  5954. return true;
  5955. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  5956. if (!AT.isValid()) {
  5957. return true;
  5958. }
  5959. analyze_format_string::ArgType::MatchKind match =
  5960. AT.matchesType(S.Context, Ex->getType());
  5961. if (match == analyze_format_string::ArgType::Match) {
  5962. return true;
  5963. }
  5964. ScanfSpecifier fixedFS = FS;
  5965. bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  5966. S.getLangOpts(), S.Context);
  5967. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  5968. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  5969. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  5970. }
  5971. if (success) {
  5972. // Get the fix string from the fixed format specifier.
  5973. SmallString<128> buf;
  5974. llvm::raw_svector_ostream os(buf);
  5975. fixedFS.toString(os);
  5976. EmitFormatDiagnostic(
  5977. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
  5978. << Ex->getType() << false << Ex->getSourceRange(),
  5979. Ex->getLocStart(),
  5980. /*IsStringLocation*/ false,
  5981. getSpecifierRange(startSpecifier, specifierLen),
  5982. FixItHint::CreateReplacement(
  5983. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  5984. } else {
  5985. EmitFormatDiagnostic(S.PDiag(diag)
  5986. << AT.getRepresentativeTypeName(S.Context)
  5987. << Ex->getType() << false << Ex->getSourceRange(),
  5988. Ex->getLocStart(),
  5989. /*IsStringLocation*/ false,
  5990. getSpecifierRange(startSpecifier, specifierLen));
  5991. }
  5992. return true;
  5993. }
  5994. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  5995. const Expr *OrigFormatExpr,
  5996. ArrayRef<const Expr *> Args,
  5997. bool HasVAListArg, unsigned format_idx,
  5998. unsigned firstDataArg,
  5999. Sema::FormatStringType Type,
  6000. bool inFunctionCall,
  6001. Sema::VariadicCallType CallType,
  6002. llvm::SmallBitVector &CheckedVarArgs,
  6003. UncoveredArgHandler &UncoveredArg) {
  6004. // CHECK: is the format string a wide literal?
  6005. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  6006. CheckFormatHandler::EmitFormatDiagnostic(
  6007. S, inFunctionCall, Args[format_idx],
  6008. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  6009. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  6010. return;
  6011. }
  6012. // Str - The format string. NOTE: this is NOT null-terminated!
  6013. StringRef StrRef = FExpr->getString();
  6014. const char *Str = StrRef.data();
  6015. // Account for cases where the string literal is truncated in a declaration.
  6016. const ConstantArrayType *T =
  6017. S.Context.getAsConstantArrayType(FExpr->getType());
  6018. assert(T && "String literal not of constant array type!");
  6019. size_t TypeSize = T->getSize().getZExtValue();
  6020. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  6021. const unsigned numDataArgs = Args.size() - firstDataArg;
  6022. // Emit a warning if the string literal is truncated and does not contain an
  6023. // embedded null character.
  6024. if (TypeSize <= StrRef.size() &&
  6025. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  6026. CheckFormatHandler::EmitFormatDiagnostic(
  6027. S, inFunctionCall, Args[format_idx],
  6028. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  6029. FExpr->getLocStart(),
  6030. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  6031. return;
  6032. }
  6033. // CHECK: empty format string?
  6034. if (StrLen == 0 && numDataArgs > 0) {
  6035. CheckFormatHandler::EmitFormatDiagnostic(
  6036. S, inFunctionCall, Args[format_idx],
  6037. S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  6038. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  6039. return;
  6040. }
  6041. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  6042. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  6043. Type == Sema::FST_OSTrace) {
  6044. CheckPrintfHandler H(
  6045. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  6046. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  6047. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  6048. CheckedVarArgs, UncoveredArg);
  6049. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  6050. S.getLangOpts(),
  6051. S.Context.getTargetInfo(),
  6052. Type == Sema::FST_FreeBSDKPrintf))
  6053. H.DoneProcessing();
  6054. } else if (Type == Sema::FST_Scanf) {
  6055. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  6056. numDataArgs, Str, HasVAListArg, Args, format_idx,
  6057. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  6058. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  6059. S.getLangOpts(),
  6060. S.Context.getTargetInfo()))
  6061. H.DoneProcessing();
  6062. } // TODO: handle other formats
  6063. }
  6064. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  6065. // Str - The format string. NOTE: this is NOT null-terminated!
  6066. StringRef StrRef = FExpr->getString();
  6067. const char *Str = StrRef.data();
  6068. // Account for cases where the string literal is truncated in a declaration.
  6069. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  6070. assert(T && "String literal not of constant array type!");
  6071. size_t TypeSize = T->getSize().getZExtValue();
  6072. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  6073. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  6074. getLangOpts(),
  6075. Context.getTargetInfo());
  6076. }
  6077. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  6078. // Returns the related absolute value function that is larger, of 0 if one
  6079. // does not exist.
  6080. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  6081. switch (AbsFunction) {
  6082. default:
  6083. return 0;
  6084. case Builtin::BI__builtin_abs:
  6085. return Builtin::BI__builtin_labs;
  6086. case Builtin::BI__builtin_labs:
  6087. return Builtin::BI__builtin_llabs;
  6088. case Builtin::BI__builtin_llabs:
  6089. return 0;
  6090. case Builtin::BI__builtin_fabsf:
  6091. return Builtin::BI__builtin_fabs;
  6092. case Builtin::BI__builtin_fabs:
  6093. return Builtin::BI__builtin_fabsl;
  6094. case Builtin::BI__builtin_fabsl:
  6095. return 0;
  6096. case Builtin::BI__builtin_cabsf:
  6097. return Builtin::BI__builtin_cabs;
  6098. case Builtin::BI__builtin_cabs:
  6099. return Builtin::BI__builtin_cabsl;
  6100. case Builtin::BI__builtin_cabsl:
  6101. return 0;
  6102. case Builtin::BIabs:
  6103. return Builtin::BIlabs;
  6104. case Builtin::BIlabs:
  6105. return Builtin::BIllabs;
  6106. case Builtin::BIllabs:
  6107. return 0;
  6108. case Builtin::BIfabsf:
  6109. return Builtin::BIfabs;
  6110. case Builtin::BIfabs:
  6111. return Builtin::BIfabsl;
  6112. case Builtin::BIfabsl:
  6113. return 0;
  6114. case Builtin::BIcabsf:
  6115. return Builtin::BIcabs;
  6116. case Builtin::BIcabs:
  6117. return Builtin::BIcabsl;
  6118. case Builtin::BIcabsl:
  6119. return 0;
  6120. }
  6121. }
  6122. // Returns the argument type of the absolute value function.
  6123. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  6124. unsigned AbsType) {
  6125. if (AbsType == 0)
  6126. return QualType();
  6127. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  6128. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  6129. if (Error != ASTContext::GE_None)
  6130. return QualType();
  6131. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  6132. if (!FT)
  6133. return QualType();
  6134. if (FT->getNumParams() != 1)
  6135. return QualType();
  6136. return FT->getParamType(0);
  6137. }
  6138. // Returns the best absolute value function, or zero, based on type and
  6139. // current absolute value function.
  6140. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  6141. unsigned AbsFunctionKind) {
  6142. unsigned BestKind = 0;
  6143. uint64_t ArgSize = Context.getTypeSize(ArgType);
  6144. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  6145. Kind = getLargerAbsoluteValueFunction(Kind)) {
  6146. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  6147. if (Context.getTypeSize(ParamType) >= ArgSize) {
  6148. if (BestKind == 0)
  6149. BestKind = Kind;
  6150. else if (Context.hasSameType(ParamType, ArgType)) {
  6151. BestKind = Kind;
  6152. break;
  6153. }
  6154. }
  6155. }
  6156. return BestKind;
  6157. }
  6158. enum AbsoluteValueKind {
  6159. AVK_Integer,
  6160. AVK_Floating,
  6161. AVK_Complex
  6162. };
  6163. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  6164. if (T->isIntegralOrEnumerationType())
  6165. return AVK_Integer;
  6166. if (T->isRealFloatingType())
  6167. return AVK_Floating;
  6168. if (T->isAnyComplexType())
  6169. return AVK_Complex;
  6170. llvm_unreachable("Type not integer, floating, or complex");
  6171. }
  6172. // Changes the absolute value function to a different type. Preserves whether
  6173. // the function is a builtin.
  6174. static unsigned changeAbsFunction(unsigned AbsKind,
  6175. AbsoluteValueKind ValueKind) {
  6176. switch (ValueKind) {
  6177. case AVK_Integer:
  6178. switch (AbsKind) {
  6179. default:
  6180. return 0;
  6181. case Builtin::BI__builtin_fabsf:
  6182. case Builtin::BI__builtin_fabs:
  6183. case Builtin::BI__builtin_fabsl:
  6184. case Builtin::BI__builtin_cabsf:
  6185. case Builtin::BI__builtin_cabs:
  6186. case Builtin::BI__builtin_cabsl:
  6187. return Builtin::BI__builtin_abs;
  6188. case Builtin::BIfabsf:
  6189. case Builtin::BIfabs:
  6190. case Builtin::BIfabsl:
  6191. case Builtin::BIcabsf:
  6192. case Builtin::BIcabs:
  6193. case Builtin::BIcabsl:
  6194. return Builtin::BIabs;
  6195. }
  6196. case AVK_Floating:
  6197. switch (AbsKind) {
  6198. default:
  6199. return 0;
  6200. case Builtin::BI__builtin_abs:
  6201. case Builtin::BI__builtin_labs:
  6202. case Builtin::BI__builtin_llabs:
  6203. case Builtin::BI__builtin_cabsf:
  6204. case Builtin::BI__builtin_cabs:
  6205. case Builtin::BI__builtin_cabsl:
  6206. return Builtin::BI__builtin_fabsf;
  6207. case Builtin::BIabs:
  6208. case Builtin::BIlabs:
  6209. case Builtin::BIllabs:
  6210. case Builtin::BIcabsf:
  6211. case Builtin::BIcabs:
  6212. case Builtin::BIcabsl:
  6213. return Builtin::BIfabsf;
  6214. }
  6215. case AVK_Complex:
  6216. switch (AbsKind) {
  6217. default:
  6218. return 0;
  6219. case Builtin::BI__builtin_abs:
  6220. case Builtin::BI__builtin_labs:
  6221. case Builtin::BI__builtin_llabs:
  6222. case Builtin::BI__builtin_fabsf:
  6223. case Builtin::BI__builtin_fabs:
  6224. case Builtin::BI__builtin_fabsl:
  6225. return Builtin::BI__builtin_cabsf;
  6226. case Builtin::BIabs:
  6227. case Builtin::BIlabs:
  6228. case Builtin::BIllabs:
  6229. case Builtin::BIfabsf:
  6230. case Builtin::BIfabs:
  6231. case Builtin::BIfabsl:
  6232. return Builtin::BIcabsf;
  6233. }
  6234. }
  6235. llvm_unreachable("Unable to convert function");
  6236. }
  6237. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  6238. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  6239. if (!FnInfo)
  6240. return 0;
  6241. switch (FDecl->getBuiltinID()) {
  6242. default:
  6243. return 0;
  6244. case Builtin::BI__builtin_abs:
  6245. case Builtin::BI__builtin_fabs:
  6246. case Builtin::BI__builtin_fabsf:
  6247. case Builtin::BI__builtin_fabsl:
  6248. case Builtin::BI__builtin_labs:
  6249. case Builtin::BI__builtin_llabs:
  6250. case Builtin::BI__builtin_cabs:
  6251. case Builtin::BI__builtin_cabsf:
  6252. case Builtin::BI__builtin_cabsl:
  6253. case Builtin::BIabs:
  6254. case Builtin::BIlabs:
  6255. case Builtin::BIllabs:
  6256. case Builtin::BIfabs:
  6257. case Builtin::BIfabsf:
  6258. case Builtin::BIfabsl:
  6259. case Builtin::BIcabs:
  6260. case Builtin::BIcabsf:
  6261. case Builtin::BIcabsl:
  6262. return FDecl->getBuiltinID();
  6263. }
  6264. llvm_unreachable("Unknown Builtin type");
  6265. }
  6266. // If the replacement is valid, emit a note with replacement function.
  6267. // Additionally, suggest including the proper header if not already included.
  6268. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  6269. unsigned AbsKind, QualType ArgType) {
  6270. bool EmitHeaderHint = true;
  6271. const char *HeaderName = nullptr;
  6272. const char *FunctionName = nullptr;
  6273. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  6274. FunctionName = "std::abs";
  6275. if (ArgType->isIntegralOrEnumerationType()) {
  6276. HeaderName = "cstdlib";
  6277. } else if (ArgType->isRealFloatingType()) {
  6278. HeaderName = "cmath";
  6279. } else {
  6280. llvm_unreachable("Invalid Type");
  6281. }
  6282. // Lookup all std::abs
  6283. if (NamespaceDecl *Std = S.getStdNamespace()) {
  6284. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  6285. R.suppressDiagnostics();
  6286. S.LookupQualifiedName(R, Std);
  6287. for (const auto *I : R) {
  6288. const FunctionDecl *FDecl = nullptr;
  6289. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  6290. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  6291. } else {
  6292. FDecl = dyn_cast<FunctionDecl>(I);
  6293. }
  6294. if (!FDecl)
  6295. continue;
  6296. // Found std::abs(), check that they are the right ones.
  6297. if (FDecl->getNumParams() != 1)
  6298. continue;
  6299. // Check that the parameter type can handle the argument.
  6300. QualType ParamType = FDecl->getParamDecl(0)->getType();
  6301. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  6302. S.Context.getTypeSize(ArgType) <=
  6303. S.Context.getTypeSize(ParamType)) {
  6304. // Found a function, don't need the header hint.
  6305. EmitHeaderHint = false;
  6306. break;
  6307. }
  6308. }
  6309. }
  6310. } else {
  6311. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  6312. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  6313. if (HeaderName) {
  6314. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  6315. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  6316. R.suppressDiagnostics();
  6317. S.LookupName(R, S.getCurScope());
  6318. if (R.isSingleResult()) {
  6319. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  6320. if (FD && FD->getBuiltinID() == AbsKind) {
  6321. EmitHeaderHint = false;
  6322. } else {
  6323. return;
  6324. }
  6325. } else if (!R.empty()) {
  6326. return;
  6327. }
  6328. }
  6329. }
  6330. S.Diag(Loc, diag::note_replace_abs_function)
  6331. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  6332. if (!HeaderName)
  6333. return;
  6334. if (!EmitHeaderHint)
  6335. return;
  6336. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  6337. << FunctionName;
  6338. }
  6339. template <std::size_t StrLen>
  6340. static bool IsStdFunction(const FunctionDecl *FDecl,
  6341. const char (&Str)[StrLen]) {
  6342. if (!FDecl)
  6343. return false;
  6344. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  6345. return false;
  6346. if (!FDecl->isInStdNamespace())
  6347. return false;
  6348. return true;
  6349. }
  6350. // Warn when using the wrong abs() function.
  6351. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  6352. const FunctionDecl *FDecl) {
  6353. if (Call->getNumArgs() != 1)
  6354. return;
  6355. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  6356. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  6357. if (AbsKind == 0 && !IsStdAbs)
  6358. return;
  6359. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  6360. QualType ParamType = Call->getArg(0)->getType();
  6361. // Unsigned types cannot be negative. Suggest removing the absolute value
  6362. // function call.
  6363. if (ArgType->isUnsignedIntegerType()) {
  6364. const char *FunctionName =
  6365. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  6366. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  6367. Diag(Call->getExprLoc(), diag::note_remove_abs)
  6368. << FunctionName
  6369. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  6370. return;
  6371. }
  6372. // Taking the absolute value of a pointer is very suspicious, they probably
  6373. // wanted to index into an array, dereference a pointer, call a function, etc.
  6374. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  6375. unsigned DiagType = 0;
  6376. if (ArgType->isFunctionType())
  6377. DiagType = 1;
  6378. else if (ArgType->isArrayType())
  6379. DiagType = 2;
  6380. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  6381. return;
  6382. }
  6383. // std::abs has overloads which prevent most of the absolute value problems
  6384. // from occurring.
  6385. if (IsStdAbs)
  6386. return;
  6387. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  6388. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  6389. // The argument and parameter are the same kind. Check if they are the right
  6390. // size.
  6391. if (ArgValueKind == ParamValueKind) {
  6392. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  6393. return;
  6394. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  6395. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  6396. << FDecl << ArgType << ParamType;
  6397. if (NewAbsKind == 0)
  6398. return;
  6399. emitReplacement(*this, Call->getExprLoc(),
  6400. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  6401. return;
  6402. }
  6403. // ArgValueKind != ParamValueKind
  6404. // The wrong type of absolute value function was used. Attempt to find the
  6405. // proper one.
  6406. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  6407. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  6408. if (NewAbsKind == 0)
  6409. return;
  6410. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  6411. << FDecl << ParamValueKind << ArgValueKind;
  6412. emitReplacement(*this, Call->getExprLoc(),
  6413. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  6414. }
  6415. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  6416. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  6417. const FunctionDecl *FDecl) {
  6418. if (!Call || !FDecl) return;
  6419. // Ignore template specializations and macros.
  6420. if (inTemplateInstantiation()) return;
  6421. if (Call->getExprLoc().isMacroID()) return;
  6422. // Only care about the one template argument, two function parameter std::max
  6423. if (Call->getNumArgs() != 2) return;
  6424. if (!IsStdFunction(FDecl, "max")) return;
  6425. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  6426. if (!ArgList) return;
  6427. if (ArgList->size() != 1) return;
  6428. // Check that template type argument is unsigned integer.
  6429. const auto& TA = ArgList->get(0);
  6430. if (TA.getKind() != TemplateArgument::Type) return;
  6431. QualType ArgType = TA.getAsType();
  6432. if (!ArgType->isUnsignedIntegerType()) return;
  6433. // See if either argument is a literal zero.
  6434. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  6435. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  6436. if (!MTE) return false;
  6437. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  6438. if (!Num) return false;
  6439. if (Num->getValue() != 0) return false;
  6440. return true;
  6441. };
  6442. const Expr *FirstArg = Call->getArg(0);
  6443. const Expr *SecondArg = Call->getArg(1);
  6444. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  6445. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  6446. // Only warn when exactly one argument is zero.
  6447. if (IsFirstArgZero == IsSecondArgZero) return;
  6448. SourceRange FirstRange = FirstArg->getSourceRange();
  6449. SourceRange SecondRange = SecondArg->getSourceRange();
  6450. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  6451. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  6452. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  6453. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  6454. SourceRange RemovalRange;
  6455. if (IsFirstArgZero) {
  6456. RemovalRange = SourceRange(FirstRange.getBegin(),
  6457. SecondRange.getBegin().getLocWithOffset(-1));
  6458. } else {
  6459. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  6460. SecondRange.getEnd());
  6461. }
  6462. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  6463. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  6464. << FixItHint::CreateRemoval(RemovalRange);
  6465. }
  6466. //===--- CHECK: Standard memory functions ---------------------------------===//
  6467. /// \brief Takes the expression passed to the size_t parameter of functions
  6468. /// such as memcmp, strncat, etc and warns if it's a comparison.
  6469. ///
  6470. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  6471. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  6472. IdentifierInfo *FnName,
  6473. SourceLocation FnLoc,
  6474. SourceLocation RParenLoc) {
  6475. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  6476. if (!Size)
  6477. return false;
  6478. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  6479. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  6480. return false;
  6481. SourceRange SizeRange = Size->getSourceRange();
  6482. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  6483. << SizeRange << FnName;
  6484. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  6485. << FnName << FixItHint::CreateInsertion(
  6486. S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
  6487. << FixItHint::CreateRemoval(RParenLoc);
  6488. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  6489. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  6490. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  6491. ")");
  6492. return true;
  6493. }
  6494. /// \brief Determine whether the given type is or contains a dynamic class type
  6495. /// (e.g., whether it has a vtable).
  6496. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  6497. bool &IsContained) {
  6498. // Look through array types while ignoring qualifiers.
  6499. const Type *Ty = T->getBaseElementTypeUnsafe();
  6500. IsContained = false;
  6501. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  6502. RD = RD ? RD->getDefinition() : nullptr;
  6503. if (!RD || RD->isInvalidDecl())
  6504. return nullptr;
  6505. if (RD->isDynamicClass())
  6506. return RD;
  6507. // Check all the fields. If any bases were dynamic, the class is dynamic.
  6508. // It's impossible for a class to transitively contain itself by value, so
  6509. // infinite recursion is impossible.
  6510. for (auto *FD : RD->fields()) {
  6511. bool SubContained;
  6512. if (const CXXRecordDecl *ContainedRD =
  6513. getContainedDynamicClass(FD->getType(), SubContained)) {
  6514. IsContained = true;
  6515. return ContainedRD;
  6516. }
  6517. }
  6518. return nullptr;
  6519. }
  6520. /// \brief If E is a sizeof expression, returns its argument expression,
  6521. /// otherwise returns NULL.
  6522. static const Expr *getSizeOfExprArg(const Expr *E) {
  6523. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  6524. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  6525. if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
  6526. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  6527. return nullptr;
  6528. }
  6529. /// \brief If E is a sizeof expression, returns its argument type.
  6530. static QualType getSizeOfArgType(const Expr *E) {
  6531. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  6532. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  6533. if (SizeOf->getKind() == UETT_SizeOf)
  6534. return SizeOf->getTypeOfArgument();
  6535. return QualType();
  6536. }
  6537. /// \brief Check for dangerous or invalid arguments to memset().
  6538. ///
  6539. /// This issues warnings on known problematic, dangerous or unspecified
  6540. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  6541. /// function calls.
  6542. ///
  6543. /// \param Call The call expression to diagnose.
  6544. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  6545. unsigned BId,
  6546. IdentifierInfo *FnName) {
  6547. assert(BId != 0);
  6548. // It is possible to have a non-standard definition of memset. Validate
  6549. // we have enough arguments, and if not, abort further checking.
  6550. unsigned ExpectedNumArgs =
  6551. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  6552. if (Call->getNumArgs() < ExpectedNumArgs)
  6553. return;
  6554. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  6555. BId == Builtin::BIstrndup ? 1 : 2);
  6556. unsigned LenArg =
  6557. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  6558. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  6559. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  6560. Call->getLocStart(), Call->getRParenLoc()))
  6561. return;
  6562. // We have special checking when the length is a sizeof expression.
  6563. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  6564. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  6565. llvm::FoldingSetNodeID SizeOfArgID;
  6566. // Although widely used, 'bzero' is not a standard function. Be more strict
  6567. // with the argument types before allowing diagnostics and only allow the
  6568. // form bzero(ptr, sizeof(...)).
  6569. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  6570. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  6571. return;
  6572. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  6573. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  6574. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  6575. QualType DestTy = Dest->getType();
  6576. QualType PointeeTy;
  6577. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  6578. PointeeTy = DestPtrTy->getPointeeType();
  6579. // Never warn about void type pointers. This can be used to suppress
  6580. // false positives.
  6581. if (PointeeTy->isVoidType())
  6582. continue;
  6583. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  6584. // actually comparing the expressions for equality. Because computing the
  6585. // expression IDs can be expensive, we only do this if the diagnostic is
  6586. // enabled.
  6587. if (SizeOfArg &&
  6588. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  6589. SizeOfArg->getExprLoc())) {
  6590. // We only compute IDs for expressions if the warning is enabled, and
  6591. // cache the sizeof arg's ID.
  6592. if (SizeOfArgID == llvm::FoldingSetNodeID())
  6593. SizeOfArg->Profile(SizeOfArgID, Context, true);
  6594. llvm::FoldingSetNodeID DestID;
  6595. Dest->Profile(DestID, Context, true);
  6596. if (DestID == SizeOfArgID) {
  6597. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  6598. // over sizeof(src) as well.
  6599. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  6600. StringRef ReadableName = FnName->getName();
  6601. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  6602. if (UnaryOp->getOpcode() == UO_AddrOf)
  6603. ActionIdx = 1; // If its an address-of operator, just remove it.
  6604. if (!PointeeTy->isIncompleteType() &&
  6605. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  6606. ActionIdx = 2; // If the pointee's size is sizeof(char),
  6607. // suggest an explicit length.
  6608. // If the function is defined as a builtin macro, do not show macro
  6609. // expansion.
  6610. SourceLocation SL = SizeOfArg->getExprLoc();
  6611. SourceRange DSR = Dest->getSourceRange();
  6612. SourceRange SSR = SizeOfArg->getSourceRange();
  6613. SourceManager &SM = getSourceManager();
  6614. if (SM.isMacroArgExpansion(SL)) {
  6615. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  6616. SL = SM.getSpellingLoc(SL);
  6617. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  6618. SM.getSpellingLoc(DSR.getEnd()));
  6619. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  6620. SM.getSpellingLoc(SSR.getEnd()));
  6621. }
  6622. DiagRuntimeBehavior(SL, SizeOfArg,
  6623. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  6624. << ReadableName
  6625. << PointeeTy
  6626. << DestTy
  6627. << DSR
  6628. << SSR);
  6629. DiagRuntimeBehavior(SL, SizeOfArg,
  6630. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  6631. << ActionIdx
  6632. << SSR);
  6633. break;
  6634. }
  6635. }
  6636. // Also check for cases where the sizeof argument is the exact same
  6637. // type as the memory argument, and where it points to a user-defined
  6638. // record type.
  6639. if (SizeOfArgTy != QualType()) {
  6640. if (PointeeTy->isRecordType() &&
  6641. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  6642. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  6643. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  6644. << FnName << SizeOfArgTy << ArgIdx
  6645. << PointeeTy << Dest->getSourceRange()
  6646. << LenExpr->getSourceRange());
  6647. break;
  6648. }
  6649. }
  6650. } else if (DestTy->isArrayType()) {
  6651. PointeeTy = DestTy;
  6652. }
  6653. if (PointeeTy == QualType())
  6654. continue;
  6655. // Always complain about dynamic classes.
  6656. bool IsContained;
  6657. if (const CXXRecordDecl *ContainedRD =
  6658. getContainedDynamicClass(PointeeTy, IsContained)) {
  6659. unsigned OperationType = 0;
  6660. // "overwritten" if we're warning about the destination for any call
  6661. // but memcmp; otherwise a verb appropriate to the call.
  6662. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  6663. if (BId == Builtin::BImemcpy)
  6664. OperationType = 1;
  6665. else if(BId == Builtin::BImemmove)
  6666. OperationType = 2;
  6667. else if (BId == Builtin::BImemcmp)
  6668. OperationType = 3;
  6669. }
  6670. DiagRuntimeBehavior(
  6671. Dest->getExprLoc(), Dest,
  6672. PDiag(diag::warn_dyn_class_memaccess)
  6673. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  6674. << FnName << IsContained << ContainedRD << OperationType
  6675. << Call->getCallee()->getSourceRange());
  6676. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  6677. BId != Builtin::BImemset)
  6678. DiagRuntimeBehavior(
  6679. Dest->getExprLoc(), Dest,
  6680. PDiag(diag::warn_arc_object_memaccess)
  6681. << ArgIdx << FnName << PointeeTy
  6682. << Call->getCallee()->getSourceRange());
  6683. else
  6684. continue;
  6685. DiagRuntimeBehavior(
  6686. Dest->getExprLoc(), Dest,
  6687. PDiag(diag::note_bad_memaccess_silence)
  6688. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  6689. break;
  6690. }
  6691. }
  6692. // A little helper routine: ignore addition and subtraction of integer literals.
  6693. // This intentionally does not ignore all integer constant expressions because
  6694. // we don't want to remove sizeof().
  6695. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  6696. Ex = Ex->IgnoreParenCasts();
  6697. while (true) {
  6698. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  6699. if (!BO || !BO->isAdditiveOp())
  6700. break;
  6701. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  6702. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  6703. if (isa<IntegerLiteral>(RHS))
  6704. Ex = LHS;
  6705. else if (isa<IntegerLiteral>(LHS))
  6706. Ex = RHS;
  6707. else
  6708. break;
  6709. }
  6710. return Ex;
  6711. }
  6712. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  6713. ASTContext &Context) {
  6714. // Only handle constant-sized or VLAs, but not flexible members.
  6715. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  6716. // Only issue the FIXIT for arrays of size > 1.
  6717. if (CAT->getSize().getSExtValue() <= 1)
  6718. return false;
  6719. } else if (!Ty->isVariableArrayType()) {
  6720. return false;
  6721. }
  6722. return true;
  6723. }
  6724. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  6725. // be the size of the source, instead of the destination.
  6726. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  6727. IdentifierInfo *FnName) {
  6728. // Don't crash if the user has the wrong number of arguments
  6729. unsigned NumArgs = Call->getNumArgs();
  6730. if ((NumArgs != 3) && (NumArgs != 4))
  6731. return;
  6732. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  6733. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  6734. const Expr *CompareWithSrc = nullptr;
  6735. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  6736. Call->getLocStart(), Call->getRParenLoc()))
  6737. return;
  6738. // Look for 'strlcpy(dst, x, sizeof(x))'
  6739. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  6740. CompareWithSrc = Ex;
  6741. else {
  6742. // Look for 'strlcpy(dst, x, strlen(x))'
  6743. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  6744. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  6745. SizeCall->getNumArgs() == 1)
  6746. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  6747. }
  6748. }
  6749. if (!CompareWithSrc)
  6750. return;
  6751. // Determine if the argument to sizeof/strlen is equal to the source
  6752. // argument. In principle there's all kinds of things you could do
  6753. // here, for instance creating an == expression and evaluating it with
  6754. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  6755. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  6756. if (!SrcArgDRE)
  6757. return;
  6758. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  6759. if (!CompareWithSrcDRE ||
  6760. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  6761. return;
  6762. const Expr *OriginalSizeArg = Call->getArg(2);
  6763. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  6764. << OriginalSizeArg->getSourceRange() << FnName;
  6765. // Output a FIXIT hint if the destination is an array (rather than a
  6766. // pointer to an array). This could be enhanced to handle some
  6767. // pointers if we know the actual size, like if DstArg is 'array+2'
  6768. // we could say 'sizeof(array)-2'.
  6769. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  6770. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  6771. return;
  6772. SmallString<128> sizeString;
  6773. llvm::raw_svector_ostream OS(sizeString);
  6774. OS << "sizeof(";
  6775. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  6776. OS << ")";
  6777. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  6778. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  6779. OS.str());
  6780. }
  6781. /// Check if two expressions refer to the same declaration.
  6782. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  6783. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  6784. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  6785. return D1->getDecl() == D2->getDecl();
  6786. return false;
  6787. }
  6788. static const Expr *getStrlenExprArg(const Expr *E) {
  6789. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  6790. const FunctionDecl *FD = CE->getDirectCallee();
  6791. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  6792. return nullptr;
  6793. return CE->getArg(0)->IgnoreParenCasts();
  6794. }
  6795. return nullptr;
  6796. }
  6797. // Warn on anti-patterns as the 'size' argument to strncat.
  6798. // The correct size argument should look like following:
  6799. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  6800. void Sema::CheckStrncatArguments(const CallExpr *CE,
  6801. IdentifierInfo *FnName) {
  6802. // Don't crash if the user has the wrong number of arguments.
  6803. if (CE->getNumArgs() < 3)
  6804. return;
  6805. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  6806. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  6807. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  6808. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
  6809. CE->getRParenLoc()))
  6810. return;
  6811. // Identify common expressions, which are wrongly used as the size argument
  6812. // to strncat and may lead to buffer overflows.
  6813. unsigned PatternType = 0;
  6814. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  6815. // - sizeof(dst)
  6816. if (referToTheSameDecl(SizeOfArg, DstArg))
  6817. PatternType = 1;
  6818. // - sizeof(src)
  6819. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  6820. PatternType = 2;
  6821. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  6822. if (BE->getOpcode() == BO_Sub) {
  6823. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  6824. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  6825. // - sizeof(dst) - strlen(dst)
  6826. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  6827. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  6828. PatternType = 1;
  6829. // - sizeof(src) - (anything)
  6830. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  6831. PatternType = 2;
  6832. }
  6833. }
  6834. if (PatternType == 0)
  6835. return;
  6836. // Generate the diagnostic.
  6837. SourceLocation SL = LenArg->getLocStart();
  6838. SourceRange SR = LenArg->getSourceRange();
  6839. SourceManager &SM = getSourceManager();
  6840. // If the function is defined as a builtin macro, do not show macro expansion.
  6841. if (SM.isMacroArgExpansion(SL)) {
  6842. SL = SM.getSpellingLoc(SL);
  6843. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  6844. SM.getSpellingLoc(SR.getEnd()));
  6845. }
  6846. // Check if the destination is an array (rather than a pointer to an array).
  6847. QualType DstTy = DstArg->getType();
  6848. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  6849. Context);
  6850. if (!isKnownSizeArray) {
  6851. if (PatternType == 1)
  6852. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  6853. else
  6854. Diag(SL, diag::warn_strncat_src_size) << SR;
  6855. return;
  6856. }
  6857. if (PatternType == 1)
  6858. Diag(SL, diag::warn_strncat_large_size) << SR;
  6859. else
  6860. Diag(SL, diag::warn_strncat_src_size) << SR;
  6861. SmallString<128> sizeString;
  6862. llvm::raw_svector_ostream OS(sizeString);
  6863. OS << "sizeof(";
  6864. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  6865. OS << ") - ";
  6866. OS << "strlen(";
  6867. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  6868. OS << ") - 1";
  6869. Diag(SL, diag::note_strncat_wrong_size)
  6870. << FixItHint::CreateReplacement(SR, OS.str());
  6871. }
  6872. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  6873. static const Expr *EvalVal(const Expr *E,
  6874. SmallVectorImpl<const DeclRefExpr *> &refVars,
  6875. const Decl *ParentDecl);
  6876. static const Expr *EvalAddr(const Expr *E,
  6877. SmallVectorImpl<const DeclRefExpr *> &refVars,
  6878. const Decl *ParentDecl);
  6879. /// CheckReturnStackAddr - Check if a return statement returns the address
  6880. /// of a stack variable.
  6881. static void
  6882. CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
  6883. SourceLocation ReturnLoc) {
  6884. const Expr *stackE = nullptr;
  6885. SmallVector<const DeclRefExpr *, 8> refVars;
  6886. // Perform checking for returned stack addresses, local blocks,
  6887. // label addresses or references to temporaries.
  6888. if (lhsType->isPointerType() ||
  6889. (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  6890. stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
  6891. } else if (lhsType->isReferenceType()) {
  6892. stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
  6893. }
  6894. if (!stackE)
  6895. return; // Nothing suspicious was found.
  6896. // Parameters are initialized in the calling scope, so taking the address
  6897. // of a parameter reference doesn't need a warning.
  6898. for (auto *DRE : refVars)
  6899. if (isa<ParmVarDecl>(DRE->getDecl()))
  6900. return;
  6901. SourceLocation diagLoc;
  6902. SourceRange diagRange;
  6903. if (refVars.empty()) {
  6904. diagLoc = stackE->getLocStart();
  6905. diagRange = stackE->getSourceRange();
  6906. } else {
  6907. // We followed through a reference variable. 'stackE' contains the
  6908. // problematic expression but we will warn at the return statement pointing
  6909. // at the reference variable. We will later display the "trail" of
  6910. // reference variables using notes.
  6911. diagLoc = refVars[0]->getLocStart();
  6912. diagRange = refVars[0]->getSourceRange();
  6913. }
  6914. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
  6915. // address of local var
  6916. S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
  6917. << DR->getDecl()->getDeclName() << diagRange;
  6918. } else if (isa<BlockExpr>(stackE)) { // local block.
  6919. S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  6920. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  6921. S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  6922. } else { // local temporary.
  6923. // If there is an LValue->RValue conversion, then the value of the
  6924. // reference type is used, not the reference.
  6925. if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
  6926. if (ICE->getCastKind() == CK_LValueToRValue) {
  6927. return;
  6928. }
  6929. }
  6930. S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
  6931. << lhsType->isReferenceType() << diagRange;
  6932. }
  6933. // Display the "trail" of reference variables that we followed until we
  6934. // found the problematic expression using notes.
  6935. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  6936. const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  6937. // If this var binds to another reference var, show the range of the next
  6938. // var, otherwise the var binds to the problematic expression, in which case
  6939. // show the range of the expression.
  6940. SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
  6941. : stackE->getSourceRange();
  6942. S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  6943. << VD->getDeclName() << range;
  6944. }
  6945. }
  6946. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  6947. /// check if the expression in a return statement evaluates to an address
  6948. /// to a location on the stack, a local block, an address of a label, or a
  6949. /// reference to local temporary. The recursion is used to traverse the
  6950. /// AST of the return expression, with recursion backtracking when we
  6951. /// encounter a subexpression that (1) clearly does not lead to one of the
  6952. /// above problematic expressions (2) is something we cannot determine leads to
  6953. /// a problematic expression based on such local checking.
  6954. ///
  6955. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  6956. /// the expression that they point to. Such variables are added to the
  6957. /// 'refVars' vector so that we know what the reference variable "trail" was.
  6958. ///
  6959. /// EvalAddr processes expressions that are pointers that are used as
  6960. /// references (and not L-values). EvalVal handles all other values.
  6961. /// At the base case of the recursion is a check for the above problematic
  6962. /// expressions.
  6963. ///
  6964. /// This implementation handles:
  6965. ///
  6966. /// * pointer-to-pointer casts
  6967. /// * implicit conversions from array references to pointers
  6968. /// * taking the address of fields
  6969. /// * arbitrary interplay between "&" and "*" operators
  6970. /// * pointer arithmetic from an address of a stack variable
  6971. /// * taking the address of an array element where the array is on the stack
  6972. static const Expr *EvalAddr(const Expr *E,
  6973. SmallVectorImpl<const DeclRefExpr *> &refVars,
  6974. const Decl *ParentDecl) {
  6975. if (E->isTypeDependent())
  6976. return nullptr;
  6977. // We should only be called for evaluating pointer expressions.
  6978. assert((E->getType()->isAnyPointerType() ||
  6979. E->getType()->isBlockPointerType() ||
  6980. E->getType()->isObjCQualifiedIdType()) &&
  6981. "EvalAddr only works on pointers");
  6982. E = E->IgnoreParens();
  6983. // Our "symbolic interpreter" is just a dispatch off the currently
  6984. // viewed AST node. We then recursively traverse the AST by calling
  6985. // EvalAddr and EvalVal appropriately.
  6986. switch (E->getStmtClass()) {
  6987. case Stmt::DeclRefExprClass: {
  6988. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  6989. // If we leave the immediate function, the lifetime isn't about to end.
  6990. if (DR->refersToEnclosingVariableOrCapture())
  6991. return nullptr;
  6992. if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  6993. // If this is a reference variable, follow through to the expression that
  6994. // it points to.
  6995. if (V->hasLocalStorage() &&
  6996. V->getType()->isReferenceType() && V->hasInit()) {
  6997. // Add the reference variable to the "trail".
  6998. refVars.push_back(DR);
  6999. return EvalAddr(V->getInit(), refVars, ParentDecl);
  7000. }
  7001. return nullptr;
  7002. }
  7003. case Stmt::UnaryOperatorClass: {
  7004. // The only unary operator that make sense to handle here
  7005. // is AddrOf. All others don't make sense as pointers.
  7006. const UnaryOperator *U = cast<UnaryOperator>(E);
  7007. if (U->getOpcode() == UO_AddrOf)
  7008. return EvalVal(U->getSubExpr(), refVars, ParentDecl);
  7009. return nullptr;
  7010. }
  7011. case Stmt::BinaryOperatorClass: {
  7012. // Handle pointer arithmetic. All other binary operators are not valid
  7013. // in this context.
  7014. const BinaryOperator *B = cast<BinaryOperator>(E);
  7015. BinaryOperatorKind op = B->getOpcode();
  7016. if (op != BO_Add && op != BO_Sub)
  7017. return nullptr;
  7018. const Expr *Base = B->getLHS();
  7019. // Determine which argument is the real pointer base. It could be
  7020. // the RHS argument instead of the LHS.
  7021. if (!Base->getType()->isPointerType())
  7022. Base = B->getRHS();
  7023. assert(Base->getType()->isPointerType());
  7024. return EvalAddr(Base, refVars, ParentDecl);
  7025. }
  7026. // For conditional operators we need to see if either the LHS or RHS are
  7027. // valid DeclRefExpr*s. If one of them is valid, we return it.
  7028. case Stmt::ConditionalOperatorClass: {
  7029. const ConditionalOperator *C = cast<ConditionalOperator>(E);
  7030. // Handle the GNU extension for missing LHS.
  7031. // FIXME: That isn't a ConditionalOperator, so doesn't get here.
  7032. if (const Expr *LHSExpr = C->getLHS()) {
  7033. // In C++, we can have a throw-expression, which has 'void' type.
  7034. if (!LHSExpr->getType()->isVoidType())
  7035. if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
  7036. return LHS;
  7037. }
  7038. // In C++, we can have a throw-expression, which has 'void' type.
  7039. if (C->getRHS()->getType()->isVoidType())
  7040. return nullptr;
  7041. return EvalAddr(C->getRHS(), refVars, ParentDecl);
  7042. }
  7043. case Stmt::BlockExprClass:
  7044. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  7045. return E; // local block.
  7046. return nullptr;
  7047. case Stmt::AddrLabelExprClass:
  7048. return E; // address of label.
  7049. case Stmt::ExprWithCleanupsClass:
  7050. return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  7051. ParentDecl);
  7052. // For casts, we need to handle conversions from arrays to
  7053. // pointer values, and pointer-to-pointer conversions.
  7054. case Stmt::ImplicitCastExprClass:
  7055. case Stmt::CStyleCastExprClass:
  7056. case Stmt::CXXFunctionalCastExprClass:
  7057. case Stmt::ObjCBridgedCastExprClass:
  7058. case Stmt::CXXStaticCastExprClass:
  7059. case Stmt::CXXDynamicCastExprClass:
  7060. case Stmt::CXXConstCastExprClass:
  7061. case Stmt::CXXReinterpretCastExprClass: {
  7062. const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  7063. switch (cast<CastExpr>(E)->getCastKind()) {
  7064. case CK_LValueToRValue:
  7065. case CK_NoOp:
  7066. case CK_BaseToDerived:
  7067. case CK_DerivedToBase:
  7068. case CK_UncheckedDerivedToBase:
  7069. case CK_Dynamic:
  7070. case CK_CPointerToObjCPointerCast:
  7071. case CK_BlockPointerToObjCPointerCast:
  7072. case CK_AnyPointerToBlockPointerCast:
  7073. return EvalAddr(SubExpr, refVars, ParentDecl);
  7074. case CK_ArrayToPointerDecay:
  7075. return EvalVal(SubExpr, refVars, ParentDecl);
  7076. case CK_BitCast:
  7077. if (SubExpr->getType()->isAnyPointerType() ||
  7078. SubExpr->getType()->isBlockPointerType() ||
  7079. SubExpr->getType()->isObjCQualifiedIdType())
  7080. return EvalAddr(SubExpr, refVars, ParentDecl);
  7081. else
  7082. return nullptr;
  7083. default:
  7084. return nullptr;
  7085. }
  7086. }
  7087. case Stmt::MaterializeTemporaryExprClass:
  7088. if (const Expr *Result =
  7089. EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  7090. refVars, ParentDecl))
  7091. return Result;
  7092. return E;
  7093. // Everything else: we simply don't reason about them.
  7094. default:
  7095. return nullptr;
  7096. }
  7097. }
  7098. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  7099. /// See the comments for EvalAddr for more details.
  7100. static const Expr *EvalVal(const Expr *E,
  7101. SmallVectorImpl<const DeclRefExpr *> &refVars,
  7102. const Decl *ParentDecl) {
  7103. do {
  7104. // We should only be called for evaluating non-pointer expressions, or
  7105. // expressions with a pointer type that are not used as references but
  7106. // instead
  7107. // are l-values (e.g., DeclRefExpr with a pointer type).
  7108. // Our "symbolic interpreter" is just a dispatch off the currently
  7109. // viewed AST node. We then recursively traverse the AST by calling
  7110. // EvalAddr and EvalVal appropriately.
  7111. E = E->IgnoreParens();
  7112. switch (E->getStmtClass()) {
  7113. case Stmt::ImplicitCastExprClass: {
  7114. const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  7115. if (IE->getValueKind() == VK_LValue) {
  7116. E = IE->getSubExpr();
  7117. continue;
  7118. }
  7119. return nullptr;
  7120. }
  7121. case Stmt::ExprWithCleanupsClass:
  7122. return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  7123. ParentDecl);
  7124. case Stmt::DeclRefExprClass: {
  7125. // When we hit a DeclRefExpr we are looking at code that refers to a
  7126. // variable's name. If it's not a reference variable we check if it has
  7127. // local storage within the function, and if so, return the expression.
  7128. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  7129. // If we leave the immediate function, the lifetime isn't about to end.
  7130. if (DR->refersToEnclosingVariableOrCapture())
  7131. return nullptr;
  7132. if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
  7133. // Check if it refers to itself, e.g. "int& i = i;".
  7134. if (V == ParentDecl)
  7135. return DR;
  7136. if (V->hasLocalStorage()) {
  7137. if (!V->getType()->isReferenceType())
  7138. return DR;
  7139. // Reference variable, follow through to the expression that
  7140. // it points to.
  7141. if (V->hasInit()) {
  7142. // Add the reference variable to the "trail".
  7143. refVars.push_back(DR);
  7144. return EvalVal(V->getInit(), refVars, V);
  7145. }
  7146. }
  7147. }
  7148. return nullptr;
  7149. }
  7150. case Stmt::UnaryOperatorClass: {
  7151. // The only unary operator that make sense to handle here
  7152. // is Deref. All others don't resolve to a "name." This includes
  7153. // handling all sorts of rvalues passed to a unary operator.
  7154. const UnaryOperator *U = cast<UnaryOperator>(E);
  7155. if (U->getOpcode() == UO_Deref)
  7156. return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
  7157. return nullptr;
  7158. }
  7159. case Stmt::ArraySubscriptExprClass: {
  7160. // Array subscripts are potential references to data on the stack. We
  7161. // retrieve the DeclRefExpr* for the array variable if it indeed
  7162. // has local storage.
  7163. const auto *ASE = cast<ArraySubscriptExpr>(E);
  7164. if (ASE->isTypeDependent())
  7165. return nullptr;
  7166. return EvalAddr(ASE->getBase(), refVars, ParentDecl);
  7167. }
  7168. case Stmt::OMPArraySectionExprClass: {
  7169. return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
  7170. ParentDecl);
  7171. }
  7172. case Stmt::ConditionalOperatorClass: {
  7173. // For conditional operators we need to see if either the LHS or RHS are
  7174. // non-NULL Expr's. If one is non-NULL, we return it.
  7175. const ConditionalOperator *C = cast<ConditionalOperator>(E);
  7176. // Handle the GNU extension for missing LHS.
  7177. if (const Expr *LHSExpr = C->getLHS()) {
  7178. // In C++, we can have a throw-expression, which has 'void' type.
  7179. if (!LHSExpr->getType()->isVoidType())
  7180. if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
  7181. return LHS;
  7182. }
  7183. // In C++, we can have a throw-expression, which has 'void' type.
  7184. if (C->getRHS()->getType()->isVoidType())
  7185. return nullptr;
  7186. return EvalVal(C->getRHS(), refVars, ParentDecl);
  7187. }
  7188. // Accesses to members are potential references to data on the stack.
  7189. case Stmt::MemberExprClass: {
  7190. const MemberExpr *M = cast<MemberExpr>(E);
  7191. // Check for indirect access. We only want direct field accesses.
  7192. if (M->isArrow())
  7193. return nullptr;
  7194. // Check whether the member type is itself a reference, in which case
  7195. // we're not going to refer to the member, but to what the member refers
  7196. // to.
  7197. if (M->getMemberDecl()->getType()->isReferenceType())
  7198. return nullptr;
  7199. return EvalVal(M->getBase(), refVars, ParentDecl);
  7200. }
  7201. case Stmt::MaterializeTemporaryExprClass:
  7202. if (const Expr *Result =
  7203. EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  7204. refVars, ParentDecl))
  7205. return Result;
  7206. return E;
  7207. default:
  7208. // Check that we don't return or take the address of a reference to a
  7209. // temporary. This is only useful in C++.
  7210. if (!E->isTypeDependent() && E->isRValue())
  7211. return E;
  7212. // Everything else: we simply don't reason about them.
  7213. return nullptr;
  7214. }
  7215. } while (true);
  7216. }
  7217. void
  7218. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  7219. SourceLocation ReturnLoc,
  7220. bool isObjCMethod,
  7221. const AttrVec *Attrs,
  7222. const FunctionDecl *FD) {
  7223. CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
  7224. // Check if the return value is null but should not be.
  7225. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  7226. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  7227. CheckNonNullExpr(*this, RetValExp))
  7228. Diag(ReturnLoc, diag::warn_null_ret)
  7229. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  7230. // C++11 [basic.stc.dynamic.allocation]p4:
  7231. // If an allocation function declared with a non-throwing
  7232. // exception-specification fails to allocate storage, it shall return
  7233. // a null pointer. Any other allocation function that fails to allocate
  7234. // storage shall indicate failure only by throwing an exception [...]
  7235. if (FD) {
  7236. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  7237. if (Op == OO_New || Op == OO_Array_New) {
  7238. const FunctionProtoType *Proto
  7239. = FD->getType()->castAs<FunctionProtoType>();
  7240. if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
  7241. CheckNonNullExpr(*this, RetValExp))
  7242. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  7243. << FD << getLangOpts().CPlusPlus11;
  7244. }
  7245. }
  7246. }
  7247. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  7248. /// Check for comparisons of floating point operands using != and ==.
  7249. /// Issue a warning if these are no self-comparisons, as they are not likely
  7250. /// to do what the programmer intended.
  7251. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  7252. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  7253. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  7254. // Special case: check for x == x (which is OK).
  7255. // Do not emit warnings for such cases.
  7256. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  7257. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  7258. if (DRL->getDecl() == DRR->getDecl())
  7259. return;
  7260. // Special case: check for comparisons against literals that can be exactly
  7261. // represented by APFloat. In such cases, do not emit a warning. This
  7262. // is a heuristic: often comparison against such literals are used to
  7263. // detect if a value in a variable has not changed. This clearly can
  7264. // lead to false negatives.
  7265. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  7266. if (FLL->isExact())
  7267. return;
  7268. } else
  7269. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  7270. if (FLR->isExact())
  7271. return;
  7272. // Check for comparisons with builtin types.
  7273. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  7274. if (CL->getBuiltinCallee())
  7275. return;
  7276. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  7277. if (CR->getBuiltinCallee())
  7278. return;
  7279. // Emit the diagnostic.
  7280. Diag(Loc, diag::warn_floatingpoint_eq)
  7281. << LHS->getSourceRange() << RHS->getSourceRange();
  7282. }
  7283. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  7284. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  7285. namespace {
  7286. /// Structure recording the 'active' range of an integer-valued
  7287. /// expression.
  7288. struct IntRange {
  7289. /// The number of bits active in the int.
  7290. unsigned Width;
  7291. /// True if the int is known not to have negative values.
  7292. bool NonNegative;
  7293. IntRange(unsigned Width, bool NonNegative)
  7294. : Width(Width), NonNegative(NonNegative) {}
  7295. /// Returns the range of the bool type.
  7296. static IntRange forBoolType() {
  7297. return IntRange(1, true);
  7298. }
  7299. /// Returns the range of an opaque value of the given integral type.
  7300. static IntRange forValueOfType(ASTContext &C, QualType T) {
  7301. return forValueOfCanonicalType(C,
  7302. T->getCanonicalTypeInternal().getTypePtr());
  7303. }
  7304. /// Returns the range of an opaque value of a canonical integral type.
  7305. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  7306. assert(T->isCanonicalUnqualified());
  7307. if (const VectorType *VT = dyn_cast<VectorType>(T))
  7308. T = VT->getElementType().getTypePtr();
  7309. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  7310. T = CT->getElementType().getTypePtr();
  7311. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  7312. T = AT->getValueType().getTypePtr();
  7313. if (!C.getLangOpts().CPlusPlus) {
  7314. // For enum types in C code, use the underlying datatype.
  7315. if (const EnumType *ET = dyn_cast<EnumType>(T))
  7316. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  7317. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  7318. // For enum types in C++, use the known bit width of the enumerators.
  7319. EnumDecl *Enum = ET->getDecl();
  7320. // In C++11, enums can have a fixed underlying type. Use this type to
  7321. // compute the range.
  7322. if (Enum->isFixed()) {
  7323. return IntRange(C.getIntWidth(QualType(T, 0)),
  7324. !ET->isSignedIntegerOrEnumerationType());
  7325. }
  7326. unsigned NumPositive = Enum->getNumPositiveBits();
  7327. unsigned NumNegative = Enum->getNumNegativeBits();
  7328. if (NumNegative == 0)
  7329. return IntRange(NumPositive, true/*NonNegative*/);
  7330. else
  7331. return IntRange(std::max(NumPositive + 1, NumNegative),
  7332. false/*NonNegative*/);
  7333. }
  7334. const BuiltinType *BT = cast<BuiltinType>(T);
  7335. assert(BT->isInteger());
  7336. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  7337. }
  7338. /// Returns the "target" range of a canonical integral type, i.e.
  7339. /// the range of values expressible in the type.
  7340. ///
  7341. /// This matches forValueOfCanonicalType except that enums have the
  7342. /// full range of their type, not the range of their enumerators.
  7343. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  7344. assert(T->isCanonicalUnqualified());
  7345. if (const VectorType *VT = dyn_cast<VectorType>(T))
  7346. T = VT->getElementType().getTypePtr();
  7347. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  7348. T = CT->getElementType().getTypePtr();
  7349. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  7350. T = AT->getValueType().getTypePtr();
  7351. if (const EnumType *ET = dyn_cast<EnumType>(T))
  7352. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  7353. const BuiltinType *BT = cast<BuiltinType>(T);
  7354. assert(BT->isInteger());
  7355. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  7356. }
  7357. /// Returns the supremum of two ranges: i.e. their conservative merge.
  7358. static IntRange join(IntRange L, IntRange R) {
  7359. return IntRange(std::max(L.Width, R.Width),
  7360. L.NonNegative && R.NonNegative);
  7361. }
  7362. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  7363. static IntRange meet(IntRange L, IntRange R) {
  7364. return IntRange(std::min(L.Width, R.Width),
  7365. L.NonNegative || R.NonNegative);
  7366. }
  7367. };
  7368. } // namespace
  7369. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  7370. unsigned MaxWidth) {
  7371. if (value.isSigned() && value.isNegative())
  7372. return IntRange(value.getMinSignedBits(), false);
  7373. if (value.getBitWidth() > MaxWidth)
  7374. value = value.trunc(MaxWidth);
  7375. // isNonNegative() just checks the sign bit without considering
  7376. // signedness.
  7377. return IntRange(value.getActiveBits(), true);
  7378. }
  7379. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  7380. unsigned MaxWidth) {
  7381. if (result.isInt())
  7382. return GetValueRange(C, result.getInt(), MaxWidth);
  7383. if (result.isVector()) {
  7384. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  7385. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  7386. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  7387. R = IntRange::join(R, El);
  7388. }
  7389. return R;
  7390. }
  7391. if (result.isComplexInt()) {
  7392. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  7393. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  7394. return IntRange::join(R, I);
  7395. }
  7396. // This can happen with lossless casts to intptr_t of "based" lvalues.
  7397. // Assume it might use arbitrary bits.
  7398. // FIXME: The only reason we need to pass the type in here is to get
  7399. // the sign right on this one case. It would be nice if APValue
  7400. // preserved this.
  7401. assert(result.isLValue() || result.isAddrLabelDiff());
  7402. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  7403. }
  7404. static QualType GetExprType(const Expr *E) {
  7405. QualType Ty = E->getType();
  7406. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  7407. Ty = AtomicRHS->getValueType();
  7408. return Ty;
  7409. }
  7410. /// Pseudo-evaluate the given integer expression, estimating the
  7411. /// range of values it might take.
  7412. ///
  7413. /// \param MaxWidth - the width to which the value will be truncated
  7414. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
  7415. E = E->IgnoreParens();
  7416. // Try a full evaluation first.
  7417. Expr::EvalResult result;
  7418. if (E->EvaluateAsRValue(result, C))
  7419. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  7420. // I think we only want to look through implicit casts here; if the
  7421. // user has an explicit widening cast, we should treat the value as
  7422. // being of the new, wider type.
  7423. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  7424. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  7425. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  7426. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  7427. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  7428. CE->getCastKind() == CK_BooleanToSignedIntegral;
  7429. // Assume that non-integer casts can span the full range of the type.
  7430. if (!isIntegerCast)
  7431. return OutputTypeRange;
  7432. IntRange SubRange
  7433. = GetExprRange(C, CE->getSubExpr(),
  7434. std::min(MaxWidth, OutputTypeRange.Width));
  7435. // Bail out if the subexpr's range is as wide as the cast type.
  7436. if (SubRange.Width >= OutputTypeRange.Width)
  7437. return OutputTypeRange;
  7438. // Otherwise, we take the smaller width, and we're non-negative if
  7439. // either the output type or the subexpr is.
  7440. return IntRange(SubRange.Width,
  7441. SubRange.NonNegative || OutputTypeRange.NonNegative);
  7442. }
  7443. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  7444. // If we can fold the condition, just take that operand.
  7445. bool CondResult;
  7446. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  7447. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  7448. : CO->getFalseExpr(),
  7449. MaxWidth);
  7450. // Otherwise, conservatively merge.
  7451. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  7452. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  7453. return IntRange::join(L, R);
  7454. }
  7455. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  7456. switch (BO->getOpcode()) {
  7457. case BO_Cmp:
  7458. llvm_unreachable("builtin <=> should have class type");
  7459. // Boolean-valued operations are single-bit and positive.
  7460. case BO_LAnd:
  7461. case BO_LOr:
  7462. case BO_LT:
  7463. case BO_GT:
  7464. case BO_LE:
  7465. case BO_GE:
  7466. case BO_EQ:
  7467. case BO_NE:
  7468. return IntRange::forBoolType();
  7469. // The type of the assignments is the type of the LHS, so the RHS
  7470. // is not necessarily the same type.
  7471. case BO_MulAssign:
  7472. case BO_DivAssign:
  7473. case BO_RemAssign:
  7474. case BO_AddAssign:
  7475. case BO_SubAssign:
  7476. case BO_XorAssign:
  7477. case BO_OrAssign:
  7478. // TODO: bitfields?
  7479. return IntRange::forValueOfType(C, GetExprType(E));
  7480. // Simple assignments just pass through the RHS, which will have
  7481. // been coerced to the LHS type.
  7482. case BO_Assign:
  7483. // TODO: bitfields?
  7484. return GetExprRange(C, BO->getRHS(), MaxWidth);
  7485. // Operations with opaque sources are black-listed.
  7486. case BO_PtrMemD:
  7487. case BO_PtrMemI:
  7488. return IntRange::forValueOfType(C, GetExprType(E));
  7489. // Bitwise-and uses the *infinum* of the two source ranges.
  7490. case BO_And:
  7491. case BO_AndAssign:
  7492. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  7493. GetExprRange(C, BO->getRHS(), MaxWidth));
  7494. // Left shift gets black-listed based on a judgement call.
  7495. case BO_Shl:
  7496. // ...except that we want to treat '1 << (blah)' as logically
  7497. // positive. It's an important idiom.
  7498. if (IntegerLiteral *I
  7499. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  7500. if (I->getValue() == 1) {
  7501. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  7502. return IntRange(R.Width, /*NonNegative*/ true);
  7503. }
  7504. }
  7505. // fallthrough
  7506. case BO_ShlAssign:
  7507. return IntRange::forValueOfType(C, GetExprType(E));
  7508. // Right shift by a constant can narrow its left argument.
  7509. case BO_Shr:
  7510. case BO_ShrAssign: {
  7511. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  7512. // If the shift amount is a positive constant, drop the width by
  7513. // that much.
  7514. llvm::APSInt shift;
  7515. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  7516. shift.isNonNegative()) {
  7517. unsigned zext = shift.getZExtValue();
  7518. if (zext >= L.Width)
  7519. L.Width = (L.NonNegative ? 0 : 1);
  7520. else
  7521. L.Width -= zext;
  7522. }
  7523. return L;
  7524. }
  7525. // Comma acts as its right operand.
  7526. case BO_Comma:
  7527. return GetExprRange(C, BO->getRHS(), MaxWidth);
  7528. // Black-list pointer subtractions.
  7529. case BO_Sub:
  7530. if (BO->getLHS()->getType()->isPointerType())
  7531. return IntRange::forValueOfType(C, GetExprType(E));
  7532. break;
  7533. // The width of a division result is mostly determined by the size
  7534. // of the LHS.
  7535. case BO_Div: {
  7536. // Don't 'pre-truncate' the operands.
  7537. unsigned opWidth = C.getIntWidth(GetExprType(E));
  7538. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  7539. // If the divisor is constant, use that.
  7540. llvm::APSInt divisor;
  7541. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  7542. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  7543. if (log2 >= L.Width)
  7544. L.Width = (L.NonNegative ? 0 : 1);
  7545. else
  7546. L.Width = std::min(L.Width - log2, MaxWidth);
  7547. return L;
  7548. }
  7549. // Otherwise, just use the LHS's width.
  7550. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  7551. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  7552. }
  7553. // The result of a remainder can't be larger than the result of
  7554. // either side.
  7555. case BO_Rem: {
  7556. // Don't 'pre-truncate' the operands.
  7557. unsigned opWidth = C.getIntWidth(GetExprType(E));
  7558. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  7559. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  7560. IntRange meet = IntRange::meet(L, R);
  7561. meet.Width = std::min(meet.Width, MaxWidth);
  7562. return meet;
  7563. }
  7564. // The default behavior is okay for these.
  7565. case BO_Mul:
  7566. case BO_Add:
  7567. case BO_Xor:
  7568. case BO_Or:
  7569. break;
  7570. }
  7571. // The default case is to treat the operation as if it were closed
  7572. // on the narrowest type that encompasses both operands.
  7573. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  7574. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  7575. return IntRange::join(L, R);
  7576. }
  7577. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  7578. switch (UO->getOpcode()) {
  7579. // Boolean-valued operations are white-listed.
  7580. case UO_LNot:
  7581. return IntRange::forBoolType();
  7582. // Operations with opaque sources are black-listed.
  7583. case UO_Deref:
  7584. case UO_AddrOf: // should be impossible
  7585. return IntRange::forValueOfType(C, GetExprType(E));
  7586. default:
  7587. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  7588. }
  7589. }
  7590. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  7591. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
  7592. if (const auto *BitField = E->getSourceBitField())
  7593. return IntRange(BitField->getBitWidthValue(C),
  7594. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  7595. return IntRange::forValueOfType(C, GetExprType(E));
  7596. }
  7597. static IntRange GetExprRange(ASTContext &C, const Expr *E) {
  7598. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
  7599. }
  7600. /// Checks whether the given value, which currently has the given
  7601. /// source semantics, has the same value when coerced through the
  7602. /// target semantics.
  7603. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  7604. const llvm::fltSemantics &Src,
  7605. const llvm::fltSemantics &Tgt) {
  7606. llvm::APFloat truncated = value;
  7607. bool ignored;
  7608. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  7609. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  7610. return truncated.bitwiseIsEqual(value);
  7611. }
  7612. /// Checks whether the given value, which currently has the given
  7613. /// source semantics, has the same value when coerced through the
  7614. /// target semantics.
  7615. ///
  7616. /// The value might be a vector of floats (or a complex number).
  7617. static bool IsSameFloatAfterCast(const APValue &value,
  7618. const llvm::fltSemantics &Src,
  7619. const llvm::fltSemantics &Tgt) {
  7620. if (value.isFloat())
  7621. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  7622. if (value.isVector()) {
  7623. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  7624. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  7625. return false;
  7626. return true;
  7627. }
  7628. assert(value.isComplexFloat());
  7629. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  7630. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  7631. }
  7632. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  7633. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  7634. // Suppress cases where we are comparing against an enum constant.
  7635. if (const DeclRefExpr *DR =
  7636. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  7637. if (isa<EnumConstantDecl>(DR->getDecl()))
  7638. return true;
  7639. // Suppress cases where the '0' value is expanded from a macro.
  7640. if (E->getLocStart().isMacroID())
  7641. return true;
  7642. return false;
  7643. }
  7644. static bool isKnownToHaveUnsignedValue(Expr *E) {
  7645. return E->getType()->isIntegerType() &&
  7646. (!E->getType()->isSignedIntegerType() ||
  7647. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  7648. }
  7649. namespace {
  7650. /// The promoted range of values of a type. In general this has the
  7651. /// following structure:
  7652. ///
  7653. /// |-----------| . . . |-----------|
  7654. /// ^ ^ ^ ^
  7655. /// Min HoleMin HoleMax Max
  7656. ///
  7657. /// ... where there is only a hole if a signed type is promoted to unsigned
  7658. /// (in which case Min and Max are the smallest and largest representable
  7659. /// values).
  7660. struct PromotedRange {
  7661. // Min, or HoleMax if there is a hole.
  7662. llvm::APSInt PromotedMin;
  7663. // Max, or HoleMin if there is a hole.
  7664. llvm::APSInt PromotedMax;
  7665. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  7666. if (R.Width == 0)
  7667. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  7668. else if (R.Width >= BitWidth && !Unsigned) {
  7669. // Promotion made the type *narrower*. This happens when promoting
  7670. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  7671. // Treat all values of 'signed int' as being in range for now.
  7672. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  7673. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  7674. } else {
  7675. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  7676. .extOrTrunc(BitWidth);
  7677. PromotedMin.setIsUnsigned(Unsigned);
  7678. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  7679. .extOrTrunc(BitWidth);
  7680. PromotedMax.setIsUnsigned(Unsigned);
  7681. }
  7682. }
  7683. // Determine whether this range is contiguous (has no hole).
  7684. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  7685. // Where a constant value is within the range.
  7686. enum ComparisonResult {
  7687. LT = 0x1,
  7688. LE = 0x2,
  7689. GT = 0x4,
  7690. GE = 0x8,
  7691. EQ = 0x10,
  7692. NE = 0x20,
  7693. InRangeFlag = 0x40,
  7694. Less = LE | LT | NE,
  7695. Min = LE | InRangeFlag,
  7696. InRange = InRangeFlag,
  7697. Max = GE | InRangeFlag,
  7698. Greater = GE | GT | NE,
  7699. OnlyValue = LE | GE | EQ | InRangeFlag,
  7700. InHole = NE
  7701. };
  7702. ComparisonResult compare(const llvm::APSInt &Value) const {
  7703. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  7704. Value.isUnsigned() == PromotedMin.isUnsigned());
  7705. if (!isContiguous()) {
  7706. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  7707. if (Value.isMinValue()) return Min;
  7708. if (Value.isMaxValue()) return Max;
  7709. if (Value >= PromotedMin) return InRange;
  7710. if (Value <= PromotedMax) return InRange;
  7711. return InHole;
  7712. }
  7713. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  7714. case -1: return Less;
  7715. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  7716. case 1:
  7717. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  7718. case -1: return InRange;
  7719. case 0: return Max;
  7720. case 1: return Greater;
  7721. }
  7722. }
  7723. llvm_unreachable("impossible compare result");
  7724. }
  7725. static llvm::Optional<StringRef>
  7726. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  7727. if (Op == BO_Cmp) {
  7728. ComparisonResult LTFlag = LT, GTFlag = GT;
  7729. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  7730. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  7731. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  7732. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  7733. return llvm::None;
  7734. }
  7735. ComparisonResult TrueFlag, FalseFlag;
  7736. if (Op == BO_EQ) {
  7737. TrueFlag = EQ;
  7738. FalseFlag = NE;
  7739. } else if (Op == BO_NE) {
  7740. TrueFlag = NE;
  7741. FalseFlag = EQ;
  7742. } else {
  7743. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  7744. TrueFlag = LT;
  7745. FalseFlag = GE;
  7746. } else {
  7747. TrueFlag = GT;
  7748. FalseFlag = LE;
  7749. }
  7750. if (Op == BO_GE || Op == BO_LE)
  7751. std::swap(TrueFlag, FalseFlag);
  7752. }
  7753. if (R & TrueFlag)
  7754. return StringRef("true");
  7755. if (R & FalseFlag)
  7756. return StringRef("false");
  7757. return llvm::None;
  7758. }
  7759. };
  7760. }
  7761. static bool HasEnumType(Expr *E) {
  7762. // Strip off implicit integral promotions.
  7763. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  7764. if (ICE->getCastKind() != CK_IntegralCast &&
  7765. ICE->getCastKind() != CK_NoOp)
  7766. break;
  7767. E = ICE->getSubExpr();
  7768. }
  7769. return E->getType()->isEnumeralType();
  7770. }
  7771. static int classifyConstantValue(Expr *Constant) {
  7772. // The values of this enumeration are used in the diagnostics
  7773. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  7774. enum ConstantValueKind {
  7775. Miscellaneous = 0,
  7776. LiteralTrue,
  7777. LiteralFalse
  7778. };
  7779. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  7780. return BL->getValue() ? ConstantValueKind::LiteralTrue
  7781. : ConstantValueKind::LiteralFalse;
  7782. return ConstantValueKind::Miscellaneous;
  7783. }
  7784. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  7785. Expr *Constant, Expr *Other,
  7786. const llvm::APSInt &Value,
  7787. bool RhsConstant) {
  7788. if (S.inTemplateInstantiation())
  7789. return false;
  7790. Expr *OriginalOther = Other;
  7791. Constant = Constant->IgnoreParenImpCasts();
  7792. Other = Other->IgnoreParenImpCasts();
  7793. // Suppress warnings on tautological comparisons between values of the same
  7794. // enumeration type. There are only two ways we could warn on this:
  7795. // - If the constant is outside the range of representable values of
  7796. // the enumeration. In such a case, we should warn about the cast
  7797. // to enumeration type, not about the comparison.
  7798. // - If the constant is the maximum / minimum in-range value. For an
  7799. // enumeratin type, such comparisons can be meaningful and useful.
  7800. if (Constant->getType()->isEnumeralType() &&
  7801. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  7802. return false;
  7803. // TODO: Investigate using GetExprRange() to get tighter bounds
  7804. // on the bit ranges.
  7805. QualType OtherT = Other->getType();
  7806. if (const auto *AT = OtherT->getAs<AtomicType>())
  7807. OtherT = AT->getValueType();
  7808. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  7809. // Whether we're treating Other as being a bool because of the form of
  7810. // expression despite it having another type (typically 'int' in C).
  7811. bool OtherIsBooleanDespiteType =
  7812. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  7813. if (OtherIsBooleanDespiteType)
  7814. OtherRange = IntRange::forBoolType();
  7815. // Determine the promoted range of the other type and see if a comparison of
  7816. // the constant against that range is tautological.
  7817. PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
  7818. Value.isUnsigned());
  7819. auto Cmp = OtherPromotedRange.compare(Value);
  7820. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  7821. if (!Result)
  7822. return false;
  7823. // Suppress the diagnostic for an in-range comparison if the constant comes
  7824. // from a macro or enumerator. We don't want to diagnose
  7825. //
  7826. // some_long_value <= INT_MAX
  7827. //
  7828. // when sizeof(int) == sizeof(long).
  7829. bool InRange = Cmp & PromotedRange::InRangeFlag;
  7830. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  7831. return false;
  7832. // If this is a comparison to an enum constant, include that
  7833. // constant in the diagnostic.
  7834. const EnumConstantDecl *ED = nullptr;
  7835. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  7836. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  7837. // Should be enough for uint128 (39 decimal digits)
  7838. SmallString<64> PrettySourceValue;
  7839. llvm::raw_svector_ostream OS(PrettySourceValue);
  7840. if (ED)
  7841. OS << '\'' << *ED << "' (" << Value << ")";
  7842. else
  7843. OS << Value;
  7844. // FIXME: We use a somewhat different formatting for the in-range cases and
  7845. // cases involving boolean values for historical reasons. We should pick a
  7846. // consistent way of presenting these diagnostics.
  7847. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  7848. S.DiagRuntimeBehavior(
  7849. E->getOperatorLoc(), E,
  7850. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  7851. : diag::warn_tautological_bool_compare)
  7852. << OS.str() << classifyConstantValue(Constant)
  7853. << OtherT << OtherIsBooleanDespiteType << *Result
  7854. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  7855. } else {
  7856. unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  7857. ? (HasEnumType(OriginalOther)
  7858. ? diag::warn_unsigned_enum_always_true_comparison
  7859. : diag::warn_unsigned_always_true_comparison)
  7860. : diag::warn_tautological_constant_compare;
  7861. S.Diag(E->getOperatorLoc(), Diag)
  7862. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  7863. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  7864. }
  7865. return true;
  7866. }
  7867. /// Analyze the operands of the given comparison. Implements the
  7868. /// fallback case from AnalyzeComparison.
  7869. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  7870. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  7871. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  7872. }
  7873. /// \brief Implements -Wsign-compare.
  7874. ///
  7875. /// \param E the binary operator to check for warnings
  7876. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  7877. // The type the comparison is being performed in.
  7878. QualType T = E->getLHS()->getType();
  7879. // Only analyze comparison operators where both sides have been converted to
  7880. // the same type.
  7881. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  7882. return AnalyzeImpConvsInComparison(S, E);
  7883. // Don't analyze value-dependent comparisons directly.
  7884. if (E->isValueDependent())
  7885. return AnalyzeImpConvsInComparison(S, E);
  7886. Expr *LHS = E->getLHS();
  7887. Expr *RHS = E->getRHS();
  7888. if (T->isIntegralType(S.Context)) {
  7889. llvm::APSInt RHSValue;
  7890. llvm::APSInt LHSValue;
  7891. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  7892. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  7893. // We don't care about expressions whose result is a constant.
  7894. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  7895. return AnalyzeImpConvsInComparison(S, E);
  7896. // We only care about expressions where just one side is literal
  7897. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  7898. // Is the constant on the RHS or LHS?
  7899. const bool RhsConstant = IsRHSIntegralLiteral;
  7900. Expr *Const = RhsConstant ? RHS : LHS;
  7901. Expr *Other = RhsConstant ? LHS : RHS;
  7902. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  7903. // Check whether an integer constant comparison results in a value
  7904. // of 'true' or 'false'.
  7905. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  7906. return AnalyzeImpConvsInComparison(S, E);
  7907. }
  7908. }
  7909. if (!T->hasUnsignedIntegerRepresentation()) {
  7910. // We don't do anything special if this isn't an unsigned integral
  7911. // comparison: we're only interested in integral comparisons, and
  7912. // signed comparisons only happen in cases we don't care to warn about.
  7913. return AnalyzeImpConvsInComparison(S, E);
  7914. }
  7915. LHS = LHS->IgnoreParenImpCasts();
  7916. RHS = RHS->IgnoreParenImpCasts();
  7917. // Check to see if one of the (unmodified) operands is of different
  7918. // signedness.
  7919. Expr *signedOperand, *unsignedOperand;
  7920. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  7921. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  7922. "unsigned comparison between two signed integer expressions?");
  7923. signedOperand = LHS;
  7924. unsignedOperand = RHS;
  7925. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  7926. signedOperand = RHS;
  7927. unsignedOperand = LHS;
  7928. } else {
  7929. return AnalyzeImpConvsInComparison(S, E);
  7930. }
  7931. // Otherwise, calculate the effective range of the signed operand.
  7932. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  7933. // Go ahead and analyze implicit conversions in the operands. Note
  7934. // that we skip the implicit conversions on both sides.
  7935. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  7936. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  7937. // If the signed range is non-negative, -Wsign-compare won't fire.
  7938. if (signedRange.NonNegative)
  7939. return;
  7940. // For (in)equality comparisons, if the unsigned operand is a
  7941. // constant which cannot collide with a overflowed signed operand,
  7942. // then reinterpreting the signed operand as unsigned will not
  7943. // change the result of the comparison.
  7944. if (E->isEqualityOp()) {
  7945. unsigned comparisonWidth = S.Context.getIntWidth(T);
  7946. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  7947. // We should never be unable to prove that the unsigned operand is
  7948. // non-negative.
  7949. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  7950. if (unsignedRange.Width < comparisonWidth)
  7951. return;
  7952. }
  7953. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  7954. S.PDiag(diag::warn_mixed_sign_comparison)
  7955. << LHS->getType() << RHS->getType()
  7956. << LHS->getSourceRange() << RHS->getSourceRange());
  7957. }
  7958. /// Analyzes an attempt to assign the given value to a bitfield.
  7959. ///
  7960. /// Returns true if there was something fishy about the attempt.
  7961. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  7962. SourceLocation InitLoc) {
  7963. assert(Bitfield->isBitField());
  7964. if (Bitfield->isInvalidDecl())
  7965. return false;
  7966. // White-list bool bitfields.
  7967. QualType BitfieldType = Bitfield->getType();
  7968. if (BitfieldType->isBooleanType())
  7969. return false;
  7970. if (BitfieldType->isEnumeralType()) {
  7971. EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
  7972. // If the underlying enum type was not explicitly specified as an unsigned
  7973. // type and the enum contain only positive values, MSVC++ will cause an
  7974. // inconsistency by storing this as a signed type.
  7975. if (S.getLangOpts().CPlusPlus11 &&
  7976. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  7977. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  7978. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  7979. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  7980. << BitfieldEnumDecl->getNameAsString();
  7981. }
  7982. }
  7983. if (Bitfield->getType()->isBooleanType())
  7984. return false;
  7985. // Ignore value- or type-dependent expressions.
  7986. if (Bitfield->getBitWidth()->isValueDependent() ||
  7987. Bitfield->getBitWidth()->isTypeDependent() ||
  7988. Init->isValueDependent() ||
  7989. Init->isTypeDependent())
  7990. return false;
  7991. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  7992. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  7993. llvm::APSInt Value;
  7994. if (!OriginalInit->EvaluateAsInt(Value, S.Context,
  7995. Expr::SE_AllowSideEffects)) {
  7996. // The RHS is not constant. If the RHS has an enum type, make sure the
  7997. // bitfield is wide enough to hold all the values of the enum without
  7998. // truncation.
  7999. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  8000. EnumDecl *ED = EnumTy->getDecl();
  8001. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  8002. // Enum types are implicitly signed on Windows, so check if there are any
  8003. // negative enumerators to see if the enum was intended to be signed or
  8004. // not.
  8005. bool SignedEnum = ED->getNumNegativeBits() > 0;
  8006. // Check for surprising sign changes when assigning enum values to a
  8007. // bitfield of different signedness. If the bitfield is signed and we
  8008. // have exactly the right number of bits to store this unsigned enum,
  8009. // suggest changing the enum to an unsigned type. This typically happens
  8010. // on Windows where unfixed enums always use an underlying type of 'int'.
  8011. unsigned DiagID = 0;
  8012. if (SignedEnum && !SignedBitfield) {
  8013. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  8014. } else if (SignedBitfield && !SignedEnum &&
  8015. ED->getNumPositiveBits() == FieldWidth) {
  8016. DiagID = diag::warn_signed_bitfield_enum_conversion;
  8017. }
  8018. if (DiagID) {
  8019. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  8020. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  8021. SourceRange TypeRange =
  8022. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  8023. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  8024. << SignedEnum << TypeRange;
  8025. }
  8026. // Compute the required bitwidth. If the enum has negative values, we need
  8027. // one more bit than the normal number of positive bits to represent the
  8028. // sign bit.
  8029. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  8030. ED->getNumNegativeBits())
  8031. : ED->getNumPositiveBits();
  8032. // Check the bitwidth.
  8033. if (BitsNeeded > FieldWidth) {
  8034. Expr *WidthExpr = Bitfield->getBitWidth();
  8035. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  8036. << Bitfield << ED;
  8037. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  8038. << BitsNeeded << ED << WidthExpr->getSourceRange();
  8039. }
  8040. }
  8041. return false;
  8042. }
  8043. unsigned OriginalWidth = Value.getBitWidth();
  8044. if (!Value.isSigned() || Value.isNegative())
  8045. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  8046. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  8047. OriginalWidth = Value.getMinSignedBits();
  8048. if (OriginalWidth <= FieldWidth)
  8049. return false;
  8050. // Compute the value which the bitfield will contain.
  8051. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  8052. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  8053. // Check whether the stored value is equal to the original value.
  8054. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  8055. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  8056. return false;
  8057. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  8058. // therefore don't strictly fit into a signed bitfield of width 1.
  8059. if (FieldWidth == 1 && Value == 1)
  8060. return false;
  8061. std::string PrettyValue = Value.toString(10);
  8062. std::string PrettyTrunc = TruncatedValue.toString(10);
  8063. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  8064. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  8065. << Init->getSourceRange();
  8066. return true;
  8067. }
  8068. /// Analyze the given simple or compound assignment for warning-worthy
  8069. /// operations.
  8070. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  8071. // Just recurse on the LHS.
  8072. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  8073. // We want to recurse on the RHS as normal unless we're assigning to
  8074. // a bitfield.
  8075. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  8076. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  8077. E->getOperatorLoc())) {
  8078. // Recurse, ignoring any implicit conversions on the RHS.
  8079. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  8080. E->getOperatorLoc());
  8081. }
  8082. }
  8083. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  8084. }
  8085. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  8086. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  8087. SourceLocation CContext, unsigned diag,
  8088. bool pruneControlFlow = false) {
  8089. if (pruneControlFlow) {
  8090. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  8091. S.PDiag(diag)
  8092. << SourceType << T << E->getSourceRange()
  8093. << SourceRange(CContext));
  8094. return;
  8095. }
  8096. S.Diag(E->getExprLoc(), diag)
  8097. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  8098. }
  8099. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  8100. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  8101. 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. static 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. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  8188. IntRange Range) {
  8189. if (!Range.Width) return "0";
  8190. llvm::APSInt ValueInRange = Value;
  8191. ValueInRange.setIsSigned(!Range.NonNegative);
  8192. ValueInRange = ValueInRange.trunc(Range.Width);
  8193. return ValueInRange.toString(10);
  8194. }
  8195. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  8196. if (!isa<ImplicitCastExpr>(Ex))
  8197. return false;
  8198. Expr *InnerE = Ex->IgnoreParenImpCasts();
  8199. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  8200. const Type *Source =
  8201. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  8202. if (Target->isDependentType())
  8203. return false;
  8204. const BuiltinType *FloatCandidateBT =
  8205. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  8206. const Type *BoolCandidateType = ToBool ? Target : Source;
  8207. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  8208. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  8209. }
  8210. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  8211. SourceLocation CC) {
  8212. unsigned NumArgs = TheCall->getNumArgs();
  8213. for (unsigned i = 0; i < NumArgs; ++i) {
  8214. Expr *CurrA = TheCall->getArg(i);
  8215. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  8216. continue;
  8217. bool IsSwapped = ((i > 0) &&
  8218. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  8219. IsSwapped |= ((i < (NumArgs - 1)) &&
  8220. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  8221. if (IsSwapped) {
  8222. // Warn on this floating-point to bool conversion.
  8223. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  8224. CurrA->getType(), CC,
  8225. diag::warn_impcast_floating_point_to_bool);
  8226. }
  8227. }
  8228. }
  8229. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  8230. SourceLocation CC) {
  8231. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  8232. E->getExprLoc()))
  8233. return;
  8234. // Don't warn on functions which have return type nullptr_t.
  8235. if (isa<CallExpr>(E))
  8236. return;
  8237. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  8238. const Expr::NullPointerConstantKind NullKind =
  8239. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  8240. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  8241. return;
  8242. // Return if target type is a safe conversion.
  8243. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  8244. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  8245. return;
  8246. SourceLocation Loc = E->getSourceRange().getBegin();
  8247. // Venture through the macro stacks to get to the source of macro arguments.
  8248. // The new location is a better location than the complete location that was
  8249. // passed in.
  8250. while (S.SourceMgr.isMacroArgExpansion(Loc))
  8251. Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
  8252. while (S.SourceMgr.isMacroArgExpansion(CC))
  8253. CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
  8254. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  8255. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  8256. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  8257. Loc, S.SourceMgr, S.getLangOpts());
  8258. if (MacroName == "NULL")
  8259. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
  8260. }
  8261. // Only warn if the null and context location are in the same macro expansion.
  8262. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  8263. return;
  8264. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  8265. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  8266. << FixItHint::CreateReplacement(Loc,
  8267. S.getFixItZeroLiteralForType(T, Loc));
  8268. }
  8269. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  8270. ObjCArrayLiteral *ArrayLiteral);
  8271. static void
  8272. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  8273. ObjCDictionaryLiteral *DictionaryLiteral);
  8274. /// Check a single element within a collection literal against the
  8275. /// target element type.
  8276. static void checkObjCCollectionLiteralElement(Sema &S,
  8277. QualType TargetElementType,
  8278. Expr *Element,
  8279. unsigned ElementKind) {
  8280. // Skip a bitcast to 'id' or qualified 'id'.
  8281. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  8282. if (ICE->getCastKind() == CK_BitCast &&
  8283. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  8284. Element = ICE->getSubExpr();
  8285. }
  8286. QualType ElementType = Element->getType();
  8287. ExprResult ElementResult(Element);
  8288. if (ElementType->getAs<ObjCObjectPointerType>() &&
  8289. S.CheckSingleAssignmentConstraints(TargetElementType,
  8290. ElementResult,
  8291. false, false)
  8292. != Sema::Compatible) {
  8293. S.Diag(Element->getLocStart(),
  8294. diag::warn_objc_collection_literal_element)
  8295. << ElementType << ElementKind << TargetElementType
  8296. << Element->getSourceRange();
  8297. }
  8298. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  8299. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  8300. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  8301. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  8302. }
  8303. /// Check an Objective-C array literal being converted to the given
  8304. /// target type.
  8305. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  8306. ObjCArrayLiteral *ArrayLiteral) {
  8307. if (!S.NSArrayDecl)
  8308. return;
  8309. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  8310. if (!TargetObjCPtr)
  8311. return;
  8312. if (TargetObjCPtr->isUnspecialized() ||
  8313. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  8314. != S.NSArrayDecl->getCanonicalDecl())
  8315. return;
  8316. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  8317. if (TypeArgs.size() != 1)
  8318. return;
  8319. QualType TargetElementType = TypeArgs[0];
  8320. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  8321. checkObjCCollectionLiteralElement(S, TargetElementType,
  8322. ArrayLiteral->getElement(I),
  8323. 0);
  8324. }
  8325. }
  8326. /// Check an Objective-C dictionary literal being converted to the given
  8327. /// target type.
  8328. static void
  8329. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  8330. ObjCDictionaryLiteral *DictionaryLiteral) {
  8331. if (!S.NSDictionaryDecl)
  8332. return;
  8333. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  8334. if (!TargetObjCPtr)
  8335. return;
  8336. if (TargetObjCPtr->isUnspecialized() ||
  8337. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  8338. != S.NSDictionaryDecl->getCanonicalDecl())
  8339. return;
  8340. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  8341. if (TypeArgs.size() != 2)
  8342. return;
  8343. QualType TargetKeyType = TypeArgs[0];
  8344. QualType TargetObjectType = TypeArgs[1];
  8345. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  8346. auto Element = DictionaryLiteral->getKeyValueElement(I);
  8347. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  8348. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  8349. }
  8350. }
  8351. // Helper function to filter out cases for constant width constant conversion.
  8352. // Don't warn on char array initialization or for non-decimal values.
  8353. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  8354. SourceLocation CC) {
  8355. // If initializing from a constant, and the constant starts with '0',
  8356. // then it is a binary, octal, or hexadecimal. Allow these constants
  8357. // to fill all the bits, even if there is a sign change.
  8358. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  8359. const char FirstLiteralCharacter =
  8360. S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
  8361. if (FirstLiteralCharacter == '0')
  8362. return false;
  8363. }
  8364. // If the CC location points to a '{', and the type is char, then assume
  8365. // assume it is an array initialization.
  8366. if (CC.isValid() && T->isCharType()) {
  8367. const char FirstContextCharacter =
  8368. S.getSourceManager().getCharacterData(CC)[0];
  8369. if (FirstContextCharacter == '{')
  8370. return false;
  8371. }
  8372. return true;
  8373. }
  8374. static void
  8375. CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
  8376. bool *ICContext = nullptr) {
  8377. if (E->isTypeDependent() || E->isValueDependent()) return;
  8378. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  8379. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  8380. if (Source == Target) return;
  8381. if (Target->isDependentType()) return;
  8382. // If the conversion context location is invalid don't complain. We also
  8383. // don't want to emit a warning if the issue occurs from the expansion of
  8384. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  8385. // delay this check as long as possible. Once we detect we are in that
  8386. // scenario, we just return.
  8387. if (CC.isInvalid())
  8388. return;
  8389. // Diagnose implicit casts to bool.
  8390. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  8391. if (isa<StringLiteral>(E))
  8392. // Warn on string literal to bool. Checks for string literals in logical
  8393. // and expressions, for instance, assert(0 && "error here"), are
  8394. // prevented by a check in AnalyzeImplicitConversions().
  8395. return DiagnoseImpCast(S, E, T, CC,
  8396. diag::warn_impcast_string_literal_to_bool);
  8397. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  8398. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  8399. // This covers the literal expressions that evaluate to Objective-C
  8400. // objects.
  8401. return DiagnoseImpCast(S, E, T, CC,
  8402. diag::warn_impcast_objective_c_literal_to_bool);
  8403. }
  8404. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  8405. // Warn on pointer to bool conversion that is always true.
  8406. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  8407. SourceRange(CC));
  8408. }
  8409. }
  8410. // Check implicit casts from Objective-C collection literals to specialized
  8411. // collection types, e.g., NSArray<NSString *> *.
  8412. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  8413. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  8414. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  8415. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  8416. // Strip vector types.
  8417. if (isa<VectorType>(Source)) {
  8418. if (!isa<VectorType>(Target)) {
  8419. if (S.SourceMgr.isInSystemMacro(CC))
  8420. return;
  8421. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  8422. }
  8423. // If the vector cast is cast between two vectors of the same size, it is
  8424. // a bitcast, not a conversion.
  8425. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  8426. return;
  8427. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  8428. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  8429. }
  8430. if (auto VecTy = dyn_cast<VectorType>(Target))
  8431. Target = VecTy->getElementType().getTypePtr();
  8432. // Strip complex types.
  8433. if (isa<ComplexType>(Source)) {
  8434. if (!isa<ComplexType>(Target)) {
  8435. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  8436. return;
  8437. return DiagnoseImpCast(S, E, T, CC,
  8438. S.getLangOpts().CPlusPlus
  8439. ? diag::err_impcast_complex_scalar
  8440. : diag::warn_impcast_complex_scalar);
  8441. }
  8442. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  8443. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  8444. }
  8445. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  8446. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  8447. // If the source is floating point...
  8448. if (SourceBT && SourceBT->isFloatingPoint()) {
  8449. // ...and the target is floating point...
  8450. if (TargetBT && TargetBT->isFloatingPoint()) {
  8451. // ...then warn if we're dropping FP rank.
  8452. // Builtin FP kinds are ordered by increasing FP rank.
  8453. if (SourceBT->getKind() > TargetBT->getKind()) {
  8454. // Don't warn about float constants that are precisely
  8455. // representable in the target type.
  8456. Expr::EvalResult result;
  8457. if (E->EvaluateAsRValue(result, S.Context)) {
  8458. // Value might be a float, a float vector, or a float complex.
  8459. if (IsSameFloatAfterCast(result.Val,
  8460. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  8461. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  8462. return;
  8463. }
  8464. if (S.SourceMgr.isInSystemMacro(CC))
  8465. return;
  8466. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  8467. }
  8468. // ... or possibly if we're increasing rank, too
  8469. else if (TargetBT->getKind() > SourceBT->getKind()) {
  8470. if (S.SourceMgr.isInSystemMacro(CC))
  8471. return;
  8472. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  8473. }
  8474. return;
  8475. }
  8476. // If the target is integral, always warn.
  8477. if (TargetBT && TargetBT->isInteger()) {
  8478. if (S.SourceMgr.isInSystemMacro(CC))
  8479. return;
  8480. DiagnoseFloatingImpCast(S, E, T, CC);
  8481. }
  8482. // Detect the case where a call result is converted from floating-point to
  8483. // to bool, and the final argument to the call is converted from bool, to
  8484. // discover this typo:
  8485. //
  8486. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  8487. //
  8488. // FIXME: This is an incredibly special case; is there some more general
  8489. // way to detect this class of misplaced-parentheses bug?
  8490. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  8491. // Check last argument of function call to see if it is an
  8492. // implicit cast from a type matching the type the result
  8493. // is being cast to.
  8494. CallExpr *CEx = cast<CallExpr>(E);
  8495. if (unsigned NumArgs = CEx->getNumArgs()) {
  8496. Expr *LastA = CEx->getArg(NumArgs - 1);
  8497. Expr *InnerE = LastA->IgnoreParenImpCasts();
  8498. if (isa<ImplicitCastExpr>(LastA) &&
  8499. InnerE->getType()->isBooleanType()) {
  8500. // Warn on this floating-point to bool conversion
  8501. DiagnoseImpCast(S, E, T, CC,
  8502. diag::warn_impcast_floating_point_to_bool);
  8503. }
  8504. }
  8505. }
  8506. return;
  8507. }
  8508. DiagnoseNullConversion(S, E, T, CC);
  8509. S.DiscardMisalignedMemberAddress(Target, E);
  8510. if (!Source->isIntegerType() || !Target->isIntegerType())
  8511. return;
  8512. // TODO: remove this early return once the false positives for constant->bool
  8513. // in templates, macros, etc, are reduced or removed.
  8514. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  8515. return;
  8516. IntRange SourceRange = GetExprRange(S.Context, E);
  8517. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  8518. if (SourceRange.Width > TargetRange.Width) {
  8519. // If the source is a constant, use a default-on diagnostic.
  8520. // TODO: this should happen for bitfield stores, too.
  8521. llvm::APSInt Value(32);
  8522. if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
  8523. if (S.SourceMgr.isInSystemMacro(CC))
  8524. return;
  8525. std::string PrettySourceValue = Value.toString(10);
  8526. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  8527. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  8528. S.PDiag(diag::warn_impcast_integer_precision_constant)
  8529. << PrettySourceValue << PrettyTargetValue
  8530. << E->getType() << T << E->getSourceRange()
  8531. << clang::SourceRange(CC));
  8532. return;
  8533. }
  8534. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  8535. if (S.SourceMgr.isInSystemMacro(CC))
  8536. return;
  8537. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  8538. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  8539. /* pruneControlFlow */ true);
  8540. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  8541. }
  8542. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  8543. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  8544. // Warn when doing a signed to signed conversion, warn if the positive
  8545. // source value is exactly the width of the target type, which will
  8546. // cause a negative value to be stored.
  8547. llvm::APSInt Value;
  8548. if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
  8549. !S.SourceMgr.isInSystemMacro(CC)) {
  8550. if (isSameWidthConstantConversion(S, E, T, CC)) {
  8551. std::string PrettySourceValue = Value.toString(10);
  8552. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  8553. S.DiagRuntimeBehavior(
  8554. E->getExprLoc(), E,
  8555. S.PDiag(diag::warn_impcast_integer_precision_constant)
  8556. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  8557. << E->getSourceRange() << clang::SourceRange(CC));
  8558. return;
  8559. }
  8560. }
  8561. // Fall through for non-constants to give a sign conversion warning.
  8562. }
  8563. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  8564. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  8565. SourceRange.Width == TargetRange.Width)) {
  8566. if (S.SourceMgr.isInSystemMacro(CC))
  8567. return;
  8568. unsigned DiagID = diag::warn_impcast_integer_sign;
  8569. // Traditionally, gcc has warned about this under -Wsign-compare.
  8570. // We also want to warn about it in -Wconversion.
  8571. // So if -Wconversion is off, use a completely identical diagnostic
  8572. // in the sign-compare group.
  8573. // The conditional-checking code will
  8574. if (ICContext) {
  8575. DiagID = diag::warn_impcast_integer_sign_conditional;
  8576. *ICContext = true;
  8577. }
  8578. return DiagnoseImpCast(S, E, T, CC, DiagID);
  8579. }
  8580. // Diagnose conversions between different enumeration types.
  8581. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  8582. // type, to give us better diagnostics.
  8583. QualType SourceType = E->getType();
  8584. if (!S.getLangOpts().CPlusPlus) {
  8585. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  8586. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  8587. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  8588. SourceType = S.Context.getTypeDeclType(Enum);
  8589. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  8590. }
  8591. }
  8592. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  8593. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  8594. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  8595. TargetEnum->getDecl()->hasNameForLinkage() &&
  8596. SourceEnum != TargetEnum) {
  8597. if (S.SourceMgr.isInSystemMacro(CC))
  8598. return;
  8599. return DiagnoseImpCast(S, E, SourceType, T, CC,
  8600. diag::warn_impcast_different_enum_types);
  8601. }
  8602. }
  8603. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  8604. SourceLocation CC, QualType T);
  8605. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  8606. SourceLocation CC, bool &ICContext) {
  8607. E = E->IgnoreParenImpCasts();
  8608. if (isa<ConditionalOperator>(E))
  8609. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  8610. AnalyzeImplicitConversions(S, E, CC);
  8611. if (E->getType() != T)
  8612. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  8613. }
  8614. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  8615. SourceLocation CC, QualType T) {
  8616. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  8617. bool Suspicious = false;
  8618. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  8619. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  8620. // If -Wconversion would have warned about either of the candidates
  8621. // for a signedness conversion to the context type...
  8622. if (!Suspicious) return;
  8623. // ...but it's currently ignored...
  8624. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  8625. return;
  8626. // ...then check whether it would have warned about either of the
  8627. // candidates for a signedness conversion to the condition type.
  8628. if (E->getType() == T) return;
  8629. Suspicious = false;
  8630. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  8631. E->getType(), CC, &Suspicious);
  8632. if (!Suspicious)
  8633. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  8634. E->getType(), CC, &Suspicious);
  8635. }
  8636. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  8637. /// Input argument E is a logical expression.
  8638. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  8639. if (S.getLangOpts().Bool)
  8640. return;
  8641. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  8642. }
  8643. /// AnalyzeImplicitConversions - Find and report any interesting
  8644. /// implicit conversions in the given expression. There are a couple
  8645. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  8646. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
  8647. SourceLocation CC) {
  8648. QualType T = OrigE->getType();
  8649. Expr *E = OrigE->IgnoreParenImpCasts();
  8650. if (E->isTypeDependent() || E->isValueDependent())
  8651. return;
  8652. // For conditional operators, we analyze the arguments as if they
  8653. // were being fed directly into the output.
  8654. if (isa<ConditionalOperator>(E)) {
  8655. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  8656. CheckConditionalOperator(S, CO, CC, T);
  8657. return;
  8658. }
  8659. // Check implicit argument conversions for function calls.
  8660. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  8661. CheckImplicitArgumentConversions(S, Call, CC);
  8662. // Go ahead and check any implicit conversions we might have skipped.
  8663. // The non-canonical typecheck is just an optimization;
  8664. // CheckImplicitConversion will filter out dead implicit conversions.
  8665. if (E->getType() != T)
  8666. CheckImplicitConversion(S, E, T, CC);
  8667. // Now continue drilling into this expression.
  8668. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  8669. // The bound subexpressions in a PseudoObjectExpr are not reachable
  8670. // as transitive children.
  8671. // FIXME: Use a more uniform representation for this.
  8672. for (auto *SE : POE->semantics())
  8673. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  8674. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  8675. }
  8676. // Skip past explicit casts.
  8677. if (isa<ExplicitCastExpr>(E)) {
  8678. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  8679. return AnalyzeImplicitConversions(S, E, CC);
  8680. }
  8681. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  8682. // Do a somewhat different check with comparison operators.
  8683. if (BO->isComparisonOp())
  8684. return AnalyzeComparison(S, BO);
  8685. // And with simple assignments.
  8686. if (BO->getOpcode() == BO_Assign)
  8687. return AnalyzeAssignment(S, BO);
  8688. }
  8689. // These break the otherwise-useful invariant below. Fortunately,
  8690. // we don't really need to recurse into them, because any internal
  8691. // expressions should have been analyzed already when they were
  8692. // built into statements.
  8693. if (isa<StmtExpr>(E)) return;
  8694. // Don't descend into unevaluated contexts.
  8695. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  8696. // Now just recurse over the expression's children.
  8697. CC = E->getExprLoc();
  8698. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  8699. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  8700. for (Stmt *SubStmt : E->children()) {
  8701. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  8702. if (!ChildExpr)
  8703. continue;
  8704. if (IsLogicalAndOperator &&
  8705. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  8706. // Ignore checking string literals that are in logical and operators.
  8707. // This is a common pattern for asserts.
  8708. continue;
  8709. AnalyzeImplicitConversions(S, ChildExpr, CC);
  8710. }
  8711. if (BO && BO->isLogicalOp()) {
  8712. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  8713. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  8714. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  8715. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  8716. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  8717. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  8718. }
  8719. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
  8720. if (U->getOpcode() == UO_LNot)
  8721. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  8722. }
  8723. /// Diagnose integer type and any valid implicit convertion to it.
  8724. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  8725. // Taking into account implicit conversions,
  8726. // allow any integer.
  8727. if (!E->getType()->isIntegerType()) {
  8728. S.Diag(E->getLocStart(),
  8729. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  8730. return true;
  8731. }
  8732. // Potentially emit standard warnings for implicit conversions if enabled
  8733. // using -Wconversion.
  8734. CheckImplicitConversion(S, E, IntT, E->getLocStart());
  8735. return false;
  8736. }
  8737. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  8738. // Returns true when emitting a warning about taking the address of a reference.
  8739. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  8740. const PartialDiagnostic &PD) {
  8741. E = E->IgnoreParenImpCasts();
  8742. const FunctionDecl *FD = nullptr;
  8743. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  8744. if (!DRE->getDecl()->getType()->isReferenceType())
  8745. return false;
  8746. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  8747. if (!M->getMemberDecl()->getType()->isReferenceType())
  8748. return false;
  8749. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  8750. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  8751. return false;
  8752. FD = Call->getDirectCallee();
  8753. } else {
  8754. return false;
  8755. }
  8756. SemaRef.Diag(E->getExprLoc(), PD);
  8757. // If possible, point to location of function.
  8758. if (FD) {
  8759. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  8760. }
  8761. return true;
  8762. }
  8763. // Returns true if the SourceLocation is expanded from any macro body.
  8764. // Returns false if the SourceLocation is invalid, is from not in a macro
  8765. // expansion, or is from expanded from a top-level macro argument.
  8766. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  8767. if (Loc.isInvalid())
  8768. return false;
  8769. while (Loc.isMacroID()) {
  8770. if (SM.isMacroBodyExpansion(Loc))
  8771. return true;
  8772. Loc = SM.getImmediateMacroCallerLoc(Loc);
  8773. }
  8774. return false;
  8775. }
  8776. /// \brief Diagnose pointers that are always non-null.
  8777. /// \param E the expression containing the pointer
  8778. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  8779. /// compared to a null pointer
  8780. /// \param IsEqual True when the comparison is equal to a null pointer
  8781. /// \param Range Extra SourceRange to highlight in the diagnostic
  8782. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  8783. Expr::NullPointerConstantKind NullKind,
  8784. bool IsEqual, SourceRange Range) {
  8785. if (!E)
  8786. return;
  8787. // Don't warn inside macros.
  8788. if (E->getExprLoc().isMacroID()) {
  8789. const SourceManager &SM = getSourceManager();
  8790. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  8791. IsInAnyMacroBody(SM, Range.getBegin()))
  8792. return;
  8793. }
  8794. E = E->IgnoreImpCasts();
  8795. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  8796. if (isa<CXXThisExpr>(E)) {
  8797. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  8798. : diag::warn_this_bool_conversion;
  8799. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  8800. return;
  8801. }
  8802. bool IsAddressOf = false;
  8803. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  8804. if (UO->getOpcode() != UO_AddrOf)
  8805. return;
  8806. IsAddressOf = true;
  8807. E = UO->getSubExpr();
  8808. }
  8809. if (IsAddressOf) {
  8810. unsigned DiagID = IsCompare
  8811. ? diag::warn_address_of_reference_null_compare
  8812. : diag::warn_address_of_reference_bool_conversion;
  8813. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  8814. << IsEqual;
  8815. if (CheckForReference(*this, E, PD)) {
  8816. return;
  8817. }
  8818. }
  8819. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  8820. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  8821. std::string Str;
  8822. llvm::raw_string_ostream S(Str);
  8823. E->printPretty(S, nullptr, getPrintingPolicy());
  8824. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  8825. : diag::warn_cast_nonnull_to_bool;
  8826. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  8827. << E->getSourceRange() << Range << IsEqual;
  8828. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  8829. };
  8830. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  8831. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  8832. if (auto *Callee = Call->getDirectCallee()) {
  8833. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  8834. ComplainAboutNonnullParamOrCall(A);
  8835. return;
  8836. }
  8837. }
  8838. }
  8839. // Expect to find a single Decl. Skip anything more complicated.
  8840. ValueDecl *D = nullptr;
  8841. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  8842. D = R->getDecl();
  8843. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  8844. D = M->getMemberDecl();
  8845. }
  8846. // Weak Decls can be null.
  8847. if (!D || D->isWeak())
  8848. return;
  8849. // Check for parameter decl with nonnull attribute
  8850. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  8851. if (getCurFunction() &&
  8852. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  8853. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  8854. ComplainAboutNonnullParamOrCall(A);
  8855. return;
  8856. }
  8857. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  8858. auto ParamIter = llvm::find(FD->parameters(), PV);
  8859. assert(ParamIter != FD->param_end());
  8860. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  8861. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  8862. if (!NonNull->args_size()) {
  8863. ComplainAboutNonnullParamOrCall(NonNull);
  8864. return;
  8865. }
  8866. for (unsigned ArgNo : NonNull->args()) {
  8867. if (ArgNo == ParamNo) {
  8868. ComplainAboutNonnullParamOrCall(NonNull);
  8869. return;
  8870. }
  8871. }
  8872. }
  8873. }
  8874. }
  8875. }
  8876. QualType T = D->getType();
  8877. const bool IsArray = T->isArrayType();
  8878. const bool IsFunction = T->isFunctionType();
  8879. // Address of function is used to silence the function warning.
  8880. if (IsAddressOf && IsFunction) {
  8881. return;
  8882. }
  8883. // Found nothing.
  8884. if (!IsAddressOf && !IsFunction && !IsArray)
  8885. return;
  8886. // Pretty print the expression for the diagnostic.
  8887. std::string Str;
  8888. llvm::raw_string_ostream S(Str);
  8889. E->printPretty(S, nullptr, getPrintingPolicy());
  8890. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  8891. : diag::warn_impcast_pointer_to_bool;
  8892. enum {
  8893. AddressOf,
  8894. FunctionPointer,
  8895. ArrayPointer
  8896. } DiagType;
  8897. if (IsAddressOf)
  8898. DiagType = AddressOf;
  8899. else if (IsFunction)
  8900. DiagType = FunctionPointer;
  8901. else if (IsArray)
  8902. DiagType = ArrayPointer;
  8903. else
  8904. llvm_unreachable("Could not determine diagnostic.");
  8905. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  8906. << Range << IsEqual;
  8907. if (!IsFunction)
  8908. return;
  8909. // Suggest '&' to silence the function warning.
  8910. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  8911. << FixItHint::CreateInsertion(E->getLocStart(), "&");
  8912. // Check to see if '()' fixit should be emitted.
  8913. QualType ReturnType;
  8914. UnresolvedSet<4> NonTemplateOverloads;
  8915. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  8916. if (ReturnType.isNull())
  8917. return;
  8918. if (IsCompare) {
  8919. // There are two cases here. If there is null constant, the only suggest
  8920. // for a pointer return type. If the null is 0, then suggest if the return
  8921. // type is a pointer or an integer type.
  8922. if (!ReturnType->isPointerType()) {
  8923. if (NullKind == Expr::NPCK_ZeroExpression ||
  8924. NullKind == Expr::NPCK_ZeroLiteral) {
  8925. if (!ReturnType->isIntegerType())
  8926. return;
  8927. } else {
  8928. return;
  8929. }
  8930. }
  8931. } else { // !IsCompare
  8932. // For function to bool, only suggest if the function pointer has bool
  8933. // return type.
  8934. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  8935. return;
  8936. }
  8937. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  8938. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
  8939. }
  8940. /// Diagnoses "dangerous" implicit conversions within the given
  8941. /// expression (which is a full expression). Implements -Wconversion
  8942. /// and -Wsign-compare.
  8943. ///
  8944. /// \param CC the "context" location of the implicit conversion, i.e.
  8945. /// the most location of the syntactic entity requiring the implicit
  8946. /// conversion
  8947. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  8948. // Don't diagnose in unevaluated contexts.
  8949. if (isUnevaluatedContext())
  8950. return;
  8951. // Don't diagnose for value- or type-dependent expressions.
  8952. if (E->isTypeDependent() || E->isValueDependent())
  8953. return;
  8954. // Check for array bounds violations in cases where the check isn't triggered
  8955. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  8956. // ArraySubscriptExpr is on the RHS of a variable initialization.
  8957. CheckArrayAccess(E);
  8958. // This is not the right CC for (e.g.) a variable initialization.
  8959. AnalyzeImplicitConversions(*this, E, CC);
  8960. }
  8961. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  8962. /// Input argument E is a logical expression.
  8963. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  8964. ::CheckBoolLikeConversion(*this, E, CC);
  8965. }
  8966. /// Diagnose when expression is an integer constant expression and its evaluation
  8967. /// results in integer overflow
  8968. void Sema::CheckForIntOverflow (Expr *E) {
  8969. // Use a work list to deal with nested struct initializers.
  8970. SmallVector<Expr *, 2> Exprs(1, E);
  8971. do {
  8972. Expr *E = Exprs.pop_back_val();
  8973. if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
  8974. E->IgnoreParenCasts()->EvaluateForOverflow(Context);
  8975. continue;
  8976. }
  8977. if (auto InitList = dyn_cast<InitListExpr>(E))
  8978. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  8979. if (isa<ObjCBoxedExpr>(E))
  8980. E->IgnoreParenCasts()->EvaluateForOverflow(Context);
  8981. } while (!Exprs.empty());
  8982. }
  8983. namespace {
  8984. /// \brief Visitor for expressions which looks for unsequenced operations on the
  8985. /// same object.
  8986. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  8987. using Base = EvaluatedExprVisitor<SequenceChecker>;
  8988. /// \brief A tree of sequenced regions within an expression. Two regions are
  8989. /// unsequenced if one is an ancestor or a descendent of the other. When we
  8990. /// finish processing an expression with sequencing, such as a comma
  8991. /// expression, we fold its tree nodes into its parent, since they are
  8992. /// unsequenced with respect to nodes we will visit later.
  8993. class SequenceTree {
  8994. struct Value {
  8995. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  8996. unsigned Parent : 31;
  8997. unsigned Merged : 1;
  8998. };
  8999. SmallVector<Value, 8> Values;
  9000. public:
  9001. /// \brief A region within an expression which may be sequenced with respect
  9002. /// to some other region.
  9003. class Seq {
  9004. friend class SequenceTree;
  9005. unsigned Index = 0;
  9006. explicit Seq(unsigned N) : Index(N) {}
  9007. public:
  9008. Seq() = default;
  9009. };
  9010. SequenceTree() { Values.push_back(Value(0)); }
  9011. Seq root() const { return Seq(0); }
  9012. /// \brief Create a new sequence of operations, which is an unsequenced
  9013. /// subset of \p Parent. This sequence of operations is sequenced with
  9014. /// respect to other children of \p Parent.
  9015. Seq allocate(Seq Parent) {
  9016. Values.push_back(Value(Parent.Index));
  9017. return Seq(Values.size() - 1);
  9018. }
  9019. /// \brief Merge a sequence of operations into its parent.
  9020. void merge(Seq S) {
  9021. Values[S.Index].Merged = true;
  9022. }
  9023. /// \brief Determine whether two operations are unsequenced. This operation
  9024. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  9025. /// should have been merged into its parent as appropriate.
  9026. bool isUnsequenced(Seq Cur, Seq Old) {
  9027. unsigned C = representative(Cur.Index);
  9028. unsigned Target = representative(Old.Index);
  9029. while (C >= Target) {
  9030. if (C == Target)
  9031. return true;
  9032. C = Values[C].Parent;
  9033. }
  9034. return false;
  9035. }
  9036. private:
  9037. /// \brief Pick a representative for a sequence.
  9038. unsigned representative(unsigned K) {
  9039. if (Values[K].Merged)
  9040. // Perform path compression as we go.
  9041. return Values[K].Parent = representative(Values[K].Parent);
  9042. return K;
  9043. }
  9044. };
  9045. /// An object for which we can track unsequenced uses.
  9046. using Object = NamedDecl *;
  9047. /// Different flavors of object usage which we track. We only track the
  9048. /// least-sequenced usage of each kind.
  9049. enum UsageKind {
  9050. /// A read of an object. Multiple unsequenced reads are OK.
  9051. UK_Use,
  9052. /// A modification of an object which is sequenced before the value
  9053. /// computation of the expression, such as ++n in C++.
  9054. UK_ModAsValue,
  9055. /// A modification of an object which is not sequenced before the value
  9056. /// computation of the expression, such as n++.
  9057. UK_ModAsSideEffect,
  9058. UK_Count = UK_ModAsSideEffect + 1
  9059. };
  9060. struct Usage {
  9061. Expr *Use = nullptr;
  9062. SequenceTree::Seq Seq;
  9063. Usage() = default;
  9064. };
  9065. struct UsageInfo {
  9066. Usage Uses[UK_Count];
  9067. /// Have we issued a diagnostic for this variable already?
  9068. bool Diagnosed = false;
  9069. UsageInfo() = default;
  9070. };
  9071. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  9072. Sema &SemaRef;
  9073. /// Sequenced regions within the expression.
  9074. SequenceTree Tree;
  9075. /// Declaration modifications and references which we have seen.
  9076. UsageInfoMap UsageMap;
  9077. /// The region we are currently within.
  9078. SequenceTree::Seq Region;
  9079. /// Filled in with declarations which were modified as a side-effect
  9080. /// (that is, post-increment operations).
  9081. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  9082. /// Expressions to check later. We defer checking these to reduce
  9083. /// stack usage.
  9084. SmallVectorImpl<Expr *> &WorkList;
  9085. /// RAII object wrapping the visitation of a sequenced subexpression of an
  9086. /// expression. At the end of this process, the side-effects of the evaluation
  9087. /// become sequenced with respect to the value computation of the result, so
  9088. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  9089. /// UK_ModAsValue.
  9090. struct SequencedSubexpression {
  9091. SequencedSubexpression(SequenceChecker &Self)
  9092. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  9093. Self.ModAsSideEffect = &ModAsSideEffect;
  9094. }
  9095. ~SequencedSubexpression() {
  9096. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  9097. UsageInfo &U = Self.UsageMap[M.first];
  9098. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  9099. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  9100. SideEffectUsage = M.second;
  9101. }
  9102. Self.ModAsSideEffect = OldModAsSideEffect;
  9103. }
  9104. SequenceChecker &Self;
  9105. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  9106. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  9107. };
  9108. /// RAII object wrapping the visitation of a subexpression which we might
  9109. /// choose to evaluate as a constant. If any subexpression is evaluated and
  9110. /// found to be non-constant, this allows us to suppress the evaluation of
  9111. /// the outer expression.
  9112. class EvaluationTracker {
  9113. public:
  9114. EvaluationTracker(SequenceChecker &Self)
  9115. : Self(Self), Prev(Self.EvalTracker) {
  9116. Self.EvalTracker = this;
  9117. }
  9118. ~EvaluationTracker() {
  9119. Self.EvalTracker = Prev;
  9120. if (Prev)
  9121. Prev->EvalOK &= EvalOK;
  9122. }
  9123. bool evaluate(const Expr *E, bool &Result) {
  9124. if (!EvalOK || E->isValueDependent())
  9125. return false;
  9126. EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
  9127. return EvalOK;
  9128. }
  9129. private:
  9130. SequenceChecker &Self;
  9131. EvaluationTracker *Prev;
  9132. bool EvalOK = true;
  9133. } *EvalTracker = nullptr;
  9134. /// \brief Find the object which is produced by the specified expression,
  9135. /// if any.
  9136. Object getObject(Expr *E, bool Mod) const {
  9137. E = E->IgnoreParenCasts();
  9138. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  9139. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  9140. return getObject(UO->getSubExpr(), Mod);
  9141. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9142. if (BO->getOpcode() == BO_Comma)
  9143. return getObject(BO->getRHS(), Mod);
  9144. if (Mod && BO->isAssignmentOp())
  9145. return getObject(BO->getLHS(), Mod);
  9146. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  9147. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  9148. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  9149. return ME->getMemberDecl();
  9150. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  9151. // FIXME: If this is a reference, map through to its value.
  9152. return DRE->getDecl();
  9153. return nullptr;
  9154. }
  9155. /// \brief Note that an object was modified or used by an expression.
  9156. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  9157. Usage &U = UI.Uses[UK];
  9158. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  9159. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  9160. ModAsSideEffect->push_back(std::make_pair(O, U));
  9161. U.Use = Ref;
  9162. U.Seq = Region;
  9163. }
  9164. }
  9165. /// \brief Check whether a modification or use conflicts with a prior usage.
  9166. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  9167. bool IsModMod) {
  9168. if (UI.Diagnosed)
  9169. return;
  9170. const Usage &U = UI.Uses[OtherKind];
  9171. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  9172. return;
  9173. Expr *Mod = U.Use;
  9174. Expr *ModOrUse = Ref;
  9175. if (OtherKind == UK_Use)
  9176. std::swap(Mod, ModOrUse);
  9177. SemaRef.Diag(Mod->getExprLoc(),
  9178. IsModMod ? diag::warn_unsequenced_mod_mod
  9179. : diag::warn_unsequenced_mod_use)
  9180. << O << SourceRange(ModOrUse->getExprLoc());
  9181. UI.Diagnosed = true;
  9182. }
  9183. void notePreUse(Object O, Expr *Use) {
  9184. UsageInfo &U = UsageMap[O];
  9185. // Uses conflict with other modifications.
  9186. checkUsage(O, U, Use, UK_ModAsValue, false);
  9187. }
  9188. void notePostUse(Object O, Expr *Use) {
  9189. UsageInfo &U = UsageMap[O];
  9190. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  9191. addUsage(U, O, Use, UK_Use);
  9192. }
  9193. void notePreMod(Object O, Expr *Mod) {
  9194. UsageInfo &U = UsageMap[O];
  9195. // Modifications conflict with other modifications and with uses.
  9196. checkUsage(O, U, Mod, UK_ModAsValue, true);
  9197. checkUsage(O, U, Mod, UK_Use, false);
  9198. }
  9199. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  9200. UsageInfo &U = UsageMap[O];
  9201. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  9202. addUsage(U, O, Use, UK);
  9203. }
  9204. public:
  9205. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  9206. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  9207. Visit(E);
  9208. }
  9209. void VisitStmt(Stmt *S) {
  9210. // Skip all statements which aren't expressions for now.
  9211. }
  9212. void VisitExpr(Expr *E) {
  9213. // By default, just recurse to evaluated subexpressions.
  9214. Base::VisitStmt(E);
  9215. }
  9216. void VisitCastExpr(CastExpr *E) {
  9217. Object O = Object();
  9218. if (E->getCastKind() == CK_LValueToRValue)
  9219. O = getObject(E->getSubExpr(), false);
  9220. if (O)
  9221. notePreUse(O, E);
  9222. VisitExpr(E);
  9223. if (O)
  9224. notePostUse(O, E);
  9225. }
  9226. void VisitBinComma(BinaryOperator *BO) {
  9227. // C++11 [expr.comma]p1:
  9228. // Every value computation and side effect associated with the left
  9229. // expression is sequenced before every value computation and side
  9230. // effect associated with the right expression.
  9231. SequenceTree::Seq LHS = Tree.allocate(Region);
  9232. SequenceTree::Seq RHS = Tree.allocate(Region);
  9233. SequenceTree::Seq OldRegion = Region;
  9234. {
  9235. SequencedSubexpression SeqLHS(*this);
  9236. Region = LHS;
  9237. Visit(BO->getLHS());
  9238. }
  9239. Region = RHS;
  9240. Visit(BO->getRHS());
  9241. Region = OldRegion;
  9242. // Forget that LHS and RHS are sequenced. They are both unsequenced
  9243. // with respect to other stuff.
  9244. Tree.merge(LHS);
  9245. Tree.merge(RHS);
  9246. }
  9247. void VisitBinAssign(BinaryOperator *BO) {
  9248. // The modification is sequenced after the value computation of the LHS
  9249. // and RHS, so check it before inspecting the operands and update the
  9250. // map afterwards.
  9251. Object O = getObject(BO->getLHS(), true);
  9252. if (!O)
  9253. return VisitExpr(BO);
  9254. notePreMod(O, BO);
  9255. // C++11 [expr.ass]p7:
  9256. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  9257. // only once.
  9258. //
  9259. // Therefore, for a compound assignment operator, O is considered used
  9260. // everywhere except within the evaluation of E1 itself.
  9261. if (isa<CompoundAssignOperator>(BO))
  9262. notePreUse(O, BO);
  9263. Visit(BO->getLHS());
  9264. if (isa<CompoundAssignOperator>(BO))
  9265. notePostUse(O, BO);
  9266. Visit(BO->getRHS());
  9267. // C++11 [expr.ass]p1:
  9268. // the assignment is sequenced [...] before the value computation of the
  9269. // assignment expression.
  9270. // C11 6.5.16/3 has no such rule.
  9271. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  9272. : UK_ModAsSideEffect);
  9273. }
  9274. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  9275. VisitBinAssign(CAO);
  9276. }
  9277. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  9278. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  9279. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  9280. Object O = getObject(UO->getSubExpr(), true);
  9281. if (!O)
  9282. return VisitExpr(UO);
  9283. notePreMod(O, UO);
  9284. Visit(UO->getSubExpr());
  9285. // C++11 [expr.pre.incr]p1:
  9286. // the expression ++x is equivalent to x+=1
  9287. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  9288. : UK_ModAsSideEffect);
  9289. }
  9290. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  9291. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  9292. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  9293. Object O = getObject(UO->getSubExpr(), true);
  9294. if (!O)
  9295. return VisitExpr(UO);
  9296. notePreMod(O, UO);
  9297. Visit(UO->getSubExpr());
  9298. notePostMod(O, UO, UK_ModAsSideEffect);
  9299. }
  9300. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  9301. void VisitBinLOr(BinaryOperator *BO) {
  9302. // The side-effects of the LHS of an '&&' are sequenced before the
  9303. // value computation of the RHS, and hence before the value computation
  9304. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  9305. // as if they were unconditionally sequenced.
  9306. EvaluationTracker Eval(*this);
  9307. {
  9308. SequencedSubexpression Sequenced(*this);
  9309. Visit(BO->getLHS());
  9310. }
  9311. bool Result;
  9312. if (Eval.evaluate(BO->getLHS(), Result)) {
  9313. if (!Result)
  9314. Visit(BO->getRHS());
  9315. } else {
  9316. // Check for unsequenced operations in the RHS, treating it as an
  9317. // entirely separate evaluation.
  9318. //
  9319. // FIXME: If there are operations in the RHS which are unsequenced
  9320. // with respect to operations outside the RHS, and those operations
  9321. // are unconditionally evaluated, diagnose them.
  9322. WorkList.push_back(BO->getRHS());
  9323. }
  9324. }
  9325. void VisitBinLAnd(BinaryOperator *BO) {
  9326. EvaluationTracker Eval(*this);
  9327. {
  9328. SequencedSubexpression Sequenced(*this);
  9329. Visit(BO->getLHS());
  9330. }
  9331. bool Result;
  9332. if (Eval.evaluate(BO->getLHS(), Result)) {
  9333. if (Result)
  9334. Visit(BO->getRHS());
  9335. } else {
  9336. WorkList.push_back(BO->getRHS());
  9337. }
  9338. }
  9339. // Only visit the condition, unless we can be sure which subexpression will
  9340. // be chosen.
  9341. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  9342. EvaluationTracker Eval(*this);
  9343. {
  9344. SequencedSubexpression Sequenced(*this);
  9345. Visit(CO->getCond());
  9346. }
  9347. bool Result;
  9348. if (Eval.evaluate(CO->getCond(), Result))
  9349. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  9350. else {
  9351. WorkList.push_back(CO->getTrueExpr());
  9352. WorkList.push_back(CO->getFalseExpr());
  9353. }
  9354. }
  9355. void VisitCallExpr(CallExpr *CE) {
  9356. // C++11 [intro.execution]p15:
  9357. // When calling a function [...], every value computation and side effect
  9358. // associated with any argument expression, or with the postfix expression
  9359. // designating the called function, is sequenced before execution of every
  9360. // expression or statement in the body of the function [and thus before
  9361. // the value computation of its result].
  9362. SequencedSubexpression Sequenced(*this);
  9363. Base::VisitCallExpr(CE);
  9364. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  9365. }
  9366. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  9367. // This is a call, so all subexpressions are sequenced before the result.
  9368. SequencedSubexpression Sequenced(*this);
  9369. if (!CCE->isListInitialization())
  9370. return VisitExpr(CCE);
  9371. // In C++11, list initializations are sequenced.
  9372. SmallVector<SequenceTree::Seq, 32> Elts;
  9373. SequenceTree::Seq Parent = Region;
  9374. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  9375. E = CCE->arg_end();
  9376. I != E; ++I) {
  9377. Region = Tree.allocate(Parent);
  9378. Elts.push_back(Region);
  9379. Visit(*I);
  9380. }
  9381. // Forget that the initializers are sequenced.
  9382. Region = Parent;
  9383. for (unsigned I = 0; I < Elts.size(); ++I)
  9384. Tree.merge(Elts[I]);
  9385. }
  9386. void VisitInitListExpr(InitListExpr *ILE) {
  9387. if (!SemaRef.getLangOpts().CPlusPlus11)
  9388. return VisitExpr(ILE);
  9389. // In C++11, list initializations are sequenced.
  9390. SmallVector<SequenceTree::Seq, 32> Elts;
  9391. SequenceTree::Seq Parent = Region;
  9392. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  9393. Expr *E = ILE->getInit(I);
  9394. if (!E) continue;
  9395. Region = Tree.allocate(Parent);
  9396. Elts.push_back(Region);
  9397. Visit(E);
  9398. }
  9399. // Forget that the initializers are sequenced.
  9400. Region = Parent;
  9401. for (unsigned I = 0; I < Elts.size(); ++I)
  9402. Tree.merge(Elts[I]);
  9403. }
  9404. };
  9405. } // namespace
  9406. void Sema::CheckUnsequencedOperations(Expr *E) {
  9407. SmallVector<Expr *, 8> WorkList;
  9408. WorkList.push_back(E);
  9409. while (!WorkList.empty()) {
  9410. Expr *Item = WorkList.pop_back_val();
  9411. SequenceChecker(*this, Item, WorkList);
  9412. }
  9413. }
  9414. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  9415. bool IsConstexpr) {
  9416. CheckImplicitConversions(E, CheckLoc);
  9417. if (!E->isInstantiationDependent())
  9418. CheckUnsequencedOperations(E);
  9419. if (!IsConstexpr && !E->isValueDependent())
  9420. CheckForIntOverflow(E);
  9421. DiagnoseMisalignedMembers();
  9422. }
  9423. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  9424. FieldDecl *BitField,
  9425. Expr *Init) {
  9426. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  9427. }
  9428. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  9429. SourceLocation Loc) {
  9430. if (!PType->isVariablyModifiedType())
  9431. return;
  9432. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  9433. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  9434. return;
  9435. }
  9436. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  9437. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  9438. return;
  9439. }
  9440. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  9441. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  9442. return;
  9443. }
  9444. const ArrayType *AT = S.Context.getAsArrayType(PType);
  9445. if (!AT)
  9446. return;
  9447. if (AT->getSizeModifier() != ArrayType::Star) {
  9448. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  9449. return;
  9450. }
  9451. S.Diag(Loc, diag::err_array_star_in_function_definition);
  9452. }
  9453. /// CheckParmsForFunctionDef - Check that the parameters of the given
  9454. /// function are appropriate for the definition of a function. This
  9455. /// takes care of any checks that cannot be performed on the
  9456. /// declaration itself, e.g., that the types of each of the function
  9457. /// parameters are complete.
  9458. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  9459. bool CheckParameterNames) {
  9460. bool HasInvalidParm = false;
  9461. for (ParmVarDecl *Param : Parameters) {
  9462. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  9463. // function declarator that is part of a function definition of
  9464. // that function shall not have incomplete type.
  9465. //
  9466. // This is also C++ [dcl.fct]p6.
  9467. if (!Param->isInvalidDecl() &&
  9468. RequireCompleteType(Param->getLocation(), Param->getType(),
  9469. diag::err_typecheck_decl_incomplete_type)) {
  9470. Param->setInvalidDecl();
  9471. HasInvalidParm = true;
  9472. }
  9473. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  9474. // declaration of each parameter shall include an identifier.
  9475. if (CheckParameterNames &&
  9476. Param->getIdentifier() == nullptr &&
  9477. !Param->isImplicit() &&
  9478. !getLangOpts().CPlusPlus)
  9479. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  9480. // C99 6.7.5.3p12:
  9481. // If the function declarator is not part of a definition of that
  9482. // function, parameters may have incomplete type and may use the [*]
  9483. // notation in their sequences of declarator specifiers to specify
  9484. // variable length array types.
  9485. QualType PType = Param->getOriginalType();
  9486. // FIXME: This diagnostic should point the '[*]' if source-location
  9487. // information is added for it.
  9488. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  9489. // MSVC destroys objects passed by value in the callee. Therefore a
  9490. // function definition which takes such a parameter must be able to call the
  9491. // object's destructor. However, we don't perform any direct access check
  9492. // on the dtor.
  9493. if (getLangOpts().CPlusPlus && Context.getTargetInfo()
  9494. .getCXXABI()
  9495. .areArgsDestroyedLeftToRightInCallee()) {
  9496. if (!Param->isInvalidDecl()) {
  9497. if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
  9498. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  9499. if (!ClassDecl->isInvalidDecl() &&
  9500. !ClassDecl->hasIrrelevantDestructor() &&
  9501. !ClassDecl->isDependentContext()) {
  9502. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  9503. MarkFunctionReferenced(Param->getLocation(), Destructor);
  9504. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  9505. }
  9506. }
  9507. }
  9508. }
  9509. // Parameters with the pass_object_size attribute only need to be marked
  9510. // constant at function definitions. Because we lack information about
  9511. // whether we're on a declaration or definition when we're instantiating the
  9512. // attribute, we need to check for constness here.
  9513. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  9514. if (!Param->getType().isConstQualified())
  9515. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  9516. << Attr->getSpelling() << 1;
  9517. }
  9518. return HasInvalidParm;
  9519. }
  9520. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  9521. /// or MemberExpr.
  9522. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  9523. ASTContext &Context) {
  9524. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  9525. return Context.getDeclAlign(DRE->getDecl());
  9526. if (const auto *ME = dyn_cast<MemberExpr>(E))
  9527. return Context.getDeclAlign(ME->getMemberDecl());
  9528. return TypeAlign;
  9529. }
  9530. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  9531. /// pointer cast increases the alignment requirements.
  9532. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  9533. // This is actually a lot of work to potentially be doing on every
  9534. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  9535. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  9536. return;
  9537. // Ignore dependent types.
  9538. if (T->isDependentType() || Op->getType()->isDependentType())
  9539. return;
  9540. // Require that the destination be a pointer type.
  9541. const PointerType *DestPtr = T->getAs<PointerType>();
  9542. if (!DestPtr) return;
  9543. // If the destination has alignment 1, we're done.
  9544. QualType DestPointee = DestPtr->getPointeeType();
  9545. if (DestPointee->isIncompleteType()) return;
  9546. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  9547. if (DestAlign.isOne()) return;
  9548. // Require that the source be a pointer type.
  9549. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  9550. if (!SrcPtr) return;
  9551. QualType SrcPointee = SrcPtr->getPointeeType();
  9552. // Whitelist casts from cv void*. We already implicitly
  9553. // whitelisted casts to cv void*, since they have alignment 1.
  9554. // Also whitelist casts involving incomplete types, which implicitly
  9555. // includes 'void'.
  9556. if (SrcPointee->isIncompleteType()) return;
  9557. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  9558. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  9559. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  9560. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  9561. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  9562. if (UO->getOpcode() == UO_AddrOf)
  9563. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  9564. }
  9565. if (SrcAlign >= DestAlign) return;
  9566. Diag(TRange.getBegin(), diag::warn_cast_align)
  9567. << Op->getType() << T
  9568. << static_cast<unsigned>(SrcAlign.getQuantity())
  9569. << static_cast<unsigned>(DestAlign.getQuantity())
  9570. << TRange << Op->getSourceRange();
  9571. }
  9572. /// \brief Check whether this array fits the idiom of a size-one tail padded
  9573. /// array member of a struct.
  9574. ///
  9575. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  9576. /// commonly used to emulate flexible arrays in C89 code.
  9577. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  9578. const NamedDecl *ND) {
  9579. if (Size != 1 || !ND) return false;
  9580. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  9581. if (!FD) return false;
  9582. // Don't consider sizes resulting from macro expansions or template argument
  9583. // substitution to form C89 tail-padded arrays.
  9584. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  9585. while (TInfo) {
  9586. TypeLoc TL = TInfo->getTypeLoc();
  9587. // Look through typedefs.
  9588. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  9589. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  9590. TInfo = TDL->getTypeSourceInfo();
  9591. continue;
  9592. }
  9593. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  9594. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  9595. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  9596. return false;
  9597. }
  9598. break;
  9599. }
  9600. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  9601. if (!RD) return false;
  9602. if (RD->isUnion()) return false;
  9603. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  9604. if (!CRD->isStandardLayout()) return false;
  9605. }
  9606. // See if this is the last field decl in the record.
  9607. const Decl *D = FD;
  9608. while ((D = D->getNextDeclInContext()))
  9609. if (isa<FieldDecl>(D))
  9610. return false;
  9611. return true;
  9612. }
  9613. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  9614. const ArraySubscriptExpr *ASE,
  9615. bool AllowOnePastEnd, bool IndexNegated) {
  9616. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  9617. if (IndexExpr->isValueDependent())
  9618. return;
  9619. const Type *EffectiveType =
  9620. BaseExpr->getType()->getPointeeOrArrayElementType();
  9621. BaseExpr = BaseExpr->IgnoreParenCasts();
  9622. const ConstantArrayType *ArrayTy =
  9623. Context.getAsConstantArrayType(BaseExpr->getType());
  9624. if (!ArrayTy)
  9625. return;
  9626. llvm::APSInt index;
  9627. if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
  9628. return;
  9629. if (IndexNegated)
  9630. index = -index;
  9631. const NamedDecl *ND = nullptr;
  9632. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  9633. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  9634. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  9635. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  9636. if (index.isUnsigned() || !index.isNegative()) {
  9637. llvm::APInt size = ArrayTy->getSize();
  9638. if (!size.isStrictlyPositive())
  9639. return;
  9640. const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
  9641. if (BaseType != EffectiveType) {
  9642. // Make sure we're comparing apples to apples when comparing index to size
  9643. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  9644. uint64_t array_typesize = Context.getTypeSize(BaseType);
  9645. // Handle ptrarith_typesize being zero, such as when casting to void*
  9646. if (!ptrarith_typesize) ptrarith_typesize = 1;
  9647. if (ptrarith_typesize != array_typesize) {
  9648. // There's a cast to a different size type involved
  9649. uint64_t ratio = array_typesize / ptrarith_typesize;
  9650. // TODO: Be smarter about handling cases where array_typesize is not a
  9651. // multiple of ptrarith_typesize
  9652. if (ptrarith_typesize * ratio == array_typesize)
  9653. size *= llvm::APInt(size.getBitWidth(), ratio);
  9654. }
  9655. }
  9656. if (size.getBitWidth() > index.getBitWidth())
  9657. index = index.zext(size.getBitWidth());
  9658. else if (size.getBitWidth() < index.getBitWidth())
  9659. size = size.zext(index.getBitWidth());
  9660. // For array subscripting the index must be less than size, but for pointer
  9661. // arithmetic also allow the index (offset) to be equal to size since
  9662. // computing the next address after the end of the array is legal and
  9663. // commonly done e.g. in C++ iterators and range-based for loops.
  9664. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  9665. return;
  9666. // Also don't warn for arrays of size 1 which are members of some
  9667. // structure. These are often used to approximate flexible arrays in C89
  9668. // code.
  9669. if (IsTailPaddedMemberArray(*this, size, ND))
  9670. return;
  9671. // Suppress the warning if the subscript expression (as identified by the
  9672. // ']' location) and the index expression are both from macro expansions
  9673. // within a system header.
  9674. if (ASE) {
  9675. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  9676. ASE->getRBracketLoc());
  9677. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  9678. SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
  9679. IndexExpr->getLocStart());
  9680. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  9681. return;
  9682. }
  9683. }
  9684. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  9685. if (ASE)
  9686. DiagID = diag::warn_array_index_exceeds_bounds;
  9687. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  9688. PDiag(DiagID) << index.toString(10, true)
  9689. << size.toString(10, true)
  9690. << (unsigned)size.getLimitedValue(~0U)
  9691. << IndexExpr->getSourceRange());
  9692. } else {
  9693. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  9694. if (!ASE) {
  9695. DiagID = diag::warn_ptr_arith_precedes_bounds;
  9696. if (index.isNegative()) index = -index;
  9697. }
  9698. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  9699. PDiag(DiagID) << index.toString(10, true)
  9700. << IndexExpr->getSourceRange());
  9701. }
  9702. if (!ND) {
  9703. // Try harder to find a NamedDecl to point at in the note.
  9704. while (const ArraySubscriptExpr *ASE =
  9705. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  9706. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  9707. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  9708. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  9709. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  9710. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  9711. }
  9712. if (ND)
  9713. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  9714. PDiag(diag::note_array_index_out_of_bounds)
  9715. << ND->getDeclName());
  9716. }
  9717. void Sema::CheckArrayAccess(const Expr *expr) {
  9718. int AllowOnePastEnd = 0;
  9719. while (expr) {
  9720. expr = expr->IgnoreParenImpCasts();
  9721. switch (expr->getStmtClass()) {
  9722. case Stmt::ArraySubscriptExprClass: {
  9723. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  9724. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  9725. AllowOnePastEnd > 0);
  9726. return;
  9727. }
  9728. case Stmt::OMPArraySectionExprClass: {
  9729. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  9730. if (ASE->getLowerBound())
  9731. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  9732. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  9733. return;
  9734. }
  9735. case Stmt::UnaryOperatorClass: {
  9736. // Only unwrap the * and & unary operators
  9737. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  9738. expr = UO->getSubExpr();
  9739. switch (UO->getOpcode()) {
  9740. case UO_AddrOf:
  9741. AllowOnePastEnd++;
  9742. break;
  9743. case UO_Deref:
  9744. AllowOnePastEnd--;
  9745. break;
  9746. default:
  9747. return;
  9748. }
  9749. break;
  9750. }
  9751. case Stmt::ConditionalOperatorClass: {
  9752. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  9753. if (const Expr *lhs = cond->getLHS())
  9754. CheckArrayAccess(lhs);
  9755. if (const Expr *rhs = cond->getRHS())
  9756. CheckArrayAccess(rhs);
  9757. return;
  9758. }
  9759. case Stmt::CXXOperatorCallExprClass: {
  9760. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  9761. for (const auto *Arg : OCE->arguments())
  9762. CheckArrayAccess(Arg);
  9763. return;
  9764. }
  9765. default:
  9766. return;
  9767. }
  9768. }
  9769. }
  9770. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  9771. namespace {
  9772. struct RetainCycleOwner {
  9773. VarDecl *Variable = nullptr;
  9774. SourceRange Range;
  9775. SourceLocation Loc;
  9776. bool Indirect = false;
  9777. RetainCycleOwner() = default;
  9778. void setLocsFrom(Expr *e) {
  9779. Loc = e->getExprLoc();
  9780. Range = e->getSourceRange();
  9781. }
  9782. };
  9783. } // namespace
  9784. /// Consider whether capturing the given variable can possibly lead to
  9785. /// a retain cycle.
  9786. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  9787. // In ARC, it's captured strongly iff the variable has __strong
  9788. // lifetime. In MRR, it's captured strongly if the variable is
  9789. // __block and has an appropriate type.
  9790. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  9791. return false;
  9792. owner.Variable = var;
  9793. if (ref)
  9794. owner.setLocsFrom(ref);
  9795. return true;
  9796. }
  9797. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  9798. while (true) {
  9799. e = e->IgnoreParens();
  9800. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  9801. switch (cast->getCastKind()) {
  9802. case CK_BitCast:
  9803. case CK_LValueBitCast:
  9804. case CK_LValueToRValue:
  9805. case CK_ARCReclaimReturnedObject:
  9806. e = cast->getSubExpr();
  9807. continue;
  9808. default:
  9809. return false;
  9810. }
  9811. }
  9812. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  9813. ObjCIvarDecl *ivar = ref->getDecl();
  9814. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  9815. return false;
  9816. // Try to find a retain cycle in the base.
  9817. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  9818. return false;
  9819. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  9820. owner.Indirect = true;
  9821. return true;
  9822. }
  9823. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  9824. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  9825. if (!var) return false;
  9826. return considerVariable(var, ref, owner);
  9827. }
  9828. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  9829. if (member->isArrow()) return false;
  9830. // Don't count this as an indirect ownership.
  9831. e = member->getBase();
  9832. continue;
  9833. }
  9834. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  9835. // Only pay attention to pseudo-objects on property references.
  9836. ObjCPropertyRefExpr *pre
  9837. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  9838. ->IgnoreParens());
  9839. if (!pre) return false;
  9840. if (pre->isImplicitProperty()) return false;
  9841. ObjCPropertyDecl *property = pre->getExplicitProperty();
  9842. if (!property->isRetaining() &&
  9843. !(property->getPropertyIvarDecl() &&
  9844. property->getPropertyIvarDecl()->getType()
  9845. .getObjCLifetime() == Qualifiers::OCL_Strong))
  9846. return false;
  9847. owner.Indirect = true;
  9848. if (pre->isSuperReceiver()) {
  9849. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  9850. if (!owner.Variable)
  9851. return false;
  9852. owner.Loc = pre->getLocation();
  9853. owner.Range = pre->getSourceRange();
  9854. return true;
  9855. }
  9856. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  9857. ->getSourceExpr());
  9858. continue;
  9859. }
  9860. // Array ivars?
  9861. return false;
  9862. }
  9863. }
  9864. namespace {
  9865. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  9866. ASTContext &Context;
  9867. VarDecl *Variable;
  9868. Expr *Capturer = nullptr;
  9869. bool VarWillBeReased = false;
  9870. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  9871. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  9872. Context(Context), Variable(variable) {}
  9873. void VisitDeclRefExpr(DeclRefExpr *ref) {
  9874. if (ref->getDecl() == Variable && !Capturer)
  9875. Capturer = ref;
  9876. }
  9877. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  9878. if (Capturer) return;
  9879. Visit(ref->getBase());
  9880. if (Capturer && ref->isFreeIvar())
  9881. Capturer = ref;
  9882. }
  9883. void VisitBlockExpr(BlockExpr *block) {
  9884. // Look inside nested blocks
  9885. if (block->getBlockDecl()->capturesVariable(Variable))
  9886. Visit(block->getBlockDecl()->getBody());
  9887. }
  9888. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  9889. if (Capturer) return;
  9890. if (OVE->getSourceExpr())
  9891. Visit(OVE->getSourceExpr());
  9892. }
  9893. void VisitBinaryOperator(BinaryOperator *BinOp) {
  9894. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  9895. return;
  9896. Expr *LHS = BinOp->getLHS();
  9897. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  9898. if (DRE->getDecl() != Variable)
  9899. return;
  9900. if (Expr *RHS = BinOp->getRHS()) {
  9901. RHS = RHS->IgnoreParenCasts();
  9902. llvm::APSInt Value;
  9903. VarWillBeReased =
  9904. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  9905. }
  9906. }
  9907. }
  9908. };
  9909. } // namespace
  9910. /// Check whether the given argument is a block which captures a
  9911. /// variable.
  9912. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  9913. assert(owner.Variable && owner.Loc.isValid());
  9914. e = e->IgnoreParenCasts();
  9915. // Look through [^{...} copy] and Block_copy(^{...}).
  9916. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  9917. Selector Cmd = ME->getSelector();
  9918. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  9919. e = ME->getInstanceReceiver();
  9920. if (!e)
  9921. return nullptr;
  9922. e = e->IgnoreParenCasts();
  9923. }
  9924. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  9925. if (CE->getNumArgs() == 1) {
  9926. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  9927. if (Fn) {
  9928. const IdentifierInfo *FnI = Fn->getIdentifier();
  9929. if (FnI && FnI->isStr("_Block_copy")) {
  9930. e = CE->getArg(0)->IgnoreParenCasts();
  9931. }
  9932. }
  9933. }
  9934. }
  9935. BlockExpr *block = dyn_cast<BlockExpr>(e);
  9936. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  9937. return nullptr;
  9938. FindCaptureVisitor visitor(S.Context, owner.Variable);
  9939. visitor.Visit(block->getBlockDecl()->getBody());
  9940. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  9941. }
  9942. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  9943. RetainCycleOwner &owner) {
  9944. assert(capturer);
  9945. assert(owner.Variable && owner.Loc.isValid());
  9946. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  9947. << owner.Variable << capturer->getSourceRange();
  9948. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  9949. << owner.Indirect << owner.Range;
  9950. }
  9951. /// Check for a keyword selector that starts with the word 'add' or
  9952. /// 'set'.
  9953. static bool isSetterLikeSelector(Selector sel) {
  9954. if (sel.isUnarySelector()) return false;
  9955. StringRef str = sel.getNameForSlot(0);
  9956. while (!str.empty() && str.front() == '_') str = str.substr(1);
  9957. if (str.startswith("set"))
  9958. str = str.substr(3);
  9959. else if (str.startswith("add")) {
  9960. // Specially whitelist 'addOperationWithBlock:'.
  9961. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  9962. return false;
  9963. str = str.substr(3);
  9964. }
  9965. else
  9966. return false;
  9967. if (str.empty()) return true;
  9968. return !isLowercase(str.front());
  9969. }
  9970. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  9971. ObjCMessageExpr *Message) {
  9972. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  9973. Message->getReceiverInterface(),
  9974. NSAPI::ClassId_NSMutableArray);
  9975. if (!IsMutableArray) {
  9976. return None;
  9977. }
  9978. Selector Sel = Message->getSelector();
  9979. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  9980. S.NSAPIObj->getNSArrayMethodKind(Sel);
  9981. if (!MKOpt) {
  9982. return None;
  9983. }
  9984. NSAPI::NSArrayMethodKind MK = *MKOpt;
  9985. switch (MK) {
  9986. case NSAPI::NSMutableArr_addObject:
  9987. case NSAPI::NSMutableArr_insertObjectAtIndex:
  9988. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  9989. return 0;
  9990. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  9991. return 1;
  9992. default:
  9993. return None;
  9994. }
  9995. return None;
  9996. }
  9997. static
  9998. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  9999. ObjCMessageExpr *Message) {
  10000. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  10001. Message->getReceiverInterface(),
  10002. NSAPI::ClassId_NSMutableDictionary);
  10003. if (!IsMutableDictionary) {
  10004. return None;
  10005. }
  10006. Selector Sel = Message->getSelector();
  10007. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  10008. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  10009. if (!MKOpt) {
  10010. return None;
  10011. }
  10012. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  10013. switch (MK) {
  10014. case NSAPI::NSMutableDict_setObjectForKey:
  10015. case NSAPI::NSMutableDict_setValueForKey:
  10016. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  10017. return 0;
  10018. default:
  10019. return None;
  10020. }
  10021. return None;
  10022. }
  10023. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  10024. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  10025. Message->getReceiverInterface(),
  10026. NSAPI::ClassId_NSMutableSet);
  10027. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  10028. Message->getReceiverInterface(),
  10029. NSAPI::ClassId_NSMutableOrderedSet);
  10030. if (!IsMutableSet && !IsMutableOrderedSet) {
  10031. return None;
  10032. }
  10033. Selector Sel = Message->getSelector();
  10034. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  10035. if (!MKOpt) {
  10036. return None;
  10037. }
  10038. NSAPI::NSSetMethodKind MK = *MKOpt;
  10039. switch (MK) {
  10040. case NSAPI::NSMutableSet_addObject:
  10041. case NSAPI::NSOrderedSet_setObjectAtIndex:
  10042. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  10043. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  10044. return 0;
  10045. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  10046. return 1;
  10047. }
  10048. return None;
  10049. }
  10050. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  10051. if (!Message->isInstanceMessage()) {
  10052. return;
  10053. }
  10054. Optional<int> ArgOpt;
  10055. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  10056. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  10057. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  10058. return;
  10059. }
  10060. int ArgIndex = *ArgOpt;
  10061. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  10062. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  10063. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  10064. }
  10065. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  10066. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  10067. if (ArgRE->isObjCSelfExpr()) {
  10068. Diag(Message->getSourceRange().getBegin(),
  10069. diag::warn_objc_circular_container)
  10070. << ArgRE->getDecl()->getName() << StringRef("super");
  10071. }
  10072. }
  10073. } else {
  10074. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  10075. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  10076. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  10077. }
  10078. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  10079. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  10080. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  10081. ValueDecl *Decl = ReceiverRE->getDecl();
  10082. Diag(Message->getSourceRange().getBegin(),
  10083. diag::warn_objc_circular_container)
  10084. << Decl->getName() << Decl->getName();
  10085. if (!ArgRE->isObjCSelfExpr()) {
  10086. Diag(Decl->getLocation(),
  10087. diag::note_objc_circular_container_declared_here)
  10088. << Decl->getName();
  10089. }
  10090. }
  10091. }
  10092. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  10093. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  10094. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  10095. ObjCIvarDecl *Decl = IvarRE->getDecl();
  10096. Diag(Message->getSourceRange().getBegin(),
  10097. diag::warn_objc_circular_container)
  10098. << Decl->getName() << Decl->getName();
  10099. Diag(Decl->getLocation(),
  10100. diag::note_objc_circular_container_declared_here)
  10101. << Decl->getName();
  10102. }
  10103. }
  10104. }
  10105. }
  10106. }
  10107. /// Check a message send to see if it's likely to cause a retain cycle.
  10108. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  10109. // Only check instance methods whose selector looks like a setter.
  10110. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  10111. return;
  10112. // Try to find a variable that the receiver is strongly owned by.
  10113. RetainCycleOwner owner;
  10114. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  10115. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  10116. return;
  10117. } else {
  10118. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  10119. owner.Variable = getCurMethodDecl()->getSelfDecl();
  10120. owner.Loc = msg->getSuperLoc();
  10121. owner.Range = msg->getSuperLoc();
  10122. }
  10123. // Check whether the receiver is captured by any of the arguments.
  10124. const ObjCMethodDecl *MD = msg->getMethodDecl();
  10125. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  10126. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  10127. // noescape blocks should not be retained by the method.
  10128. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  10129. continue;
  10130. return diagnoseRetainCycle(*this, capturer, owner);
  10131. }
  10132. }
  10133. }
  10134. /// Check a property assign to see if it's likely to cause a retain cycle.
  10135. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  10136. RetainCycleOwner owner;
  10137. if (!findRetainCycleOwner(*this, receiver, owner))
  10138. return;
  10139. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  10140. diagnoseRetainCycle(*this, capturer, owner);
  10141. }
  10142. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  10143. RetainCycleOwner Owner;
  10144. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  10145. return;
  10146. // Because we don't have an expression for the variable, we have to set the
  10147. // location explicitly here.
  10148. Owner.Loc = Var->getLocation();
  10149. Owner.Range = Var->getSourceRange();
  10150. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  10151. diagnoseRetainCycle(*this, Capturer, Owner);
  10152. }
  10153. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  10154. Expr *RHS, bool isProperty) {
  10155. // Check if RHS is an Objective-C object literal, which also can get
  10156. // immediately zapped in a weak reference. Note that we explicitly
  10157. // allow ObjCStringLiterals, since those are designed to never really die.
  10158. RHS = RHS->IgnoreParenImpCasts();
  10159. // This enum needs to match with the 'select' in
  10160. // warn_objc_arc_literal_assign (off-by-1).
  10161. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  10162. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  10163. return false;
  10164. S.Diag(Loc, diag::warn_arc_literal_assign)
  10165. << (unsigned) Kind
  10166. << (isProperty ? 0 : 1)
  10167. << RHS->getSourceRange();
  10168. return true;
  10169. }
  10170. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  10171. Qualifiers::ObjCLifetime LT,
  10172. Expr *RHS, bool isProperty) {
  10173. // Strip off any implicit cast added to get to the one ARC-specific.
  10174. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  10175. if (cast->getCastKind() == CK_ARCConsumeObject) {
  10176. S.Diag(Loc, diag::warn_arc_retained_assign)
  10177. << (LT == Qualifiers::OCL_ExplicitNone)
  10178. << (isProperty ? 0 : 1)
  10179. << RHS->getSourceRange();
  10180. return true;
  10181. }
  10182. RHS = cast->getSubExpr();
  10183. }
  10184. if (LT == Qualifiers::OCL_Weak &&
  10185. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  10186. return true;
  10187. return false;
  10188. }
  10189. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  10190. QualType LHS, Expr *RHS) {
  10191. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  10192. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  10193. return false;
  10194. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  10195. return true;
  10196. return false;
  10197. }
  10198. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  10199. Expr *LHS, Expr *RHS) {
  10200. QualType LHSType;
  10201. // PropertyRef on LHS type need be directly obtained from
  10202. // its declaration as it has a PseudoType.
  10203. ObjCPropertyRefExpr *PRE
  10204. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  10205. if (PRE && !PRE->isImplicitProperty()) {
  10206. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  10207. if (PD)
  10208. LHSType = PD->getType();
  10209. }
  10210. if (LHSType.isNull())
  10211. LHSType = LHS->getType();
  10212. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  10213. if (LT == Qualifiers::OCL_Weak) {
  10214. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  10215. getCurFunction()->markSafeWeakUse(LHS);
  10216. }
  10217. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  10218. return;
  10219. // FIXME. Check for other life times.
  10220. if (LT != Qualifiers::OCL_None)
  10221. return;
  10222. if (PRE) {
  10223. if (PRE->isImplicitProperty())
  10224. return;
  10225. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  10226. if (!PD)
  10227. return;
  10228. unsigned Attributes = PD->getPropertyAttributes();
  10229. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  10230. // when 'assign' attribute was not explicitly specified
  10231. // by user, ignore it and rely on property type itself
  10232. // for lifetime info.
  10233. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  10234. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  10235. LHSType->isObjCRetainableType())
  10236. return;
  10237. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  10238. if (cast->getCastKind() == CK_ARCConsumeObject) {
  10239. Diag(Loc, diag::warn_arc_retained_property_assign)
  10240. << RHS->getSourceRange();
  10241. return;
  10242. }
  10243. RHS = cast->getSubExpr();
  10244. }
  10245. }
  10246. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  10247. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  10248. return;
  10249. }
  10250. }
  10251. }
  10252. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  10253. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  10254. SourceLocation StmtLoc,
  10255. const NullStmt *Body) {
  10256. // Do not warn if the body is a macro that expands to nothing, e.g:
  10257. //
  10258. // #define CALL(x)
  10259. // if (condition)
  10260. // CALL(0);
  10261. if (Body->hasLeadingEmptyMacro())
  10262. return false;
  10263. // Get line numbers of statement and body.
  10264. bool StmtLineInvalid;
  10265. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  10266. &StmtLineInvalid);
  10267. if (StmtLineInvalid)
  10268. return false;
  10269. bool BodyLineInvalid;
  10270. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  10271. &BodyLineInvalid);
  10272. if (BodyLineInvalid)
  10273. return false;
  10274. // Warn if null statement and body are on the same line.
  10275. if (StmtLine != BodyLine)
  10276. return false;
  10277. return true;
  10278. }
  10279. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  10280. const Stmt *Body,
  10281. unsigned DiagID) {
  10282. // Since this is a syntactic check, don't emit diagnostic for template
  10283. // instantiations, this just adds noise.
  10284. if (CurrentInstantiationScope)
  10285. return;
  10286. // The body should be a null statement.
  10287. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  10288. if (!NBody)
  10289. return;
  10290. // Do the usual checks.
  10291. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  10292. return;
  10293. Diag(NBody->getSemiLoc(), DiagID);
  10294. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  10295. }
  10296. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  10297. const Stmt *PossibleBody) {
  10298. assert(!CurrentInstantiationScope); // Ensured by caller
  10299. SourceLocation StmtLoc;
  10300. const Stmt *Body;
  10301. unsigned DiagID;
  10302. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  10303. StmtLoc = FS->getRParenLoc();
  10304. Body = FS->getBody();
  10305. DiagID = diag::warn_empty_for_body;
  10306. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  10307. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  10308. Body = WS->getBody();
  10309. DiagID = diag::warn_empty_while_body;
  10310. } else
  10311. return; // Neither `for' nor `while'.
  10312. // The body should be a null statement.
  10313. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  10314. if (!NBody)
  10315. return;
  10316. // Skip expensive checks if diagnostic is disabled.
  10317. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  10318. return;
  10319. // Do the usual checks.
  10320. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  10321. return;
  10322. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  10323. // noise level low, emit diagnostics only if for/while is followed by a
  10324. // CompoundStmt, e.g.:
  10325. // for (int i = 0; i < n; i++);
  10326. // {
  10327. // a(i);
  10328. // }
  10329. // or if for/while is followed by a statement with more indentation
  10330. // than for/while itself:
  10331. // for (int i = 0; i < n; i++);
  10332. // a(i);
  10333. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  10334. if (!ProbableTypo) {
  10335. bool BodyColInvalid;
  10336. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  10337. PossibleBody->getLocStart(),
  10338. &BodyColInvalid);
  10339. if (BodyColInvalid)
  10340. return;
  10341. bool StmtColInvalid;
  10342. unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
  10343. S->getLocStart(),
  10344. &StmtColInvalid);
  10345. if (StmtColInvalid)
  10346. return;
  10347. if (BodyCol > StmtCol)
  10348. ProbableTypo = true;
  10349. }
  10350. if (ProbableTypo) {
  10351. Diag(NBody->getSemiLoc(), DiagID);
  10352. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  10353. }
  10354. }
  10355. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  10356. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  10357. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  10358. SourceLocation OpLoc) {
  10359. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  10360. return;
  10361. if (inTemplateInstantiation())
  10362. return;
  10363. // Strip parens and casts away.
  10364. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  10365. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  10366. // Check for a call expression
  10367. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  10368. if (!CE || CE->getNumArgs() != 1)
  10369. return;
  10370. // Check for a call to std::move
  10371. if (!CE->isCallToStdMove())
  10372. return;
  10373. // Get argument from std::move
  10374. RHSExpr = CE->getArg(0);
  10375. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  10376. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  10377. // Two DeclRefExpr's, check that the decls are the same.
  10378. if (LHSDeclRef && RHSDeclRef) {
  10379. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  10380. return;
  10381. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  10382. RHSDeclRef->getDecl()->getCanonicalDecl())
  10383. return;
  10384. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  10385. << LHSExpr->getSourceRange()
  10386. << RHSExpr->getSourceRange();
  10387. return;
  10388. }
  10389. // Member variables require a different approach to check for self moves.
  10390. // MemberExpr's are the same if every nested MemberExpr refers to the same
  10391. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  10392. // the base Expr's are CXXThisExpr's.
  10393. const Expr *LHSBase = LHSExpr;
  10394. const Expr *RHSBase = RHSExpr;
  10395. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  10396. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  10397. if (!LHSME || !RHSME)
  10398. return;
  10399. while (LHSME && RHSME) {
  10400. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  10401. RHSME->getMemberDecl()->getCanonicalDecl())
  10402. return;
  10403. LHSBase = LHSME->getBase();
  10404. RHSBase = RHSME->getBase();
  10405. LHSME = dyn_cast<MemberExpr>(LHSBase);
  10406. RHSME = dyn_cast<MemberExpr>(RHSBase);
  10407. }
  10408. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  10409. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  10410. if (LHSDeclRef && RHSDeclRef) {
  10411. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  10412. return;
  10413. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  10414. RHSDeclRef->getDecl()->getCanonicalDecl())
  10415. return;
  10416. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  10417. << LHSExpr->getSourceRange()
  10418. << RHSExpr->getSourceRange();
  10419. return;
  10420. }
  10421. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  10422. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  10423. << LHSExpr->getSourceRange()
  10424. << RHSExpr->getSourceRange();
  10425. }
  10426. //===--- Layout compatibility ----------------------------------------------//
  10427. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  10428. /// \brief Check if two enumeration types are layout-compatible.
  10429. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  10430. // C++11 [dcl.enum] p8:
  10431. // Two enumeration types are layout-compatible if they have the same
  10432. // underlying type.
  10433. return ED1->isComplete() && ED2->isComplete() &&
  10434. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  10435. }
  10436. /// \brief Check if two fields are layout-compatible.
  10437. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  10438. FieldDecl *Field2) {
  10439. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  10440. return false;
  10441. if (Field1->isBitField() != Field2->isBitField())
  10442. return false;
  10443. if (Field1->isBitField()) {
  10444. // Make sure that the bit-fields are the same length.
  10445. unsigned Bits1 = Field1->getBitWidthValue(C);
  10446. unsigned Bits2 = Field2->getBitWidthValue(C);
  10447. if (Bits1 != Bits2)
  10448. return false;
  10449. }
  10450. return true;
  10451. }
  10452. /// \brief Check if two standard-layout structs are layout-compatible.
  10453. /// (C++11 [class.mem] p17)
  10454. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  10455. RecordDecl *RD2) {
  10456. // If both records are C++ classes, check that base classes match.
  10457. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  10458. // If one of records is a CXXRecordDecl we are in C++ mode,
  10459. // thus the other one is a CXXRecordDecl, too.
  10460. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  10461. // Check number of base classes.
  10462. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  10463. return false;
  10464. // Check the base classes.
  10465. for (CXXRecordDecl::base_class_const_iterator
  10466. Base1 = D1CXX->bases_begin(),
  10467. BaseEnd1 = D1CXX->bases_end(),
  10468. Base2 = D2CXX->bases_begin();
  10469. Base1 != BaseEnd1;
  10470. ++Base1, ++Base2) {
  10471. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  10472. return false;
  10473. }
  10474. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  10475. // If only RD2 is a C++ class, it should have zero base classes.
  10476. if (D2CXX->getNumBases() > 0)
  10477. return false;
  10478. }
  10479. // Check the fields.
  10480. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  10481. Field2End = RD2->field_end(),
  10482. Field1 = RD1->field_begin(),
  10483. Field1End = RD1->field_end();
  10484. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  10485. if (!isLayoutCompatible(C, *Field1, *Field2))
  10486. return false;
  10487. }
  10488. if (Field1 != Field1End || Field2 != Field2End)
  10489. return false;
  10490. return true;
  10491. }
  10492. /// \brief Check if two standard-layout unions are layout-compatible.
  10493. /// (C++11 [class.mem] p18)
  10494. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  10495. RecordDecl *RD2) {
  10496. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  10497. for (auto *Field2 : RD2->fields())
  10498. UnmatchedFields.insert(Field2);
  10499. for (auto *Field1 : RD1->fields()) {
  10500. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  10501. I = UnmatchedFields.begin(),
  10502. E = UnmatchedFields.end();
  10503. for ( ; I != E; ++I) {
  10504. if (isLayoutCompatible(C, Field1, *I)) {
  10505. bool Result = UnmatchedFields.erase(*I);
  10506. (void) Result;
  10507. assert(Result);
  10508. break;
  10509. }
  10510. }
  10511. if (I == E)
  10512. return false;
  10513. }
  10514. return UnmatchedFields.empty();
  10515. }
  10516. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  10517. RecordDecl *RD2) {
  10518. if (RD1->isUnion() != RD2->isUnion())
  10519. return false;
  10520. if (RD1->isUnion())
  10521. return isLayoutCompatibleUnion(C, RD1, RD2);
  10522. else
  10523. return isLayoutCompatibleStruct(C, RD1, RD2);
  10524. }
  10525. /// \brief Check if two types are layout-compatible in C++11 sense.
  10526. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  10527. if (T1.isNull() || T2.isNull())
  10528. return false;
  10529. // C++11 [basic.types] p11:
  10530. // If two types T1 and T2 are the same type, then T1 and T2 are
  10531. // layout-compatible types.
  10532. if (C.hasSameType(T1, T2))
  10533. return true;
  10534. T1 = T1.getCanonicalType().getUnqualifiedType();
  10535. T2 = T2.getCanonicalType().getUnqualifiedType();
  10536. const Type::TypeClass TC1 = T1->getTypeClass();
  10537. const Type::TypeClass TC2 = T2->getTypeClass();
  10538. if (TC1 != TC2)
  10539. return false;
  10540. if (TC1 == Type::Enum) {
  10541. return isLayoutCompatible(C,
  10542. cast<EnumType>(T1)->getDecl(),
  10543. cast<EnumType>(T2)->getDecl());
  10544. } else if (TC1 == Type::Record) {
  10545. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  10546. return false;
  10547. return isLayoutCompatible(C,
  10548. cast<RecordType>(T1)->getDecl(),
  10549. cast<RecordType>(T2)->getDecl());
  10550. }
  10551. return false;
  10552. }
  10553. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  10554. /// \brief Given a type tag expression find the type tag itself.
  10555. ///
  10556. /// \param TypeExpr Type tag expression, as it appears in user's code.
  10557. ///
  10558. /// \param VD Declaration of an identifier that appears in a type tag.
  10559. ///
  10560. /// \param MagicValue Type tag magic value.
  10561. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  10562. const ValueDecl **VD, uint64_t *MagicValue) {
  10563. while(true) {
  10564. if (!TypeExpr)
  10565. return false;
  10566. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  10567. switch (TypeExpr->getStmtClass()) {
  10568. case Stmt::UnaryOperatorClass: {
  10569. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  10570. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  10571. TypeExpr = UO->getSubExpr();
  10572. continue;
  10573. }
  10574. return false;
  10575. }
  10576. case Stmt::DeclRefExprClass: {
  10577. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  10578. *VD = DRE->getDecl();
  10579. return true;
  10580. }
  10581. case Stmt::IntegerLiteralClass: {
  10582. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  10583. llvm::APInt MagicValueAPInt = IL->getValue();
  10584. if (MagicValueAPInt.getActiveBits() <= 64) {
  10585. *MagicValue = MagicValueAPInt.getZExtValue();
  10586. return true;
  10587. } else
  10588. return false;
  10589. }
  10590. case Stmt::BinaryConditionalOperatorClass:
  10591. case Stmt::ConditionalOperatorClass: {
  10592. const AbstractConditionalOperator *ACO =
  10593. cast<AbstractConditionalOperator>(TypeExpr);
  10594. bool Result;
  10595. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  10596. if (Result)
  10597. TypeExpr = ACO->getTrueExpr();
  10598. else
  10599. TypeExpr = ACO->getFalseExpr();
  10600. continue;
  10601. }
  10602. return false;
  10603. }
  10604. case Stmt::BinaryOperatorClass: {
  10605. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  10606. if (BO->getOpcode() == BO_Comma) {
  10607. TypeExpr = BO->getRHS();
  10608. continue;
  10609. }
  10610. return false;
  10611. }
  10612. default:
  10613. return false;
  10614. }
  10615. }
  10616. }
  10617. /// \brief Retrieve the C type corresponding to type tag TypeExpr.
  10618. ///
  10619. /// \param TypeExpr Expression that specifies a type tag.
  10620. ///
  10621. /// \param MagicValues Registered magic values.
  10622. ///
  10623. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  10624. /// kind.
  10625. ///
  10626. /// \param TypeInfo Information about the corresponding C type.
  10627. ///
  10628. /// \returns true if the corresponding C type was found.
  10629. static bool GetMatchingCType(
  10630. const IdentifierInfo *ArgumentKind,
  10631. const Expr *TypeExpr, const ASTContext &Ctx,
  10632. const llvm::DenseMap<Sema::TypeTagMagicValue,
  10633. Sema::TypeTagData> *MagicValues,
  10634. bool &FoundWrongKind,
  10635. Sema::TypeTagData &TypeInfo) {
  10636. FoundWrongKind = false;
  10637. // Variable declaration that has type_tag_for_datatype attribute.
  10638. const ValueDecl *VD = nullptr;
  10639. uint64_t MagicValue;
  10640. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  10641. return false;
  10642. if (VD) {
  10643. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  10644. if (I->getArgumentKind() != ArgumentKind) {
  10645. FoundWrongKind = true;
  10646. return false;
  10647. }
  10648. TypeInfo.Type = I->getMatchingCType();
  10649. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  10650. TypeInfo.MustBeNull = I->getMustBeNull();
  10651. return true;
  10652. }
  10653. return false;
  10654. }
  10655. if (!MagicValues)
  10656. return false;
  10657. llvm::DenseMap<Sema::TypeTagMagicValue,
  10658. Sema::TypeTagData>::const_iterator I =
  10659. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  10660. if (I == MagicValues->end())
  10661. return false;
  10662. TypeInfo = I->second;
  10663. return true;
  10664. }
  10665. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  10666. uint64_t MagicValue, QualType Type,
  10667. bool LayoutCompatible,
  10668. bool MustBeNull) {
  10669. if (!TypeTagForDatatypeMagicValues)
  10670. TypeTagForDatatypeMagicValues.reset(
  10671. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  10672. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  10673. (*TypeTagForDatatypeMagicValues)[Magic] =
  10674. TypeTagData(Type, LayoutCompatible, MustBeNull);
  10675. }
  10676. static bool IsSameCharType(QualType T1, QualType T2) {
  10677. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  10678. if (!BT1)
  10679. return false;
  10680. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  10681. if (!BT2)
  10682. return false;
  10683. BuiltinType::Kind T1Kind = BT1->getKind();
  10684. BuiltinType::Kind T2Kind = BT2->getKind();
  10685. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  10686. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  10687. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  10688. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  10689. }
  10690. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  10691. const ArrayRef<const Expr *> ExprArgs,
  10692. SourceLocation CallSiteLoc) {
  10693. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  10694. bool IsPointerAttr = Attr->getIsPointer();
  10695. // Retrieve the argument representing the 'type_tag'.
  10696. if (Attr->getTypeTagIdx() >= ExprArgs.size()) {
  10697. // Add 1 to display the user's specified value.
  10698. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  10699. << 0 << Attr->getTypeTagIdx() + 1;
  10700. return;
  10701. }
  10702. const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
  10703. bool FoundWrongKind;
  10704. TypeTagData TypeInfo;
  10705. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  10706. TypeTagForDatatypeMagicValues.get(),
  10707. FoundWrongKind, TypeInfo)) {
  10708. if (FoundWrongKind)
  10709. Diag(TypeTagExpr->getExprLoc(),
  10710. diag::warn_type_tag_for_datatype_wrong_kind)
  10711. << TypeTagExpr->getSourceRange();
  10712. return;
  10713. }
  10714. // Retrieve the argument representing the 'arg_idx'.
  10715. if (Attr->getArgumentIdx() >= ExprArgs.size()) {
  10716. // Add 1 to display the user's specified value.
  10717. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  10718. << 1 << Attr->getArgumentIdx() + 1;
  10719. return;
  10720. }
  10721. const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
  10722. if (IsPointerAttr) {
  10723. // Skip implicit cast of pointer to `void *' (as a function argument).
  10724. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  10725. if (ICE->getType()->isVoidPointerType() &&
  10726. ICE->getCastKind() == CK_BitCast)
  10727. ArgumentExpr = ICE->getSubExpr();
  10728. }
  10729. QualType ArgumentType = ArgumentExpr->getType();
  10730. // Passing a `void*' pointer shouldn't trigger a warning.
  10731. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  10732. return;
  10733. if (TypeInfo.MustBeNull) {
  10734. // Type tag with matching void type requires a null pointer.
  10735. if (!ArgumentExpr->isNullPointerConstant(Context,
  10736. Expr::NPC_ValueDependentIsNotNull)) {
  10737. Diag(ArgumentExpr->getExprLoc(),
  10738. diag::warn_type_safety_null_pointer_required)
  10739. << ArgumentKind->getName()
  10740. << ArgumentExpr->getSourceRange()
  10741. << TypeTagExpr->getSourceRange();
  10742. }
  10743. return;
  10744. }
  10745. QualType RequiredType = TypeInfo.Type;
  10746. if (IsPointerAttr)
  10747. RequiredType = Context.getPointerType(RequiredType);
  10748. bool mismatch = false;
  10749. if (!TypeInfo.LayoutCompatible) {
  10750. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  10751. // C++11 [basic.fundamental] p1:
  10752. // Plain char, signed char, and unsigned char are three distinct types.
  10753. //
  10754. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  10755. // char' depending on the current char signedness mode.
  10756. if (mismatch)
  10757. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  10758. RequiredType->getPointeeType())) ||
  10759. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  10760. mismatch = false;
  10761. } else
  10762. if (IsPointerAttr)
  10763. mismatch = !isLayoutCompatible(Context,
  10764. ArgumentType->getPointeeType(),
  10765. RequiredType->getPointeeType());
  10766. else
  10767. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  10768. if (mismatch)
  10769. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  10770. << ArgumentType << ArgumentKind
  10771. << TypeInfo.LayoutCompatible << RequiredType
  10772. << ArgumentExpr->getSourceRange()
  10773. << TypeTagExpr->getSourceRange();
  10774. }
  10775. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  10776. CharUnits Alignment) {
  10777. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  10778. }
  10779. void Sema::DiagnoseMisalignedMembers() {
  10780. for (MisalignedMember &m : MisalignedMembers) {
  10781. const NamedDecl *ND = m.RD;
  10782. if (ND->getName().empty()) {
  10783. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  10784. ND = TD;
  10785. }
  10786. Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
  10787. << m.MD << ND << m.E->getSourceRange();
  10788. }
  10789. MisalignedMembers.clear();
  10790. }
  10791. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  10792. E = E->IgnoreParens();
  10793. if (!T->isPointerType() && !T->isIntegerType())
  10794. return;
  10795. if (isa<UnaryOperator>(E) &&
  10796. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  10797. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  10798. if (isa<MemberExpr>(Op)) {
  10799. auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
  10800. MisalignedMember(Op));
  10801. if (MA != MisalignedMembers.end() &&
  10802. (T->isIntegerType() ||
  10803. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  10804. Context.getTypeAlignInChars(
  10805. T->getPointeeType()) <= MA->Alignment))))
  10806. MisalignedMembers.erase(MA);
  10807. }
  10808. }
  10809. }
  10810. void Sema::RefersToMemberWithReducedAlignment(
  10811. Expr *E,
  10812. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  10813. Action) {
  10814. const auto *ME = dyn_cast<MemberExpr>(E);
  10815. if (!ME)
  10816. return;
  10817. // No need to check expressions with an __unaligned-qualified type.
  10818. if (E->getType().getQualifiers().hasUnaligned())
  10819. return;
  10820. // For a chain of MemberExpr like "a.b.c.d" this list
  10821. // will keep FieldDecl's like [d, c, b].
  10822. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  10823. const MemberExpr *TopME = nullptr;
  10824. bool AnyIsPacked = false;
  10825. do {
  10826. QualType BaseType = ME->getBase()->getType();
  10827. if (ME->isArrow())
  10828. BaseType = BaseType->getPointeeType();
  10829. RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
  10830. if (RD->isInvalidDecl())
  10831. return;
  10832. ValueDecl *MD = ME->getMemberDecl();
  10833. auto *FD = dyn_cast<FieldDecl>(MD);
  10834. // We do not care about non-data members.
  10835. if (!FD || FD->isInvalidDecl())
  10836. return;
  10837. AnyIsPacked =
  10838. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  10839. ReverseMemberChain.push_back(FD);
  10840. TopME = ME;
  10841. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  10842. } while (ME);
  10843. assert(TopME && "We did not compute a topmost MemberExpr!");
  10844. // Not the scope of this diagnostic.
  10845. if (!AnyIsPacked)
  10846. return;
  10847. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  10848. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  10849. // TODO: The innermost base of the member expression may be too complicated.
  10850. // For now, just disregard these cases. This is left for future
  10851. // improvement.
  10852. if (!DRE && !isa<CXXThisExpr>(TopBase))
  10853. return;
  10854. // Alignment expected by the whole expression.
  10855. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  10856. // No need to do anything else with this case.
  10857. if (ExpectedAlignment.isOne())
  10858. return;
  10859. // Synthesize offset of the whole access.
  10860. CharUnits Offset;
  10861. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  10862. I++) {
  10863. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  10864. }
  10865. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  10866. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  10867. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  10868. // The base expression of the innermost MemberExpr may give
  10869. // stronger guarantees than the class containing the member.
  10870. if (DRE && !TopME->isArrow()) {
  10871. const ValueDecl *VD = DRE->getDecl();
  10872. if (!VD->getType()->isReferenceType())
  10873. CompleteObjectAlignment =
  10874. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  10875. }
  10876. // Check if the synthesized offset fulfills the alignment.
  10877. if (Offset % ExpectedAlignment != 0 ||
  10878. // It may fulfill the offset it but the effective alignment may still be
  10879. // lower than the expected expression alignment.
  10880. CompleteObjectAlignment < ExpectedAlignment) {
  10881. // If this happens, we want to determine a sensible culprit of this.
  10882. // Intuitively, watching the chain of member expressions from right to
  10883. // left, we start with the required alignment (as required by the field
  10884. // type) but some packed attribute in that chain has reduced the alignment.
  10885. // It may happen that another packed structure increases it again. But if
  10886. // we are here such increase has not been enough. So pointing the first
  10887. // FieldDecl that either is packed or else its RecordDecl is,
  10888. // seems reasonable.
  10889. FieldDecl *FD = nullptr;
  10890. CharUnits Alignment;
  10891. for (FieldDecl *FDI : ReverseMemberChain) {
  10892. if (FDI->hasAttr<PackedAttr>() ||
  10893. FDI->getParent()->hasAttr<PackedAttr>()) {
  10894. FD = FDI;
  10895. Alignment = std::min(
  10896. Context.getTypeAlignInChars(FD->getType()),
  10897. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  10898. break;
  10899. }
  10900. }
  10901. assert(FD && "We did not find a packed FieldDecl!");
  10902. Action(E, FD->getParent(), FD, Alignment);
  10903. }
  10904. }
  10905. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  10906. using namespace std::placeholders;
  10907. RefersToMemberWithReducedAlignment(
  10908. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  10909. _2, _3, _4));
  10910. }