SemaChecking.cpp 554 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225
  1. //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements extra semantic analysis beyond what is enforced
  10. // by the C type system.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/APValue.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/AttrIterator.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclBase.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclarationName.h"
  23. #include "clang/AST/EvaluatedExprVisitor.h"
  24. #include "clang/AST/Expr.h"
  25. #include "clang/AST/ExprCXX.h"
  26. #include "clang/AST/ExprObjC.h"
  27. #include "clang/AST/ExprOpenMP.h"
  28. #include "clang/AST/FormatString.h"
  29. #include "clang/AST/NSAPI.h"
  30. #include "clang/AST/NonTrivialTypeVisitor.h"
  31. #include "clang/AST/OperationKinds.h"
  32. #include "clang/AST/Stmt.h"
  33. #include "clang/AST/TemplateBase.h"
  34. #include "clang/AST/Type.h"
  35. #include "clang/AST/TypeLoc.h"
  36. #include "clang/AST/UnresolvedSet.h"
  37. #include "clang/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->getEndLoc(), 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)->getBeginLoc(),
  114. call->getArg(argCount - 1)->getEndLoc());
  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->getBeginLoc(), 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->getBeginLoc(), 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->getEndLoc(), 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->getBeginLoc(), 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->getBeginLoc());
  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. ExprResult Arg = TheCall->getArg(I);
  181. QualType Ty = Arg.get()->getType();
  182. if (!Ty->isIntegerType()) {
  183. S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
  184. << Ty << Arg.get()->getSourceRange();
  185. return true;
  186. }
  187. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  188. S.getASTContext(), Ty, /*consume*/ false);
  189. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  190. if (Arg.isInvalid())
  191. return true;
  192. TheCall->setArg(I, Arg.get());
  193. }
  194. // Third argument should be a pointer to a non-const integer.
  195. // IRGen correctly handles volatile, restrict, and address spaces, and
  196. // the other qualifiers aren't possible.
  197. {
  198. ExprResult Arg = TheCall->getArg(2);
  199. QualType Ty = Arg.get()->getType();
  200. const auto *PtrTy = Ty->getAs<PointerType>();
  201. if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
  202. !PtrTy->getPointeeType().isConstQualified())) {
  203. S.Diag(Arg.get()->getBeginLoc(),
  204. diag::err_overflow_builtin_must_be_ptr_int)
  205. << Ty << Arg.get()->getSourceRange();
  206. return true;
  207. }
  208. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  209. S.getASTContext(), Ty, /*consume*/ false);
  210. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  211. if (Arg.isInvalid())
  212. return true;
  213. TheCall->setArg(2, Arg.get());
  214. }
  215. return false;
  216. }
  217. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  218. if (checkArgCount(S, BuiltinCall, 2))
  219. return true;
  220. SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
  221. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  222. Expr *Call = BuiltinCall->getArg(0);
  223. Expr *Chain = BuiltinCall->getArg(1);
  224. if (Call->getStmtClass() != Stmt::CallExprClass) {
  225. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  226. << Call->getSourceRange();
  227. return true;
  228. }
  229. auto CE = cast<CallExpr>(Call);
  230. if (CE->getCallee()->getType()->isBlockPointerType()) {
  231. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  232. << Call->getSourceRange();
  233. return true;
  234. }
  235. const Decl *TargetDecl = CE->getCalleeDecl();
  236. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  237. if (FD->getBuiltinID()) {
  238. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  239. << Call->getSourceRange();
  240. return true;
  241. }
  242. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  243. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  244. << Call->getSourceRange();
  245. return true;
  246. }
  247. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  248. if (ChainResult.isInvalid())
  249. return true;
  250. if (!ChainResult.get()->getType()->isPointerType()) {
  251. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  252. << Chain->getSourceRange();
  253. return true;
  254. }
  255. QualType ReturnTy = CE->getCallReturnType(S.Context);
  256. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  257. QualType BuiltinTy = S.Context.getFunctionType(
  258. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  259. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  260. Builtin =
  261. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  262. BuiltinCall->setType(CE->getType());
  263. BuiltinCall->setValueKind(CE->getValueKind());
  264. BuiltinCall->setObjectKind(CE->getObjectKind());
  265. BuiltinCall->setCallee(Builtin);
  266. BuiltinCall->setArg(1, ChainResult.get());
  267. return false;
  268. }
  269. /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
  270. /// __builtin_*_chk function, then use the object size argument specified in the
  271. /// source. Otherwise, infer the object size using __builtin_object_size.
  272. void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
  273. CallExpr *TheCall) {
  274. // FIXME: There are some more useful checks we could be doing here:
  275. // - Analyze the format string of sprintf to see how much of buffer is used.
  276. // - Evaluate strlen of strcpy arguments, use as object size.
  277. if (TheCall->isValueDependent() || TheCall->isTypeDependent())
  278. return;
  279. unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
  280. if (!BuiltinID)
  281. return;
  282. unsigned DiagID = 0;
  283. bool IsChkVariant = false;
  284. unsigned SizeIndex, ObjectIndex;
  285. switch (BuiltinID) {
  286. default:
  287. return;
  288. case Builtin::BI__builtin___memcpy_chk:
  289. case Builtin::BI__builtin___memmove_chk:
  290. case Builtin::BI__builtin___memset_chk:
  291. case Builtin::BI__builtin___strlcat_chk:
  292. case Builtin::BI__builtin___strlcpy_chk:
  293. case Builtin::BI__builtin___strncat_chk:
  294. case Builtin::BI__builtin___strncpy_chk:
  295. case Builtin::BI__builtin___stpncpy_chk:
  296. case Builtin::BI__builtin___memccpy_chk: {
  297. DiagID = diag::warn_builtin_chk_overflow;
  298. IsChkVariant = true;
  299. SizeIndex = TheCall->getNumArgs() - 2;
  300. ObjectIndex = TheCall->getNumArgs() - 1;
  301. break;
  302. }
  303. case Builtin::BI__builtin___snprintf_chk:
  304. case Builtin::BI__builtin___vsnprintf_chk: {
  305. DiagID = diag::warn_builtin_chk_overflow;
  306. IsChkVariant = true;
  307. SizeIndex = 1;
  308. ObjectIndex = 3;
  309. break;
  310. }
  311. case Builtin::BIstrncat:
  312. case Builtin::BI__builtin_strncat:
  313. case Builtin::BIstrncpy:
  314. case Builtin::BI__builtin_strncpy:
  315. case Builtin::BIstpncpy:
  316. case Builtin::BI__builtin_stpncpy: {
  317. // Whether these functions overflow depends on the runtime strlen of the
  318. // string, not just the buffer size, so emitting the "always overflow"
  319. // diagnostic isn't quite right. We should still diagnose passing a buffer
  320. // size larger than the destination buffer though; this is a runtime abort
  321. // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
  322. DiagID = diag::warn_fortify_source_size_mismatch;
  323. SizeIndex = TheCall->getNumArgs() - 1;
  324. ObjectIndex = 0;
  325. break;
  326. }
  327. case Builtin::BImemcpy:
  328. case Builtin::BI__builtin_memcpy:
  329. case Builtin::BImemmove:
  330. case Builtin::BI__builtin_memmove:
  331. case Builtin::BImemset:
  332. case Builtin::BI__builtin_memset: {
  333. DiagID = diag::warn_fortify_source_overflow;
  334. SizeIndex = TheCall->getNumArgs() - 1;
  335. ObjectIndex = 0;
  336. break;
  337. }
  338. case Builtin::BIsnprintf:
  339. case Builtin::BI__builtin_snprintf:
  340. case Builtin::BIvsnprintf:
  341. case Builtin::BI__builtin_vsnprintf: {
  342. DiagID = diag::warn_fortify_source_size_mismatch;
  343. SizeIndex = 1;
  344. ObjectIndex = 0;
  345. break;
  346. }
  347. }
  348. llvm::APSInt ObjectSize;
  349. // For __builtin___*_chk, the object size is explicitly provided by the caller
  350. // (usually using __builtin_object_size). Use that value to check this call.
  351. if (IsChkVariant) {
  352. Expr::EvalResult Result;
  353. Expr *SizeArg = TheCall->getArg(ObjectIndex);
  354. if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
  355. return;
  356. ObjectSize = Result.Val.getInt();
  357. // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
  358. } else {
  359. // If the parameter has a pass_object_size attribute, then we should use its
  360. // (potentially) more strict checking mode. Otherwise, conservatively assume
  361. // type 0.
  362. int BOSType = 0;
  363. if (const auto *POS =
  364. FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
  365. BOSType = POS->getType();
  366. Expr *ObjArg = TheCall->getArg(ObjectIndex);
  367. uint64_t Result;
  368. if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
  369. return;
  370. // Get the object size in the target's size_t width.
  371. const TargetInfo &TI = getASTContext().getTargetInfo();
  372. unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
  373. ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
  374. }
  375. // Evaluate the number of bytes of the object that this call will use.
  376. Expr::EvalResult Result;
  377. Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
  378. if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
  379. return;
  380. llvm::APSInt UsedSize = Result.Val.getInt();
  381. if (UsedSize.ule(ObjectSize))
  382. return;
  383. StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
  384. // Skim off the details of whichever builtin was called to produce a better
  385. // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
  386. if (IsChkVariant) {
  387. FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
  388. FunctionName = FunctionName.drop_back(std::strlen("_chk"));
  389. } else if (FunctionName.startswith("__builtin_")) {
  390. FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
  391. }
  392. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  393. PDiag(DiagID)
  394. << FunctionName << ObjectSize.toString(/*Radix=*/10)
  395. << UsedSize.toString(/*Radix=*/10));
  396. }
  397. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  398. Scope::ScopeFlags NeededScopeFlags,
  399. unsigned DiagID) {
  400. // Scopes aren't available during instantiation. Fortunately, builtin
  401. // functions cannot be template args so they cannot be formed through template
  402. // instantiation. Therefore checking once during the parse is sufficient.
  403. if (SemaRef.inTemplateInstantiation())
  404. return false;
  405. Scope *S = SemaRef.getCurScope();
  406. while (S && !S->isSEHExceptScope())
  407. S = S->getParent();
  408. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  409. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  410. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  411. << DRE->getDecl()->getIdentifier();
  412. return true;
  413. }
  414. return false;
  415. }
  416. static inline bool isBlockPointer(Expr *Arg) {
  417. return Arg->getType()->isBlockPointerType();
  418. }
  419. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  420. /// void*, which is a requirement of device side enqueue.
  421. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  422. const BlockPointerType *BPT =
  423. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  424. ArrayRef<QualType> Params =
  425. BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
  426. unsigned ArgCounter = 0;
  427. bool IllegalParams = false;
  428. // Iterate through the block parameters until either one is found that is not
  429. // a local void*, or the block is valid.
  430. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  431. I != E; ++I, ++ArgCounter) {
  432. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  433. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  434. LangAS::opencl_local) {
  435. // Get the location of the error. If a block literal has been passed
  436. // (BlockExpr) then we can point straight to the offending argument,
  437. // else we just point to the variable reference.
  438. SourceLocation ErrorLoc;
  439. if (isa<BlockExpr>(BlockArg)) {
  440. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  441. ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
  442. } else if (isa<DeclRefExpr>(BlockArg)) {
  443. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
  444. }
  445. S.Diag(ErrorLoc,
  446. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  447. IllegalParams = true;
  448. }
  449. }
  450. return IllegalParams;
  451. }
  452. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  453. if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
  454. S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
  455. << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
  456. return true;
  457. }
  458. return false;
  459. }
  460. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  461. if (checkArgCount(S, TheCall, 2))
  462. return true;
  463. if (checkOpenCLSubgroupExt(S, TheCall))
  464. return true;
  465. // First argument is an ndrange_t type.
  466. Expr *NDRangeArg = TheCall->getArg(0);
  467. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  468. S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  469. << TheCall->getDirectCallee() << "'ndrange_t'";
  470. return true;
  471. }
  472. Expr *BlockArg = TheCall->getArg(1);
  473. if (!isBlockPointer(BlockArg)) {
  474. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  475. << TheCall->getDirectCallee() << "block";
  476. return true;
  477. }
  478. return checkOpenCLBlockArgs(S, BlockArg);
  479. }
  480. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  481. /// get_kernel_work_group_size
  482. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  483. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  484. if (checkArgCount(S, TheCall, 1))
  485. return true;
  486. Expr *BlockArg = TheCall->getArg(0);
  487. if (!isBlockPointer(BlockArg)) {
  488. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  489. << TheCall->getDirectCallee() << "block";
  490. return true;
  491. }
  492. return checkOpenCLBlockArgs(S, BlockArg);
  493. }
  494. /// Diagnose integer type and any valid implicit conversion to it.
  495. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  496. const QualType &IntType);
  497. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  498. unsigned Start, unsigned End) {
  499. bool IllegalParams = false;
  500. for (unsigned I = Start; I <= End; ++I)
  501. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  502. S.Context.getSizeType());
  503. return IllegalParams;
  504. }
  505. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  506. /// 'local void*' parameter of passed block.
  507. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  508. Expr *BlockArg,
  509. unsigned NumNonVarArgs) {
  510. const BlockPointerType *BPT =
  511. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  512. unsigned NumBlockParams =
  513. BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
  514. unsigned TotalNumArgs = TheCall->getNumArgs();
  515. // For each argument passed to the block, a corresponding uint needs to
  516. // be passed to describe the size of the local memory.
  517. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  518. S.Diag(TheCall->getBeginLoc(),
  519. diag::err_opencl_enqueue_kernel_local_size_args);
  520. return true;
  521. }
  522. // Check that the sizes of the local memory are specified by integers.
  523. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  524. TotalNumArgs - 1);
  525. }
  526. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  527. /// overload formats specified in Table 6.13.17.1.
  528. /// int enqueue_kernel(queue_t queue,
  529. /// kernel_enqueue_flags_t flags,
  530. /// const ndrange_t ndrange,
  531. /// void (^block)(void))
  532. /// int enqueue_kernel(queue_t queue,
  533. /// kernel_enqueue_flags_t flags,
  534. /// const ndrange_t ndrange,
  535. /// uint num_events_in_wait_list,
  536. /// clk_event_t *event_wait_list,
  537. /// clk_event_t *event_ret,
  538. /// void (^block)(void))
  539. /// int enqueue_kernel(queue_t queue,
  540. /// kernel_enqueue_flags_t flags,
  541. /// const ndrange_t ndrange,
  542. /// void (^block)(local void*, ...),
  543. /// uint size0, ...)
  544. /// int enqueue_kernel(queue_t queue,
  545. /// kernel_enqueue_flags_t flags,
  546. /// const ndrange_t ndrange,
  547. /// uint num_events_in_wait_list,
  548. /// clk_event_t *event_wait_list,
  549. /// clk_event_t *event_ret,
  550. /// void (^block)(local void*, ...),
  551. /// uint size0, ...)
  552. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  553. unsigned NumArgs = TheCall->getNumArgs();
  554. if (NumArgs < 4) {
  555. S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
  556. return true;
  557. }
  558. Expr *Arg0 = TheCall->getArg(0);
  559. Expr *Arg1 = TheCall->getArg(1);
  560. Expr *Arg2 = TheCall->getArg(2);
  561. Expr *Arg3 = TheCall->getArg(3);
  562. // First argument always needs to be a queue_t type.
  563. if (!Arg0->getType()->isQueueT()) {
  564. S.Diag(TheCall->getArg(0)->getBeginLoc(),
  565. diag::err_opencl_builtin_expected_type)
  566. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  567. return true;
  568. }
  569. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  570. if (!Arg1->getType()->isIntegerType()) {
  571. S.Diag(TheCall->getArg(1)->getBeginLoc(),
  572. diag::err_opencl_builtin_expected_type)
  573. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  574. return true;
  575. }
  576. // Third argument is always an ndrange_t type.
  577. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  578. S.Diag(TheCall->getArg(2)->getBeginLoc(),
  579. diag::err_opencl_builtin_expected_type)
  580. << TheCall->getDirectCallee() << "'ndrange_t'";
  581. return true;
  582. }
  583. // With four arguments, there is only one form that the function could be
  584. // called in: no events and no variable arguments.
  585. if (NumArgs == 4) {
  586. // check that the last argument is the right block type.
  587. if (!isBlockPointer(Arg3)) {
  588. S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  589. << TheCall->getDirectCallee() << "block";
  590. return true;
  591. }
  592. // we have a block type, check the prototype
  593. const BlockPointerType *BPT =
  594. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  595. if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
  596. S.Diag(Arg3->getBeginLoc(),
  597. diag::err_opencl_enqueue_kernel_blocks_no_args);
  598. return true;
  599. }
  600. return false;
  601. }
  602. // we can have block + varargs.
  603. if (isBlockPointer(Arg3))
  604. return (checkOpenCLBlockArgs(S, Arg3) ||
  605. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  606. // last two cases with either exactly 7 args or 7 args and varargs.
  607. if (NumArgs >= 7) {
  608. // check common block argument.
  609. Expr *Arg6 = TheCall->getArg(6);
  610. if (!isBlockPointer(Arg6)) {
  611. S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  612. << TheCall->getDirectCallee() << "block";
  613. return true;
  614. }
  615. if (checkOpenCLBlockArgs(S, Arg6))
  616. return true;
  617. // Forth argument has to be any integer type.
  618. if (!Arg3->getType()->isIntegerType()) {
  619. S.Diag(TheCall->getArg(3)->getBeginLoc(),
  620. diag::err_opencl_builtin_expected_type)
  621. << TheCall->getDirectCallee() << "integer";
  622. return true;
  623. }
  624. // check remaining common arguments.
  625. Expr *Arg4 = TheCall->getArg(4);
  626. Expr *Arg5 = TheCall->getArg(5);
  627. // Fifth argument is always passed as a pointer to clk_event_t.
  628. if (!Arg4->isNullPointerConstant(S.Context,
  629. Expr::NPC_ValueDependentIsNotNull) &&
  630. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  631. S.Diag(TheCall->getArg(4)->getBeginLoc(),
  632. diag::err_opencl_builtin_expected_type)
  633. << TheCall->getDirectCallee()
  634. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  635. return true;
  636. }
  637. // Sixth argument is always passed as a pointer to clk_event_t.
  638. if (!Arg5->isNullPointerConstant(S.Context,
  639. Expr::NPC_ValueDependentIsNotNull) &&
  640. !(Arg5->getType()->isPointerType() &&
  641. Arg5->getType()->getPointeeType()->isClkEventT())) {
  642. S.Diag(TheCall->getArg(5)->getBeginLoc(),
  643. diag::err_opencl_builtin_expected_type)
  644. << TheCall->getDirectCallee()
  645. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  646. return true;
  647. }
  648. if (NumArgs == 7)
  649. return false;
  650. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  651. }
  652. // None of the specific case has been detected, give generic error
  653. S.Diag(TheCall->getBeginLoc(),
  654. diag::err_opencl_enqueue_kernel_incorrect_args);
  655. return true;
  656. }
  657. /// Returns OpenCL access qual.
  658. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  659. return D->getAttr<OpenCLAccessAttr>();
  660. }
  661. /// Returns true if pipe element type is different from the pointer.
  662. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  663. const Expr *Arg0 = Call->getArg(0);
  664. // First argument type should always be pipe.
  665. if (!Arg0->getType()->isPipeType()) {
  666. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  667. << Call->getDirectCallee() << Arg0->getSourceRange();
  668. return true;
  669. }
  670. OpenCLAccessAttr *AccessQual =
  671. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  672. // Validates the access qualifier is compatible with the call.
  673. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  674. // read_only and write_only, and assumed to be read_only if no qualifier is
  675. // specified.
  676. switch (Call->getDirectCallee()->getBuiltinID()) {
  677. case Builtin::BIread_pipe:
  678. case Builtin::BIreserve_read_pipe:
  679. case Builtin::BIcommit_read_pipe:
  680. case Builtin::BIwork_group_reserve_read_pipe:
  681. case Builtin::BIsub_group_reserve_read_pipe:
  682. case Builtin::BIwork_group_commit_read_pipe:
  683. case Builtin::BIsub_group_commit_read_pipe:
  684. if (!(!AccessQual || AccessQual->isReadOnly())) {
  685. S.Diag(Arg0->getBeginLoc(),
  686. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  687. << "read_only" << Arg0->getSourceRange();
  688. return true;
  689. }
  690. break;
  691. case Builtin::BIwrite_pipe:
  692. case Builtin::BIreserve_write_pipe:
  693. case Builtin::BIcommit_write_pipe:
  694. case Builtin::BIwork_group_reserve_write_pipe:
  695. case Builtin::BIsub_group_reserve_write_pipe:
  696. case Builtin::BIwork_group_commit_write_pipe:
  697. case Builtin::BIsub_group_commit_write_pipe:
  698. if (!(AccessQual && AccessQual->isWriteOnly())) {
  699. S.Diag(Arg0->getBeginLoc(),
  700. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  701. << "write_only" << Arg0->getSourceRange();
  702. return true;
  703. }
  704. break;
  705. default:
  706. break;
  707. }
  708. return false;
  709. }
  710. /// Returns true if pipe element type is different from the pointer.
  711. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  712. const Expr *Arg0 = Call->getArg(0);
  713. const Expr *ArgIdx = Call->getArg(Idx);
  714. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  715. const QualType EltTy = PipeTy->getElementType();
  716. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  717. // The Idx argument should be a pointer and the type of the pointer and
  718. // the type of pipe element should also be the same.
  719. if (!ArgTy ||
  720. !S.Context.hasSameType(
  721. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  722. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  723. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  724. << ArgIdx->getType() << ArgIdx->getSourceRange();
  725. return true;
  726. }
  727. return false;
  728. }
  729. // Performs semantic analysis for the read/write_pipe call.
  730. // \param S Reference to the semantic analyzer.
  731. // \param Call A pointer to the builtin call.
  732. // \return True if a semantic error has been found, false otherwise.
  733. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  734. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  735. // functions have two forms.
  736. switch (Call->getNumArgs()) {
  737. case 2:
  738. if (checkOpenCLPipeArg(S, Call))
  739. return true;
  740. // The call with 2 arguments should be
  741. // read/write_pipe(pipe T, T*).
  742. // Check packet type T.
  743. if (checkOpenCLPipePacketType(S, Call, 1))
  744. return true;
  745. break;
  746. case 4: {
  747. if (checkOpenCLPipeArg(S, Call))
  748. return true;
  749. // The call with 4 arguments should be
  750. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  751. // Check reserve_id_t.
  752. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  753. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  754. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  755. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  756. return true;
  757. }
  758. // Check the index.
  759. const Expr *Arg2 = Call->getArg(2);
  760. if (!Arg2->getType()->isIntegerType() &&
  761. !Arg2->getType()->isUnsignedIntegerType()) {
  762. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  763. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  764. << Arg2->getType() << Arg2->getSourceRange();
  765. return true;
  766. }
  767. // Check packet type T.
  768. if (checkOpenCLPipePacketType(S, Call, 3))
  769. return true;
  770. } break;
  771. default:
  772. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
  773. << Call->getDirectCallee() << Call->getSourceRange();
  774. return true;
  775. }
  776. return false;
  777. }
  778. // Performs a semantic analysis on the {work_group_/sub_group_
  779. // /_}reserve_{read/write}_pipe
  780. // \param S Reference to the semantic analyzer.
  781. // \param Call The call to the builtin function to be analyzed.
  782. // \return True if a semantic error was found, false otherwise.
  783. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  784. if (checkArgCount(S, Call, 2))
  785. return true;
  786. if (checkOpenCLPipeArg(S, Call))
  787. return true;
  788. // Check the reserve size.
  789. if (!Call->getArg(1)->getType()->isIntegerType() &&
  790. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  791. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  792. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  793. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  794. return true;
  795. }
  796. // Since return type of reserve_read/write_pipe built-in function is
  797. // reserve_id_t, which is not defined in the builtin def file , we used int
  798. // as return type and need to override the return type of these functions.
  799. Call->setType(S.Context.OCLReserveIDTy);
  800. return false;
  801. }
  802. // Performs a semantic analysis on {work_group_/sub_group_
  803. // /_}commit_{read/write}_pipe
  804. // \param S Reference to the semantic analyzer.
  805. // \param Call The call to the builtin function to be analyzed.
  806. // \return True if a semantic error was found, false otherwise.
  807. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  808. if (checkArgCount(S, Call, 2))
  809. return true;
  810. if (checkOpenCLPipeArg(S, Call))
  811. return true;
  812. // Check reserve_id_t.
  813. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  814. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  815. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  816. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  817. return true;
  818. }
  819. return false;
  820. }
  821. // Performs a semantic analysis on the call to built-in Pipe
  822. // Query Functions.
  823. // \param S Reference to the semantic analyzer.
  824. // \param Call The call to the builtin function to be analyzed.
  825. // \return True if a semantic error was found, false otherwise.
  826. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  827. if (checkArgCount(S, Call, 1))
  828. return true;
  829. if (!Call->getArg(0)->getType()->isPipeType()) {
  830. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  831. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  832. return true;
  833. }
  834. return false;
  835. }
  836. // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  837. // Performs semantic analysis for the to_global/local/private call.
  838. // \param S Reference to the semantic analyzer.
  839. // \param BuiltinID ID of the builtin function.
  840. // \param Call A pointer to the builtin call.
  841. // \return True if a semantic error has been found, false otherwise.
  842. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  843. CallExpr *Call) {
  844. if (Call->getNumArgs() != 1) {
  845. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
  846. << Call->getDirectCallee() << Call->getSourceRange();
  847. return true;
  848. }
  849. auto RT = Call->getArg(0)->getType();
  850. if (!RT->isPointerType() || RT->getPointeeType()
  851. .getAddressSpace() == LangAS::opencl_constant) {
  852. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
  853. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  854. return true;
  855. }
  856. if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
  857. S.Diag(Call->getArg(0)->getBeginLoc(),
  858. diag::warn_opencl_generic_address_space_arg)
  859. << Call->getDirectCallee()->getNameInfo().getAsString()
  860. << Call->getArg(0)->getSourceRange();
  861. }
  862. RT = RT->getPointeeType();
  863. auto Qual = RT.getQualifiers();
  864. switch (BuiltinID) {
  865. case Builtin::BIto_global:
  866. Qual.setAddressSpace(LangAS::opencl_global);
  867. break;
  868. case Builtin::BIto_local:
  869. Qual.setAddressSpace(LangAS::opencl_local);
  870. break;
  871. case Builtin::BIto_private:
  872. Qual.setAddressSpace(LangAS::opencl_private);
  873. break;
  874. default:
  875. llvm_unreachable("Invalid builtin function");
  876. }
  877. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  878. RT.getUnqualifiedType(), Qual)));
  879. return false;
  880. }
  881. static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
  882. if (checkArgCount(S, TheCall, 1))
  883. return ExprError();
  884. // Compute __builtin_launder's parameter type from the argument.
  885. // The parameter type is:
  886. // * The type of the argument if it's not an array or function type,
  887. // Otherwise,
  888. // * The decayed argument type.
  889. QualType ParamTy = [&]() {
  890. QualType ArgTy = TheCall->getArg(0)->getType();
  891. if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
  892. return S.Context.getPointerType(Ty->getElementType());
  893. if (ArgTy->isFunctionType()) {
  894. return S.Context.getPointerType(ArgTy);
  895. }
  896. return ArgTy;
  897. }();
  898. TheCall->setType(ParamTy);
  899. auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
  900. if (!ParamTy->isPointerType())
  901. return 0;
  902. if (ParamTy->isFunctionPointerType())
  903. return 1;
  904. if (ParamTy->isVoidPointerType())
  905. return 2;
  906. return llvm::Optional<unsigned>{};
  907. }();
  908. if (DiagSelect.hasValue()) {
  909. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
  910. << DiagSelect.getValue() << TheCall->getSourceRange();
  911. return ExprError();
  912. }
  913. // We either have an incomplete class type, or we have a class template
  914. // whose instantiation has not been forced. Example:
  915. //
  916. // template <class T> struct Foo { T value; };
  917. // Foo<int> *p = nullptr;
  918. // auto *d = __builtin_launder(p);
  919. if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
  920. diag::err_incomplete_type))
  921. return ExprError();
  922. assert(ParamTy->getPointeeType()->isObjectType() &&
  923. "Unhandled non-object pointer case");
  924. InitializedEntity Entity =
  925. InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
  926. ExprResult Arg =
  927. S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
  928. if (Arg.isInvalid())
  929. return ExprError();
  930. TheCall->setArg(0, Arg.get());
  931. return TheCall;
  932. }
  933. // Emit an error and return true if the current architecture is not in the list
  934. // of supported architectures.
  935. static bool
  936. CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
  937. ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
  938. llvm::Triple::ArchType CurArch =
  939. S.getASTContext().getTargetInfo().getTriple().getArch();
  940. if (llvm::is_contained(SupportedArchs, CurArch))
  941. return false;
  942. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  943. << TheCall->getSourceRange();
  944. return true;
  945. }
  946. ExprResult
  947. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  948. CallExpr *TheCall) {
  949. ExprResult TheCallResult(TheCall);
  950. // Find out if any arguments are required to be integer constant expressions.
  951. unsigned ICEArguments = 0;
  952. ASTContext::GetBuiltinTypeError Error;
  953. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  954. if (Error != ASTContext::GE_None)
  955. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  956. // If any arguments are required to be ICE's, check and diagnose.
  957. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  958. // Skip arguments not required to be ICE's.
  959. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  960. llvm::APSInt Result;
  961. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  962. return true;
  963. ICEArguments &= ~(1 << ArgNo);
  964. }
  965. switch (BuiltinID) {
  966. case Builtin::BI__builtin___CFStringMakeConstantString:
  967. assert(TheCall->getNumArgs() == 1 &&
  968. "Wrong # arguments to builtin CFStringMakeConstantString");
  969. if (CheckObjCString(TheCall->getArg(0)))
  970. return ExprError();
  971. break;
  972. case Builtin::BI__builtin_ms_va_start:
  973. case Builtin::BI__builtin_stdarg_start:
  974. case Builtin::BI__builtin_va_start:
  975. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  976. return ExprError();
  977. break;
  978. case Builtin::BI__va_start: {
  979. switch (Context.getTargetInfo().getTriple().getArch()) {
  980. case llvm::Triple::aarch64:
  981. case llvm::Triple::arm:
  982. case llvm::Triple::thumb:
  983. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  984. return ExprError();
  985. break;
  986. default:
  987. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  988. return ExprError();
  989. break;
  990. }
  991. break;
  992. }
  993. // The acquire, release, and no fence variants are ARM and AArch64 only.
  994. case Builtin::BI_interlockedbittestandset_acq:
  995. case Builtin::BI_interlockedbittestandset_rel:
  996. case Builtin::BI_interlockedbittestandset_nf:
  997. case Builtin::BI_interlockedbittestandreset_acq:
  998. case Builtin::BI_interlockedbittestandreset_rel:
  999. case Builtin::BI_interlockedbittestandreset_nf:
  1000. if (CheckBuiltinTargetSupport(
  1001. *this, BuiltinID, TheCall,
  1002. {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
  1003. return ExprError();
  1004. break;
  1005. // The 64-bit bittest variants are x64, ARM, and AArch64 only.
  1006. case Builtin::BI_bittest64:
  1007. case Builtin::BI_bittestandcomplement64:
  1008. case Builtin::BI_bittestandreset64:
  1009. case Builtin::BI_bittestandset64:
  1010. case Builtin::BI_interlockedbittestandreset64:
  1011. case Builtin::BI_interlockedbittestandset64:
  1012. if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
  1013. {llvm::Triple::x86_64, llvm::Triple::arm,
  1014. llvm::Triple::thumb, llvm::Triple::aarch64}))
  1015. return ExprError();
  1016. break;
  1017. case Builtin::BI__builtin_isgreater:
  1018. case Builtin::BI__builtin_isgreaterequal:
  1019. case Builtin::BI__builtin_isless:
  1020. case Builtin::BI__builtin_islessequal:
  1021. case Builtin::BI__builtin_islessgreater:
  1022. case Builtin::BI__builtin_isunordered:
  1023. if (SemaBuiltinUnorderedCompare(TheCall))
  1024. return ExprError();
  1025. break;
  1026. case Builtin::BI__builtin_fpclassify:
  1027. if (SemaBuiltinFPClassification(TheCall, 6))
  1028. return ExprError();
  1029. break;
  1030. case Builtin::BI__builtin_isfinite:
  1031. case Builtin::BI__builtin_isinf:
  1032. case Builtin::BI__builtin_isinf_sign:
  1033. case Builtin::BI__builtin_isnan:
  1034. case Builtin::BI__builtin_isnormal:
  1035. case Builtin::BI__builtin_signbit:
  1036. case Builtin::BI__builtin_signbitf:
  1037. case Builtin::BI__builtin_signbitl:
  1038. if (SemaBuiltinFPClassification(TheCall, 1))
  1039. return ExprError();
  1040. break;
  1041. case Builtin::BI__builtin_shufflevector:
  1042. return SemaBuiltinShuffleVector(TheCall);
  1043. // TheCall will be freed by the smart pointer here, but that's fine, since
  1044. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  1045. case Builtin::BI__builtin_prefetch:
  1046. if (SemaBuiltinPrefetch(TheCall))
  1047. return ExprError();
  1048. break;
  1049. case Builtin::BI__builtin_alloca_with_align:
  1050. if (SemaBuiltinAllocaWithAlign(TheCall))
  1051. return ExprError();
  1052. break;
  1053. case Builtin::BI__assume:
  1054. case Builtin::BI__builtin_assume:
  1055. if (SemaBuiltinAssume(TheCall))
  1056. return ExprError();
  1057. break;
  1058. case Builtin::BI__builtin_assume_aligned:
  1059. if (SemaBuiltinAssumeAligned(TheCall))
  1060. return ExprError();
  1061. break;
  1062. case Builtin::BI__builtin_dynamic_object_size:
  1063. case Builtin::BI__builtin_object_size:
  1064. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  1065. return ExprError();
  1066. break;
  1067. case Builtin::BI__builtin_longjmp:
  1068. if (SemaBuiltinLongjmp(TheCall))
  1069. return ExprError();
  1070. break;
  1071. case Builtin::BI__builtin_setjmp:
  1072. if (SemaBuiltinSetjmp(TheCall))
  1073. return ExprError();
  1074. break;
  1075. case Builtin::BI_setjmp:
  1076. case Builtin::BI_setjmpex:
  1077. if (checkArgCount(*this, TheCall, 1))
  1078. return true;
  1079. break;
  1080. case Builtin::BI__builtin_classify_type:
  1081. if (checkArgCount(*this, TheCall, 1)) return true;
  1082. TheCall->setType(Context.IntTy);
  1083. break;
  1084. case Builtin::BI__builtin_constant_p: {
  1085. if (checkArgCount(*this, TheCall, 1)) return true;
  1086. ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
  1087. if (Arg.isInvalid()) return true;
  1088. TheCall->setArg(0, Arg.get());
  1089. TheCall->setType(Context.IntTy);
  1090. break;
  1091. }
  1092. case Builtin::BI__builtin_launder:
  1093. return SemaBuiltinLaunder(*this, TheCall);
  1094. case Builtin::BI__sync_fetch_and_add:
  1095. case Builtin::BI__sync_fetch_and_add_1:
  1096. case Builtin::BI__sync_fetch_and_add_2:
  1097. case Builtin::BI__sync_fetch_and_add_4:
  1098. case Builtin::BI__sync_fetch_and_add_8:
  1099. case Builtin::BI__sync_fetch_and_add_16:
  1100. case Builtin::BI__sync_fetch_and_sub:
  1101. case Builtin::BI__sync_fetch_and_sub_1:
  1102. case Builtin::BI__sync_fetch_and_sub_2:
  1103. case Builtin::BI__sync_fetch_and_sub_4:
  1104. case Builtin::BI__sync_fetch_and_sub_8:
  1105. case Builtin::BI__sync_fetch_and_sub_16:
  1106. case Builtin::BI__sync_fetch_and_or:
  1107. case Builtin::BI__sync_fetch_and_or_1:
  1108. case Builtin::BI__sync_fetch_and_or_2:
  1109. case Builtin::BI__sync_fetch_and_or_4:
  1110. case Builtin::BI__sync_fetch_and_or_8:
  1111. case Builtin::BI__sync_fetch_and_or_16:
  1112. case Builtin::BI__sync_fetch_and_and:
  1113. case Builtin::BI__sync_fetch_and_and_1:
  1114. case Builtin::BI__sync_fetch_and_and_2:
  1115. case Builtin::BI__sync_fetch_and_and_4:
  1116. case Builtin::BI__sync_fetch_and_and_8:
  1117. case Builtin::BI__sync_fetch_and_and_16:
  1118. case Builtin::BI__sync_fetch_and_xor:
  1119. case Builtin::BI__sync_fetch_and_xor_1:
  1120. case Builtin::BI__sync_fetch_and_xor_2:
  1121. case Builtin::BI__sync_fetch_and_xor_4:
  1122. case Builtin::BI__sync_fetch_and_xor_8:
  1123. case Builtin::BI__sync_fetch_and_xor_16:
  1124. case Builtin::BI__sync_fetch_and_nand:
  1125. case Builtin::BI__sync_fetch_and_nand_1:
  1126. case Builtin::BI__sync_fetch_and_nand_2:
  1127. case Builtin::BI__sync_fetch_and_nand_4:
  1128. case Builtin::BI__sync_fetch_and_nand_8:
  1129. case Builtin::BI__sync_fetch_and_nand_16:
  1130. case Builtin::BI__sync_add_and_fetch:
  1131. case Builtin::BI__sync_add_and_fetch_1:
  1132. case Builtin::BI__sync_add_and_fetch_2:
  1133. case Builtin::BI__sync_add_and_fetch_4:
  1134. case Builtin::BI__sync_add_and_fetch_8:
  1135. case Builtin::BI__sync_add_and_fetch_16:
  1136. case Builtin::BI__sync_sub_and_fetch:
  1137. case Builtin::BI__sync_sub_and_fetch_1:
  1138. case Builtin::BI__sync_sub_and_fetch_2:
  1139. case Builtin::BI__sync_sub_and_fetch_4:
  1140. case Builtin::BI__sync_sub_and_fetch_8:
  1141. case Builtin::BI__sync_sub_and_fetch_16:
  1142. case Builtin::BI__sync_and_and_fetch:
  1143. case Builtin::BI__sync_and_and_fetch_1:
  1144. case Builtin::BI__sync_and_and_fetch_2:
  1145. case Builtin::BI__sync_and_and_fetch_4:
  1146. case Builtin::BI__sync_and_and_fetch_8:
  1147. case Builtin::BI__sync_and_and_fetch_16:
  1148. case Builtin::BI__sync_or_and_fetch:
  1149. case Builtin::BI__sync_or_and_fetch_1:
  1150. case Builtin::BI__sync_or_and_fetch_2:
  1151. case Builtin::BI__sync_or_and_fetch_4:
  1152. case Builtin::BI__sync_or_and_fetch_8:
  1153. case Builtin::BI__sync_or_and_fetch_16:
  1154. case Builtin::BI__sync_xor_and_fetch:
  1155. case Builtin::BI__sync_xor_and_fetch_1:
  1156. case Builtin::BI__sync_xor_and_fetch_2:
  1157. case Builtin::BI__sync_xor_and_fetch_4:
  1158. case Builtin::BI__sync_xor_and_fetch_8:
  1159. case Builtin::BI__sync_xor_and_fetch_16:
  1160. case Builtin::BI__sync_nand_and_fetch:
  1161. case Builtin::BI__sync_nand_and_fetch_1:
  1162. case Builtin::BI__sync_nand_and_fetch_2:
  1163. case Builtin::BI__sync_nand_and_fetch_4:
  1164. case Builtin::BI__sync_nand_and_fetch_8:
  1165. case Builtin::BI__sync_nand_and_fetch_16:
  1166. case Builtin::BI__sync_val_compare_and_swap:
  1167. case Builtin::BI__sync_val_compare_and_swap_1:
  1168. case Builtin::BI__sync_val_compare_and_swap_2:
  1169. case Builtin::BI__sync_val_compare_and_swap_4:
  1170. case Builtin::BI__sync_val_compare_and_swap_8:
  1171. case Builtin::BI__sync_val_compare_and_swap_16:
  1172. case Builtin::BI__sync_bool_compare_and_swap:
  1173. case Builtin::BI__sync_bool_compare_and_swap_1:
  1174. case Builtin::BI__sync_bool_compare_and_swap_2:
  1175. case Builtin::BI__sync_bool_compare_and_swap_4:
  1176. case Builtin::BI__sync_bool_compare_and_swap_8:
  1177. case Builtin::BI__sync_bool_compare_and_swap_16:
  1178. case Builtin::BI__sync_lock_test_and_set:
  1179. case Builtin::BI__sync_lock_test_and_set_1:
  1180. case Builtin::BI__sync_lock_test_and_set_2:
  1181. case Builtin::BI__sync_lock_test_and_set_4:
  1182. case Builtin::BI__sync_lock_test_and_set_8:
  1183. case Builtin::BI__sync_lock_test_and_set_16:
  1184. case Builtin::BI__sync_lock_release:
  1185. case Builtin::BI__sync_lock_release_1:
  1186. case Builtin::BI__sync_lock_release_2:
  1187. case Builtin::BI__sync_lock_release_4:
  1188. case Builtin::BI__sync_lock_release_8:
  1189. case Builtin::BI__sync_lock_release_16:
  1190. case Builtin::BI__sync_swap:
  1191. case Builtin::BI__sync_swap_1:
  1192. case Builtin::BI__sync_swap_2:
  1193. case Builtin::BI__sync_swap_4:
  1194. case Builtin::BI__sync_swap_8:
  1195. case Builtin::BI__sync_swap_16:
  1196. return SemaBuiltinAtomicOverloaded(TheCallResult);
  1197. case Builtin::BI__sync_synchronize:
  1198. Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
  1199. << TheCall->getCallee()->getSourceRange();
  1200. break;
  1201. case Builtin::BI__builtin_nontemporal_load:
  1202. case Builtin::BI__builtin_nontemporal_store:
  1203. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  1204. #define BUILTIN(ID, TYPE, ATTRS)
  1205. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  1206. case Builtin::BI##ID: \
  1207. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  1208. #include "clang/Basic/Builtins.def"
  1209. case Builtin::BI__annotation:
  1210. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  1211. return ExprError();
  1212. break;
  1213. case Builtin::BI__builtin_annotation:
  1214. if (SemaBuiltinAnnotation(*this, TheCall))
  1215. return ExprError();
  1216. break;
  1217. case Builtin::BI__builtin_addressof:
  1218. if (SemaBuiltinAddressof(*this, TheCall))
  1219. return ExprError();
  1220. break;
  1221. case Builtin::BI__builtin_add_overflow:
  1222. case Builtin::BI__builtin_sub_overflow:
  1223. case Builtin::BI__builtin_mul_overflow:
  1224. if (SemaBuiltinOverflow(*this, TheCall))
  1225. return ExprError();
  1226. break;
  1227. case Builtin::BI__builtin_operator_new:
  1228. case Builtin::BI__builtin_operator_delete: {
  1229. bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
  1230. ExprResult Res =
  1231. SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
  1232. if (Res.isInvalid())
  1233. CorrectDelayedTyposInExpr(TheCallResult.get());
  1234. return Res;
  1235. }
  1236. case Builtin::BI__builtin_dump_struct: {
  1237. // We first want to ensure we are called with 2 arguments
  1238. if (checkArgCount(*this, TheCall, 2))
  1239. return ExprError();
  1240. // Ensure that the first argument is of type 'struct XX *'
  1241. const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
  1242. const QualType PtrArgType = PtrArg->getType();
  1243. if (!PtrArgType->isPointerType() ||
  1244. !PtrArgType->getPointeeType()->isRecordType()) {
  1245. Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1246. << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
  1247. << "structure pointer";
  1248. return ExprError();
  1249. }
  1250. // Ensure that the second argument is of type 'FunctionType'
  1251. const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
  1252. const QualType FnPtrArgType = FnPtrArg->getType();
  1253. if (!FnPtrArgType->isPointerType()) {
  1254. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1255. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1256. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1257. return ExprError();
  1258. }
  1259. const auto *FuncType =
  1260. FnPtrArgType->getPointeeType()->getAs<FunctionType>();
  1261. if (!FuncType) {
  1262. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1263. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1264. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1265. return ExprError();
  1266. }
  1267. if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
  1268. if (!FT->getNumParams()) {
  1269. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1270. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1271. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1272. return ExprError();
  1273. }
  1274. QualType PT = FT->getParamType(0);
  1275. if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
  1276. !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
  1277. !PT->getPointeeType().isConstQualified()) {
  1278. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1279. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1280. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1281. return ExprError();
  1282. }
  1283. }
  1284. TheCall->setType(Context.IntTy);
  1285. break;
  1286. }
  1287. case Builtin::BI__builtin_call_with_static_chain:
  1288. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  1289. return ExprError();
  1290. break;
  1291. case Builtin::BI__exception_code:
  1292. case Builtin::BI_exception_code:
  1293. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  1294. diag::err_seh___except_block))
  1295. return ExprError();
  1296. break;
  1297. case Builtin::BI__exception_info:
  1298. case Builtin::BI_exception_info:
  1299. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  1300. diag::err_seh___except_filter))
  1301. return ExprError();
  1302. break;
  1303. case Builtin::BI__GetExceptionInfo:
  1304. if (checkArgCount(*this, TheCall, 1))
  1305. return ExprError();
  1306. if (CheckCXXThrowOperand(
  1307. TheCall->getBeginLoc(),
  1308. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1309. TheCall))
  1310. return ExprError();
  1311. TheCall->setType(Context.VoidPtrTy);
  1312. break;
  1313. // OpenCL v2.0, s6.13.16 - Pipe functions
  1314. case Builtin::BIread_pipe:
  1315. case Builtin::BIwrite_pipe:
  1316. // Since those two functions are declared with var args, we need a semantic
  1317. // check for the argument.
  1318. if (SemaBuiltinRWPipe(*this, TheCall))
  1319. return ExprError();
  1320. break;
  1321. case Builtin::BIreserve_read_pipe:
  1322. case Builtin::BIreserve_write_pipe:
  1323. case Builtin::BIwork_group_reserve_read_pipe:
  1324. case Builtin::BIwork_group_reserve_write_pipe:
  1325. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1326. return ExprError();
  1327. break;
  1328. case Builtin::BIsub_group_reserve_read_pipe:
  1329. case Builtin::BIsub_group_reserve_write_pipe:
  1330. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1331. SemaBuiltinReserveRWPipe(*this, TheCall))
  1332. return ExprError();
  1333. break;
  1334. case Builtin::BIcommit_read_pipe:
  1335. case Builtin::BIcommit_write_pipe:
  1336. case Builtin::BIwork_group_commit_read_pipe:
  1337. case Builtin::BIwork_group_commit_write_pipe:
  1338. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1339. return ExprError();
  1340. break;
  1341. case Builtin::BIsub_group_commit_read_pipe:
  1342. case Builtin::BIsub_group_commit_write_pipe:
  1343. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1344. SemaBuiltinCommitRWPipe(*this, TheCall))
  1345. return ExprError();
  1346. break;
  1347. case Builtin::BIget_pipe_num_packets:
  1348. case Builtin::BIget_pipe_max_packets:
  1349. if (SemaBuiltinPipePackets(*this, TheCall))
  1350. return ExprError();
  1351. break;
  1352. case Builtin::BIto_global:
  1353. case Builtin::BIto_local:
  1354. case Builtin::BIto_private:
  1355. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1356. return ExprError();
  1357. break;
  1358. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1359. case Builtin::BIenqueue_kernel:
  1360. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1361. return ExprError();
  1362. break;
  1363. case Builtin::BIget_kernel_work_group_size:
  1364. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1365. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1366. return ExprError();
  1367. break;
  1368. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1369. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1370. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1371. return ExprError();
  1372. break;
  1373. case Builtin::BI__builtin_os_log_format:
  1374. case Builtin::BI__builtin_os_log_format_buffer_size:
  1375. if (SemaBuiltinOSLogFormat(TheCall))
  1376. return ExprError();
  1377. break;
  1378. }
  1379. // Since the target specific builtins for each arch overlap, only check those
  1380. // of the arch we are compiling for.
  1381. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  1382. switch (Context.getTargetInfo().getTriple().getArch()) {
  1383. case llvm::Triple::arm:
  1384. case llvm::Triple::armeb:
  1385. case llvm::Triple::thumb:
  1386. case llvm::Triple::thumbeb:
  1387. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  1388. return ExprError();
  1389. break;
  1390. case llvm::Triple::aarch64:
  1391. case llvm::Triple::aarch64_be:
  1392. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  1393. return ExprError();
  1394. break;
  1395. case llvm::Triple::hexagon:
  1396. if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
  1397. return ExprError();
  1398. break;
  1399. case llvm::Triple::mips:
  1400. case llvm::Triple::mipsel:
  1401. case llvm::Triple::mips64:
  1402. case llvm::Triple::mips64el:
  1403. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  1404. return ExprError();
  1405. break;
  1406. case llvm::Triple::systemz:
  1407. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  1408. return ExprError();
  1409. break;
  1410. case llvm::Triple::x86:
  1411. case llvm::Triple::x86_64:
  1412. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  1413. return ExprError();
  1414. break;
  1415. case llvm::Triple::ppc:
  1416. case llvm::Triple::ppc64:
  1417. case llvm::Triple::ppc64le:
  1418. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  1419. return ExprError();
  1420. break;
  1421. default:
  1422. break;
  1423. }
  1424. }
  1425. return TheCallResult;
  1426. }
  1427. // Get the valid immediate range for the specified NEON type code.
  1428. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  1429. NeonTypeFlags Type(t);
  1430. int IsQuad = ForceQuad ? true : Type.isQuad();
  1431. switch (Type.getEltType()) {
  1432. case NeonTypeFlags::Int8:
  1433. case NeonTypeFlags::Poly8:
  1434. return shift ? 7 : (8 << IsQuad) - 1;
  1435. case NeonTypeFlags::Int16:
  1436. case NeonTypeFlags::Poly16:
  1437. return shift ? 15 : (4 << IsQuad) - 1;
  1438. case NeonTypeFlags::Int32:
  1439. return shift ? 31 : (2 << IsQuad) - 1;
  1440. case NeonTypeFlags::Int64:
  1441. case NeonTypeFlags::Poly64:
  1442. return shift ? 63 : (1 << IsQuad) - 1;
  1443. case NeonTypeFlags::Poly128:
  1444. return shift ? 127 : (1 << IsQuad) - 1;
  1445. case NeonTypeFlags::Float16:
  1446. assert(!shift && "cannot shift float types!");
  1447. return (4 << IsQuad) - 1;
  1448. case NeonTypeFlags::Float32:
  1449. assert(!shift && "cannot shift float types!");
  1450. return (2 << IsQuad) - 1;
  1451. case NeonTypeFlags::Float64:
  1452. assert(!shift && "cannot shift float types!");
  1453. return (1 << IsQuad) - 1;
  1454. }
  1455. llvm_unreachable("Invalid NeonTypeFlag!");
  1456. }
  1457. /// getNeonEltType - Return the QualType corresponding to the elements of
  1458. /// the vector type specified by the NeonTypeFlags. This is used to check
  1459. /// the pointer arguments for Neon load/store intrinsics.
  1460. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  1461. bool IsPolyUnsigned, bool IsInt64Long) {
  1462. switch (Flags.getEltType()) {
  1463. case NeonTypeFlags::Int8:
  1464. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  1465. case NeonTypeFlags::Int16:
  1466. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  1467. case NeonTypeFlags::Int32:
  1468. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  1469. case NeonTypeFlags::Int64:
  1470. if (IsInt64Long)
  1471. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  1472. else
  1473. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  1474. : Context.LongLongTy;
  1475. case NeonTypeFlags::Poly8:
  1476. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  1477. case NeonTypeFlags::Poly16:
  1478. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  1479. case NeonTypeFlags::Poly64:
  1480. if (IsInt64Long)
  1481. return Context.UnsignedLongTy;
  1482. else
  1483. return Context.UnsignedLongLongTy;
  1484. case NeonTypeFlags::Poly128:
  1485. break;
  1486. case NeonTypeFlags::Float16:
  1487. return Context.HalfTy;
  1488. case NeonTypeFlags::Float32:
  1489. return Context.FloatTy;
  1490. case NeonTypeFlags::Float64:
  1491. return Context.DoubleTy;
  1492. }
  1493. llvm_unreachable("Invalid NeonTypeFlag!");
  1494. }
  1495. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1496. llvm::APSInt Result;
  1497. uint64_t mask = 0;
  1498. unsigned TV = 0;
  1499. int PtrArgNum = -1;
  1500. bool HasConstPtr = false;
  1501. switch (BuiltinID) {
  1502. #define GET_NEON_OVERLOAD_CHECK
  1503. #include "clang/Basic/arm_neon.inc"
  1504. #include "clang/Basic/arm_fp16.inc"
  1505. #undef GET_NEON_OVERLOAD_CHECK
  1506. }
  1507. // For NEON intrinsics which are overloaded on vector element type, validate
  1508. // the immediate which specifies which variant to emit.
  1509. unsigned ImmArg = TheCall->getNumArgs()-1;
  1510. if (mask) {
  1511. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  1512. return true;
  1513. TV = Result.getLimitedValue(64);
  1514. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  1515. return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
  1516. << TheCall->getArg(ImmArg)->getSourceRange();
  1517. }
  1518. if (PtrArgNum >= 0) {
  1519. // Check that pointer arguments have the specified type.
  1520. Expr *Arg = TheCall->getArg(PtrArgNum);
  1521. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  1522. Arg = ICE->getSubExpr();
  1523. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  1524. QualType RHSTy = RHS.get()->getType();
  1525. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  1526. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  1527. Arch == llvm::Triple::aarch64_be;
  1528. bool IsInt64Long =
  1529. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  1530. QualType EltTy =
  1531. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  1532. if (HasConstPtr)
  1533. EltTy = EltTy.withConst();
  1534. QualType LHSTy = Context.getPointerType(EltTy);
  1535. AssignConvertType ConvTy;
  1536. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  1537. if (RHS.isInvalid())
  1538. return true;
  1539. if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
  1540. RHS.get(), AA_Assigning))
  1541. return true;
  1542. }
  1543. // For NEON intrinsics which take an immediate value as part of the
  1544. // instruction, range check them here.
  1545. unsigned i = 0, l = 0, u = 0;
  1546. switch (BuiltinID) {
  1547. default:
  1548. return false;
  1549. #define GET_NEON_IMMEDIATE_CHECK
  1550. #include "clang/Basic/arm_neon.inc"
  1551. #include "clang/Basic/arm_fp16.inc"
  1552. #undef GET_NEON_IMMEDIATE_CHECK
  1553. }
  1554. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1555. }
  1556. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  1557. unsigned MaxWidth) {
  1558. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1559. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1560. BuiltinID == ARM::BI__builtin_arm_strex ||
  1561. BuiltinID == ARM::BI__builtin_arm_stlex ||
  1562. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1563. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1564. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1565. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  1566. "unexpected ARM builtin");
  1567. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1568. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1569. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1570. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  1571. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1572. // Ensure that we have the proper number of arguments.
  1573. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  1574. return true;
  1575. // Inspect the pointer argument of the atomic builtin. This should always be
  1576. // a pointer type, whose element is an integral scalar or pointer type.
  1577. // Because it is a pointer type, we don't have to worry about any implicit
  1578. // casts here.
  1579. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  1580. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  1581. if (PointerArgRes.isInvalid())
  1582. return true;
  1583. PointerArg = PointerArgRes.get();
  1584. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  1585. if (!pointerType) {
  1586. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  1587. << PointerArg->getType() << PointerArg->getSourceRange();
  1588. return true;
  1589. }
  1590. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  1591. // task is to insert the appropriate casts into the AST. First work out just
  1592. // what the appropriate type is.
  1593. QualType ValType = pointerType->getPointeeType();
  1594. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  1595. if (IsLdrex)
  1596. AddrType.addConst();
  1597. // Issue a warning if the cast is dodgy.
  1598. CastKind CastNeeded = CK_NoOp;
  1599. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  1600. CastNeeded = CK_BitCast;
  1601. Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
  1602. << PointerArg->getType() << Context.getPointerType(AddrType)
  1603. << AA_Passing << PointerArg->getSourceRange();
  1604. }
  1605. // Finally, do the cast and replace the argument with the corrected version.
  1606. AddrType = Context.getPointerType(AddrType);
  1607. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  1608. if (PointerArgRes.isInvalid())
  1609. return true;
  1610. PointerArg = PointerArgRes.get();
  1611. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  1612. // In general, we allow ints, floats and pointers to be loaded and stored.
  1613. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1614. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  1615. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  1616. << PointerArg->getType() << PointerArg->getSourceRange();
  1617. return true;
  1618. }
  1619. // But ARM doesn't have instructions to deal with 128-bit versions.
  1620. if (Context.getTypeSize(ValType) > MaxWidth) {
  1621. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  1622. Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
  1623. << PointerArg->getType() << PointerArg->getSourceRange();
  1624. return true;
  1625. }
  1626. switch (ValType.getObjCLifetime()) {
  1627. case Qualifiers::OCL_None:
  1628. case Qualifiers::OCL_ExplicitNone:
  1629. // okay
  1630. break;
  1631. case Qualifiers::OCL_Weak:
  1632. case Qualifiers::OCL_Strong:
  1633. case Qualifiers::OCL_Autoreleasing:
  1634. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  1635. << ValType << PointerArg->getSourceRange();
  1636. return true;
  1637. }
  1638. if (IsLdrex) {
  1639. TheCall->setType(ValType);
  1640. return false;
  1641. }
  1642. // Initialize the argument to be stored.
  1643. ExprResult ValArg = TheCall->getArg(0);
  1644. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  1645. Context, ValType, /*consume*/ false);
  1646. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  1647. if (ValArg.isInvalid())
  1648. return true;
  1649. TheCall->setArg(0, ValArg.get());
  1650. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  1651. // but the custom checker bypasses all default analysis.
  1652. TheCall->setType(Context.IntTy);
  1653. return false;
  1654. }
  1655. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1656. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1657. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1658. BuiltinID == ARM::BI__builtin_arm_strex ||
  1659. BuiltinID == ARM::BI__builtin_arm_stlex) {
  1660. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  1661. }
  1662. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  1663. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1664. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  1665. }
  1666. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  1667. BuiltinID == ARM::BI__builtin_arm_wsr64)
  1668. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  1669. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  1670. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  1671. BuiltinID == ARM::BI__builtin_arm_wsr ||
  1672. BuiltinID == ARM::BI__builtin_arm_wsrp)
  1673. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1674. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1675. return true;
  1676. // For intrinsics which take an immediate value as part of the instruction,
  1677. // range check them here.
  1678. // FIXME: VFP Intrinsics should error if VFP not present.
  1679. switch (BuiltinID) {
  1680. default: return false;
  1681. case ARM::BI__builtin_arm_ssat:
  1682. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  1683. case ARM::BI__builtin_arm_usat:
  1684. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  1685. case ARM::BI__builtin_arm_ssat16:
  1686. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  1687. case ARM::BI__builtin_arm_usat16:
  1688. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  1689. case ARM::BI__builtin_arm_vcvtr_f:
  1690. case ARM::BI__builtin_arm_vcvtr_d:
  1691. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  1692. case ARM::BI__builtin_arm_dmb:
  1693. case ARM::BI__builtin_arm_dsb:
  1694. case ARM::BI__builtin_arm_isb:
  1695. case ARM::BI__builtin_arm_dbg:
  1696. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  1697. }
  1698. }
  1699. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  1700. CallExpr *TheCall) {
  1701. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1702. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1703. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1704. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  1705. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  1706. }
  1707. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  1708. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1709. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  1710. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  1711. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  1712. }
  1713. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  1714. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  1715. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1716. // Memory Tagging Extensions (MTE) Intrinsics
  1717. if (BuiltinID == AArch64::BI__builtin_arm_irg ||
  1718. BuiltinID == AArch64::BI__builtin_arm_addg ||
  1719. BuiltinID == AArch64::BI__builtin_arm_gmi ||
  1720. BuiltinID == AArch64::BI__builtin_arm_ldg ||
  1721. BuiltinID == AArch64::BI__builtin_arm_stg ||
  1722. BuiltinID == AArch64::BI__builtin_arm_subp) {
  1723. return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
  1724. }
  1725. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  1726. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  1727. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  1728. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  1729. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1730. // Only check the valid encoding range. Any constant in this range would be
  1731. // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
  1732. // an exception for incorrect registers. This matches MSVC behavior.
  1733. if (BuiltinID == AArch64::BI_ReadStatusReg ||
  1734. BuiltinID == AArch64::BI_WriteStatusReg)
  1735. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
  1736. if (BuiltinID == AArch64::BI__getReg)
  1737. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
  1738. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1739. return true;
  1740. // For intrinsics which take an immediate value as part of the instruction,
  1741. // range check them here.
  1742. unsigned i = 0, l = 0, u = 0;
  1743. switch (BuiltinID) {
  1744. default: return false;
  1745. case AArch64::BI__builtin_arm_dmb:
  1746. case AArch64::BI__builtin_arm_dsb:
  1747. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  1748. }
  1749. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1750. }
  1751. bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
  1752. struct BuiltinAndString {
  1753. unsigned BuiltinID;
  1754. const char *Str;
  1755. };
  1756. static BuiltinAndString ValidCPU[] = {
  1757. { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
  1758. { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
  1759. { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
  1760. { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
  1761. { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
  1762. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
  1763. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
  1764. { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
  1765. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
  1766. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
  1767. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
  1768. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
  1769. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
  1770. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
  1771. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
  1772. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
  1773. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
  1774. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
  1775. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
  1776. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
  1777. { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
  1778. { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
  1779. { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
  1780. };
  1781. static BuiltinAndString ValidHVX[] = {
  1782. { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
  1783. { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
  1784. { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
  1785. { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
  1786. { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
  1787. { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
  1788. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
  1789. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
  1790. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
  1791. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
  1792. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
  1793. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
  1794. { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
  1795. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
  1796. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
  1797. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
  1798. { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
  1799. { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
  1800. { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
  1801. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
  1802. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
  1803. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
  1804. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
  1805. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
  1806. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
  1807. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
  1808. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
  1809. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
  1810. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
  1811. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
  1812. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
  1813. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
  1814. { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
  1815. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
  1816. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
  1817. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
  1818. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
  1819. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
  1820. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
  1821. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
  1822. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
  1823. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
  1824. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
  1825. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
  1826. { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
  1827. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
  1828. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
  1829. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
  1830. { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
  1831. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
  1832. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
  1833. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
  1834. { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
  1835. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
  1836. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
  1837. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
  1838. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
  1839. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
  1840. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
  1841. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
  1842. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
  1843. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
  1844. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
  1845. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
  1846. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
  1847. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
  1848. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
  1849. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
  1850. { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
  1851. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
  1852. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
  1853. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
  1854. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
  1855. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
  1856. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
  1857. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
  1858. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
  1859. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
  1860. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
  1861. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
  1862. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
  1863. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
  1864. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
  1865. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
  1866. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
  1867. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
  1868. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
  1869. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
  1870. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
  1871. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
  1872. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
  1873. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
  1874. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
  1875. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
  1876. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
  1877. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
  1878. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
  1879. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
  1880. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
  1881. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
  1882. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
  1883. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
  1884. { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
  1885. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
  1886. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
  1887. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
  1888. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
  1889. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
  1890. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
  1891. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
  1892. { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
  1893. { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
  1894. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
  1895. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
  1896. { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
  1897. { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
  1898. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
  1899. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
  1900. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
  1901. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
  1902. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
  1903. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
  1904. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
  1905. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
  1906. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
  1907. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
  1908. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
  1909. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
  1910. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
  1911. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
  1912. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
  1913. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
  1914. { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
  1915. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
  1916. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
  1917. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
  1918. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
  1919. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
  1920. { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
  1921. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
  1922. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
  1923. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
  1924. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
  1925. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
  1926. { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
  1927. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
  1928. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
  1929. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
  1930. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
  1931. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
  1932. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
  1933. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
  1934. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
  1935. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
  1936. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
  1937. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
  1938. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
  1939. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
  1940. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
  1941. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
  1942. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
  1943. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
  1944. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
  1945. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
  1946. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
  1947. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
  1948. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
  1949. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
  1950. { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
  1951. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
  1952. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
  1953. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
  1954. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
  1955. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
  1956. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
  1957. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
  1958. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
  1959. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
  1960. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
  1961. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
  1962. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
  1963. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
  1964. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
  1965. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
  1966. { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
  1967. { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
  1968. { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
  1969. { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
  1970. { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
  1971. { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
  1972. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
  1973. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
  1974. { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
  1975. { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
  1976. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
  1977. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
  1978. { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
  1979. { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
  1980. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
  1981. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
  1982. { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
  1983. { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
  1984. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
  1985. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
  1986. { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
  1987. { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
  1988. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
  1989. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
  1990. { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
  1991. { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
  1992. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
  1993. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
  1994. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
  1995. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
  1996. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
  1997. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
  1998. { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
  1999. { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
  2000. { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
  2001. { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
  2002. { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
  2003. { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
  2004. { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
  2005. { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
  2006. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
  2007. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
  2008. { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
  2009. { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
  2010. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
  2011. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
  2012. { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
  2013. { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
  2014. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
  2015. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
  2016. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
  2017. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
  2018. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
  2019. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
  2020. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
  2021. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
  2022. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
  2023. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
  2024. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
  2025. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
  2026. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
  2027. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
  2028. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
  2029. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
  2030. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
  2031. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
  2032. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
  2033. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
  2034. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
  2035. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
  2036. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
  2037. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
  2038. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
  2039. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
  2040. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
  2041. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
  2042. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
  2043. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
  2044. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
  2045. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
  2046. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
  2047. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
  2048. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
  2049. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
  2050. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
  2051. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
  2052. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
  2053. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
  2054. { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
  2055. { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
  2056. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
  2057. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
  2058. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
  2059. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
  2060. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
  2061. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
  2062. { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
  2063. { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
  2064. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
  2065. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
  2066. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
  2067. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
  2068. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
  2069. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
  2070. { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
  2071. { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
  2072. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
  2073. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
  2074. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
  2075. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
  2076. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
  2077. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
  2078. { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
  2079. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
  2080. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
  2081. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
  2082. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
  2083. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
  2084. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
  2085. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
  2086. { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
  2087. { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
  2088. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
  2089. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
  2090. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
  2091. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
  2092. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
  2093. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
  2094. { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
  2095. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
  2096. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
  2097. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
  2098. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
  2099. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
  2100. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
  2101. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
  2102. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
  2103. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
  2104. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
  2105. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
  2106. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
  2107. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
  2108. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
  2109. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
  2110. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
  2111. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
  2112. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
  2113. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
  2114. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
  2115. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
  2116. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
  2117. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
  2118. { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
  2119. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
  2120. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
  2121. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
  2122. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
  2123. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
  2124. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
  2125. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
  2126. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
  2127. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
  2128. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
  2129. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
  2130. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
  2131. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
  2132. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
  2133. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
  2134. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
  2135. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
  2136. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
  2137. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
  2138. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
  2139. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
  2140. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
  2141. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
  2142. { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
  2143. { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
  2144. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
  2145. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
  2146. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
  2147. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
  2148. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
  2149. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
  2150. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
  2151. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
  2152. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
  2153. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
  2154. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
  2155. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
  2156. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
  2157. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
  2158. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
  2159. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
  2160. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
  2161. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
  2162. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
  2163. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
  2164. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
  2165. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
  2166. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
  2167. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
  2168. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
  2169. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
  2170. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
  2171. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
  2172. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
  2173. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
  2174. { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
  2175. { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
  2176. { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
  2177. { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
  2178. { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
  2179. { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
  2180. { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
  2181. { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
  2182. { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
  2183. { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
  2184. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
  2185. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
  2186. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
  2187. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
  2188. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
  2189. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
  2190. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
  2191. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
  2192. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
  2193. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
  2194. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
  2195. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
  2196. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
  2197. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
  2198. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
  2199. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
  2200. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
  2201. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
  2202. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
  2203. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
  2204. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
  2205. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
  2206. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
  2207. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
  2208. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
  2209. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
  2210. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
  2211. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
  2212. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
  2213. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
  2214. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
  2215. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
  2216. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
  2217. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
  2218. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
  2219. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
  2220. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
  2221. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
  2222. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
  2223. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
  2224. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
  2225. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
  2226. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
  2227. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
  2228. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
  2229. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
  2230. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
  2231. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
  2232. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
  2233. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
  2234. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
  2235. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
  2236. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
  2237. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
  2238. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
  2239. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
  2240. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
  2241. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
  2242. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
  2243. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
  2244. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
  2245. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
  2246. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
  2247. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
  2248. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
  2249. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
  2250. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
  2251. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
  2252. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
  2253. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
  2254. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
  2255. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
  2256. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
  2257. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
  2258. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
  2259. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
  2260. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
  2261. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
  2262. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
  2263. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
  2264. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
  2265. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
  2266. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
  2267. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
  2268. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
  2269. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
  2270. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
  2271. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
  2272. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
  2273. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
  2274. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
  2275. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
  2276. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
  2277. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
  2278. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
  2279. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
  2280. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
  2281. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
  2282. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
  2283. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
  2284. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
  2285. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
  2286. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
  2287. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
  2288. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
  2289. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
  2290. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
  2291. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
  2292. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
  2293. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
  2294. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
  2295. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
  2296. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
  2297. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
  2298. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
  2299. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
  2300. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
  2301. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
  2302. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
  2303. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
  2304. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
  2305. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
  2306. { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
  2307. { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
  2308. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
  2309. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
  2310. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
  2311. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
  2312. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
  2313. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
  2314. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
  2315. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
  2316. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
  2317. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
  2318. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
  2319. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
  2320. { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
  2321. { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
  2322. { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
  2323. { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
  2324. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
  2325. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
  2326. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
  2327. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
  2328. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
  2329. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
  2330. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
  2331. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
  2332. { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
  2333. { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
  2334. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
  2335. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
  2336. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
  2337. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
  2338. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
  2339. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
  2340. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
  2341. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
  2342. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
  2343. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
  2344. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
  2345. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
  2346. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
  2347. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
  2348. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
  2349. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
  2350. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
  2351. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
  2352. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
  2353. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
  2354. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
  2355. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
  2356. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
  2357. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
  2358. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
  2359. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
  2360. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
  2361. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
  2362. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
  2363. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
  2364. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
  2365. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
  2366. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
  2367. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
  2368. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
  2369. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
  2370. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
  2371. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
  2372. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
  2373. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
  2374. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
  2375. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
  2376. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
  2377. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
  2378. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
  2379. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
  2380. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
  2381. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
  2382. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
  2383. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
  2384. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
  2385. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
  2386. { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
  2387. { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
  2388. { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
  2389. { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
  2390. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
  2391. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
  2392. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
  2393. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
  2394. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
  2395. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
  2396. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
  2397. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
  2398. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
  2399. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
  2400. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
  2401. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
  2402. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
  2403. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
  2404. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
  2405. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
  2406. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
  2407. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
  2408. { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
  2409. { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
  2410. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
  2411. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
  2412. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
  2413. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
  2414. { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
  2415. { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
  2416. { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
  2417. { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
  2418. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
  2419. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
  2420. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
  2421. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
  2422. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
  2423. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
  2424. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
  2425. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
  2426. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
  2427. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
  2428. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
  2429. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
  2430. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
  2431. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
  2432. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
  2433. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
  2434. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
  2435. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
  2436. { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
  2437. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
  2438. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
  2439. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
  2440. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
  2441. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
  2442. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
  2443. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
  2444. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
  2445. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
  2446. { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
  2447. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
  2448. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
  2449. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
  2450. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
  2451. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
  2452. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
  2453. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
  2454. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
  2455. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
  2456. { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
  2457. { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
  2458. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
  2459. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
  2460. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
  2461. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
  2462. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
  2463. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
  2464. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
  2465. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
  2466. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
  2467. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
  2468. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
  2469. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
  2470. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
  2471. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
  2472. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
  2473. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
  2474. { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
  2475. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
  2476. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
  2477. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
  2478. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
  2479. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
  2480. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
  2481. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
  2482. { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
  2483. { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
  2484. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
  2485. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
  2486. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
  2487. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
  2488. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
  2489. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
  2490. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
  2491. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
  2492. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
  2493. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
  2494. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
  2495. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
  2496. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
  2497. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
  2498. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
  2499. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
  2500. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
  2501. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
  2502. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
  2503. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
  2504. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
  2505. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
  2506. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
  2507. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
  2508. { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
  2509. { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
  2510. { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
  2511. { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
  2512. { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
  2513. { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
  2514. };
  2515. // Sort the tables on first execution so we can binary search them.
  2516. auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
  2517. return LHS.BuiltinID < RHS.BuiltinID;
  2518. };
  2519. static const bool SortOnce =
  2520. (llvm::sort(ValidCPU, SortCmp),
  2521. llvm::sort(ValidHVX, SortCmp), true);
  2522. (void)SortOnce;
  2523. auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
  2524. return BI.BuiltinID < BuiltinID;
  2525. };
  2526. const TargetInfo &TI = Context.getTargetInfo();
  2527. const BuiltinAndString *FC =
  2528. std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
  2529. LowerBoundCmp);
  2530. if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
  2531. const TargetOptions &Opts = TI.getTargetOpts();
  2532. StringRef CPU = Opts.CPU;
  2533. if (!CPU.empty()) {
  2534. assert(CPU.startswith("hexagon") && "Unexpected CPU name");
  2535. CPU.consume_front("hexagon");
  2536. SmallVector<StringRef, 3> CPUs;
  2537. StringRef(FC->Str).split(CPUs, ',');
  2538. if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
  2539. return Diag(TheCall->getBeginLoc(),
  2540. diag::err_hexagon_builtin_unsupported_cpu);
  2541. }
  2542. }
  2543. const BuiltinAndString *FH =
  2544. std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
  2545. LowerBoundCmp);
  2546. if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
  2547. if (!TI.hasFeature("hvx"))
  2548. return Diag(TheCall->getBeginLoc(),
  2549. diag::err_hexagon_builtin_requires_hvx);
  2550. SmallVector<StringRef, 3> HVXs;
  2551. StringRef(FH->Str).split(HVXs, ',');
  2552. bool IsValid = llvm::any_of(HVXs,
  2553. [&TI] (StringRef V) {
  2554. std::string F = "hvx" + V.str();
  2555. return TI.hasFeature(F);
  2556. });
  2557. if (!IsValid)
  2558. return Diag(TheCall->getBeginLoc(),
  2559. diag::err_hexagon_builtin_unsupported_hvx);
  2560. }
  2561. return false;
  2562. }
  2563. bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
  2564. struct ArgInfo {
  2565. uint8_t OpNum;
  2566. bool IsSigned;
  2567. uint8_t BitWidth;
  2568. uint8_t Align;
  2569. };
  2570. struct BuiltinInfo {
  2571. unsigned BuiltinID;
  2572. ArgInfo Infos[2];
  2573. };
  2574. static BuiltinInfo Infos[] = {
  2575. { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
  2576. { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
  2577. { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
  2578. { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
  2579. { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
  2580. { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
  2581. { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
  2582. { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
  2583. { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
  2584. { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
  2585. { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
  2586. { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
  2587. { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
  2588. { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
  2589. { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
  2590. { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
  2591. { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
  2592. { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
  2593. { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
  2594. { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
  2595. { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
  2596. { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
  2597. { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
  2598. { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
  2599. { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
  2600. { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
  2601. { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
  2602. { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
  2603. { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
  2604. { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
  2605. { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
  2606. { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
  2607. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
  2608. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
  2609. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
  2610. { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
  2611. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
  2612. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
  2613. { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
  2614. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
  2615. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
  2616. { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
  2617. { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
  2618. { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
  2619. { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
  2620. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
  2621. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
  2622. { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
  2623. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
  2624. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
  2625. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
  2626. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
  2627. { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
  2628. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
  2629. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
  2630. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
  2631. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
  2632. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
  2633. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
  2634. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
  2635. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
  2636. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
  2637. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
  2638. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
  2639. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
  2640. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
  2641. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
  2642. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
  2643. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
  2644. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
  2645. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
  2646. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
  2647. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
  2648. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
  2649. {{ 1, false, 6, 0 }} },
  2650. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
  2651. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
  2652. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
  2653. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
  2654. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
  2655. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
  2656. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
  2657. {{ 1, false, 5, 0 }} },
  2658. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
  2659. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
  2660. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
  2661. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
  2662. { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
  2663. { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
  2664. { 2, false, 5, 0 }} },
  2665. { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
  2666. { 2, false, 6, 0 }} },
  2667. { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
  2668. { 3, false, 5, 0 }} },
  2669. { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
  2670. { 3, false, 6, 0 }} },
  2671. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
  2672. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
  2673. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
  2674. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
  2675. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
  2676. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
  2677. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
  2678. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
  2679. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
  2680. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
  2681. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
  2682. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
  2683. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
  2684. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
  2685. { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
  2686. { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
  2687. {{ 2, false, 4, 0 },
  2688. { 3, false, 5, 0 }} },
  2689. { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
  2690. {{ 2, false, 4, 0 },
  2691. { 3, false, 5, 0 }} },
  2692. { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
  2693. {{ 2, false, 4, 0 },
  2694. { 3, false, 5, 0 }} },
  2695. { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
  2696. {{ 2, false, 4, 0 },
  2697. { 3, false, 5, 0 }} },
  2698. { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
  2699. { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
  2700. { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
  2701. { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
  2702. { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
  2703. { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
  2704. { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
  2705. { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
  2706. { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
  2707. { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
  2708. { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
  2709. { 2, false, 5, 0 }} },
  2710. { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
  2711. { 2, false, 6, 0 }} },
  2712. { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
  2713. { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
  2714. { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
  2715. { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
  2716. { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
  2717. { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
  2718. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
  2719. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
  2720. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
  2721. {{ 1, false, 4, 0 }} },
  2722. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
  2723. { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
  2724. {{ 1, false, 4, 0 }} },
  2725. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
  2726. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
  2727. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
  2728. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
  2729. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
  2730. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
  2731. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
  2732. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
  2733. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
  2734. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
  2735. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
  2736. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
  2737. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
  2738. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
  2739. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
  2740. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
  2741. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
  2742. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
  2743. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
  2744. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
  2745. {{ 3, false, 1, 0 }} },
  2746. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
  2747. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
  2748. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
  2749. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
  2750. {{ 3, false, 1, 0 }} },
  2751. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
  2752. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
  2753. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
  2754. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
  2755. {{ 3, false, 1, 0 }} },
  2756. };
  2757. // Use a dynamically initialized static to sort the table exactly once on
  2758. // first run.
  2759. static const bool SortOnce =
  2760. (llvm::sort(Infos,
  2761. [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
  2762. return LHS.BuiltinID < RHS.BuiltinID;
  2763. }),
  2764. true);
  2765. (void)SortOnce;
  2766. const BuiltinInfo *F =
  2767. std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
  2768. [](const BuiltinInfo &BI, unsigned BuiltinID) {
  2769. return BI.BuiltinID < BuiltinID;
  2770. });
  2771. if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
  2772. return false;
  2773. bool Error = false;
  2774. for (const ArgInfo &A : F->Infos) {
  2775. // Ignore empty ArgInfo elements.
  2776. if (A.BitWidth == 0)
  2777. continue;
  2778. int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
  2779. int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
  2780. if (!A.Align) {
  2781. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
  2782. } else {
  2783. unsigned M = 1 << A.Align;
  2784. Min *= M;
  2785. Max *= M;
  2786. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
  2787. SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
  2788. }
  2789. }
  2790. return Error;
  2791. }
  2792. bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
  2793. CallExpr *TheCall) {
  2794. return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
  2795. CheckHexagonBuiltinArgument(BuiltinID, TheCall);
  2796. }
  2797. // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
  2798. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  2799. // ordering for DSP is unspecified. MSA is ordered by the data format used
  2800. // by the underlying instruction i.e., df/m, df/n and then by size.
  2801. //
  2802. // FIXME: The size tests here should instead be tablegen'd along with the
  2803. // definitions from include/clang/Basic/BuiltinsMips.def.
  2804. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  2805. // be too.
  2806. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2807. unsigned i = 0, l = 0, u = 0, m = 0;
  2808. switch (BuiltinID) {
  2809. default: return false;
  2810. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  2811. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  2812. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  2813. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  2814. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  2815. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  2816. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  2817. // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
  2818. // df/m field.
  2819. // These intrinsics take an unsigned 3 bit immediate.
  2820. case Mips::BI__builtin_msa_bclri_b:
  2821. case Mips::BI__builtin_msa_bnegi_b:
  2822. case Mips::BI__builtin_msa_bseti_b:
  2823. case Mips::BI__builtin_msa_sat_s_b:
  2824. case Mips::BI__builtin_msa_sat_u_b:
  2825. case Mips::BI__builtin_msa_slli_b:
  2826. case Mips::BI__builtin_msa_srai_b:
  2827. case Mips::BI__builtin_msa_srari_b:
  2828. case Mips::BI__builtin_msa_srli_b:
  2829. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  2830. case Mips::BI__builtin_msa_binsli_b:
  2831. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  2832. // These intrinsics take an unsigned 4 bit immediate.
  2833. case Mips::BI__builtin_msa_bclri_h:
  2834. case Mips::BI__builtin_msa_bnegi_h:
  2835. case Mips::BI__builtin_msa_bseti_h:
  2836. case Mips::BI__builtin_msa_sat_s_h:
  2837. case Mips::BI__builtin_msa_sat_u_h:
  2838. case Mips::BI__builtin_msa_slli_h:
  2839. case Mips::BI__builtin_msa_srai_h:
  2840. case Mips::BI__builtin_msa_srari_h:
  2841. case Mips::BI__builtin_msa_srli_h:
  2842. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  2843. case Mips::BI__builtin_msa_binsli_h:
  2844. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  2845. // These intrinsics take an unsigned 5 bit immediate.
  2846. // The first block of intrinsics actually have an unsigned 5 bit field,
  2847. // not a df/n field.
  2848. case Mips::BI__builtin_msa_clei_u_b:
  2849. case Mips::BI__builtin_msa_clei_u_h:
  2850. case Mips::BI__builtin_msa_clei_u_w:
  2851. case Mips::BI__builtin_msa_clei_u_d:
  2852. case Mips::BI__builtin_msa_clti_u_b:
  2853. case Mips::BI__builtin_msa_clti_u_h:
  2854. case Mips::BI__builtin_msa_clti_u_w:
  2855. case Mips::BI__builtin_msa_clti_u_d:
  2856. case Mips::BI__builtin_msa_maxi_u_b:
  2857. case Mips::BI__builtin_msa_maxi_u_h:
  2858. case Mips::BI__builtin_msa_maxi_u_w:
  2859. case Mips::BI__builtin_msa_maxi_u_d:
  2860. case Mips::BI__builtin_msa_mini_u_b:
  2861. case Mips::BI__builtin_msa_mini_u_h:
  2862. case Mips::BI__builtin_msa_mini_u_w:
  2863. case Mips::BI__builtin_msa_mini_u_d:
  2864. case Mips::BI__builtin_msa_addvi_b:
  2865. case Mips::BI__builtin_msa_addvi_h:
  2866. case Mips::BI__builtin_msa_addvi_w:
  2867. case Mips::BI__builtin_msa_addvi_d:
  2868. case Mips::BI__builtin_msa_bclri_w:
  2869. case Mips::BI__builtin_msa_bnegi_w:
  2870. case Mips::BI__builtin_msa_bseti_w:
  2871. case Mips::BI__builtin_msa_sat_s_w:
  2872. case Mips::BI__builtin_msa_sat_u_w:
  2873. case Mips::BI__builtin_msa_slli_w:
  2874. case Mips::BI__builtin_msa_srai_w:
  2875. case Mips::BI__builtin_msa_srari_w:
  2876. case Mips::BI__builtin_msa_srli_w:
  2877. case Mips::BI__builtin_msa_srlri_w:
  2878. case Mips::BI__builtin_msa_subvi_b:
  2879. case Mips::BI__builtin_msa_subvi_h:
  2880. case Mips::BI__builtin_msa_subvi_w:
  2881. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  2882. case Mips::BI__builtin_msa_binsli_w:
  2883. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  2884. // These intrinsics take an unsigned 6 bit immediate.
  2885. case Mips::BI__builtin_msa_bclri_d:
  2886. case Mips::BI__builtin_msa_bnegi_d:
  2887. case Mips::BI__builtin_msa_bseti_d:
  2888. case Mips::BI__builtin_msa_sat_s_d:
  2889. case Mips::BI__builtin_msa_sat_u_d:
  2890. case Mips::BI__builtin_msa_slli_d:
  2891. case Mips::BI__builtin_msa_srai_d:
  2892. case Mips::BI__builtin_msa_srari_d:
  2893. case Mips::BI__builtin_msa_srli_d:
  2894. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  2895. case Mips::BI__builtin_msa_binsli_d:
  2896. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  2897. // These intrinsics take a signed 5 bit immediate.
  2898. case Mips::BI__builtin_msa_ceqi_b:
  2899. case Mips::BI__builtin_msa_ceqi_h:
  2900. case Mips::BI__builtin_msa_ceqi_w:
  2901. case Mips::BI__builtin_msa_ceqi_d:
  2902. case Mips::BI__builtin_msa_clti_s_b:
  2903. case Mips::BI__builtin_msa_clti_s_h:
  2904. case Mips::BI__builtin_msa_clti_s_w:
  2905. case Mips::BI__builtin_msa_clti_s_d:
  2906. case Mips::BI__builtin_msa_clei_s_b:
  2907. case Mips::BI__builtin_msa_clei_s_h:
  2908. case Mips::BI__builtin_msa_clei_s_w:
  2909. case Mips::BI__builtin_msa_clei_s_d:
  2910. case Mips::BI__builtin_msa_maxi_s_b:
  2911. case Mips::BI__builtin_msa_maxi_s_h:
  2912. case Mips::BI__builtin_msa_maxi_s_w:
  2913. case Mips::BI__builtin_msa_maxi_s_d:
  2914. case Mips::BI__builtin_msa_mini_s_b:
  2915. case Mips::BI__builtin_msa_mini_s_h:
  2916. case Mips::BI__builtin_msa_mini_s_w:
  2917. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  2918. // These intrinsics take an unsigned 8 bit immediate.
  2919. case Mips::BI__builtin_msa_andi_b:
  2920. case Mips::BI__builtin_msa_nori_b:
  2921. case Mips::BI__builtin_msa_ori_b:
  2922. case Mips::BI__builtin_msa_shf_b:
  2923. case Mips::BI__builtin_msa_shf_h:
  2924. case Mips::BI__builtin_msa_shf_w:
  2925. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  2926. case Mips::BI__builtin_msa_bseli_b:
  2927. case Mips::BI__builtin_msa_bmnzi_b:
  2928. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  2929. // df/n format
  2930. // These intrinsics take an unsigned 4 bit immediate.
  2931. case Mips::BI__builtin_msa_copy_s_b:
  2932. case Mips::BI__builtin_msa_copy_u_b:
  2933. case Mips::BI__builtin_msa_insve_b:
  2934. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  2935. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  2936. // These intrinsics take an unsigned 3 bit immediate.
  2937. case Mips::BI__builtin_msa_copy_s_h:
  2938. case Mips::BI__builtin_msa_copy_u_h:
  2939. case Mips::BI__builtin_msa_insve_h:
  2940. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  2941. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  2942. // These intrinsics take an unsigned 2 bit immediate.
  2943. case Mips::BI__builtin_msa_copy_s_w:
  2944. case Mips::BI__builtin_msa_copy_u_w:
  2945. case Mips::BI__builtin_msa_insve_w:
  2946. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  2947. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  2948. // These intrinsics take an unsigned 1 bit immediate.
  2949. case Mips::BI__builtin_msa_copy_s_d:
  2950. case Mips::BI__builtin_msa_copy_u_d:
  2951. case Mips::BI__builtin_msa_insve_d:
  2952. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  2953. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  2954. // Memory offsets and immediate loads.
  2955. // These intrinsics take a signed 10 bit immediate.
  2956. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  2957. case Mips::BI__builtin_msa_ldi_h:
  2958. case Mips::BI__builtin_msa_ldi_w:
  2959. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  2960. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
  2961. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
  2962. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
  2963. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
  2964. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
  2965. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
  2966. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
  2967. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
  2968. }
  2969. if (!m)
  2970. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2971. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  2972. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  2973. }
  2974. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2975. unsigned i = 0, l = 0, u = 0;
  2976. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  2977. BuiltinID == PPC::BI__builtin_divdeu ||
  2978. BuiltinID == PPC::BI__builtin_bpermd;
  2979. bool IsTarget64Bit = Context.getTargetInfo()
  2980. .getTypeWidth(Context
  2981. .getTargetInfo()
  2982. .getIntPtrType()) == 64;
  2983. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  2984. BuiltinID == PPC::BI__builtin_divweu ||
  2985. BuiltinID == PPC::BI__builtin_divde ||
  2986. BuiltinID == PPC::BI__builtin_divdeu;
  2987. if (Is64BitBltin && !IsTarget64Bit)
  2988. return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
  2989. << TheCall->getSourceRange();
  2990. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  2991. (BuiltinID == PPC::BI__builtin_bpermd &&
  2992. !Context.getTargetInfo().hasFeature("bpermd")))
  2993. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  2994. << TheCall->getSourceRange();
  2995. auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
  2996. if (!Context.getTargetInfo().hasFeature("vsx"))
  2997. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  2998. << TheCall->getSourceRange();
  2999. return false;
  3000. };
  3001. switch (BuiltinID) {
  3002. default: return false;
  3003. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  3004. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  3005. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  3006. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3007. case PPC::BI__builtin_tbegin:
  3008. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  3009. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  3010. case PPC::BI__builtin_tabortwc:
  3011. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  3012. case PPC::BI__builtin_tabortwci:
  3013. case PPC::BI__builtin_tabortdci:
  3014. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  3015. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  3016. case PPC::BI__builtin_vsx_xxpermdi:
  3017. case PPC::BI__builtin_vsx_xxsldwi:
  3018. return SemaBuiltinVSX(TheCall);
  3019. case PPC::BI__builtin_unpack_vector_int128:
  3020. return SemaVSXCheck(TheCall) ||
  3021. SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  3022. case PPC::BI__builtin_pack_vector_int128:
  3023. return SemaVSXCheck(TheCall);
  3024. }
  3025. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3026. }
  3027. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  3028. CallExpr *TheCall) {
  3029. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  3030. Expr *Arg = TheCall->getArg(0);
  3031. llvm::APSInt AbortCode(32);
  3032. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  3033. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  3034. return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
  3035. << Arg->getSourceRange();
  3036. }
  3037. // For intrinsics which take an immediate value as part of the instruction,
  3038. // range check them here.
  3039. unsigned i = 0, l = 0, u = 0;
  3040. switch (BuiltinID) {
  3041. default: return false;
  3042. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  3043. case SystemZ::BI__builtin_s390_verimb:
  3044. case SystemZ::BI__builtin_s390_verimh:
  3045. case SystemZ::BI__builtin_s390_verimf:
  3046. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  3047. case SystemZ::BI__builtin_s390_vfaeb:
  3048. case SystemZ::BI__builtin_s390_vfaeh:
  3049. case SystemZ::BI__builtin_s390_vfaef:
  3050. case SystemZ::BI__builtin_s390_vfaebs:
  3051. case SystemZ::BI__builtin_s390_vfaehs:
  3052. case SystemZ::BI__builtin_s390_vfaefs:
  3053. case SystemZ::BI__builtin_s390_vfaezb:
  3054. case SystemZ::BI__builtin_s390_vfaezh:
  3055. case SystemZ::BI__builtin_s390_vfaezf:
  3056. case SystemZ::BI__builtin_s390_vfaezbs:
  3057. case SystemZ::BI__builtin_s390_vfaezhs:
  3058. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  3059. case SystemZ::BI__builtin_s390_vfisb:
  3060. case SystemZ::BI__builtin_s390_vfidb:
  3061. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  3062. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3063. case SystemZ::BI__builtin_s390_vftcisb:
  3064. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  3065. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  3066. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  3067. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  3068. case SystemZ::BI__builtin_s390_vstrcb:
  3069. case SystemZ::BI__builtin_s390_vstrch:
  3070. case SystemZ::BI__builtin_s390_vstrcf:
  3071. case SystemZ::BI__builtin_s390_vstrczb:
  3072. case SystemZ::BI__builtin_s390_vstrczh:
  3073. case SystemZ::BI__builtin_s390_vstrczf:
  3074. case SystemZ::BI__builtin_s390_vstrcbs:
  3075. case SystemZ::BI__builtin_s390_vstrchs:
  3076. case SystemZ::BI__builtin_s390_vstrcfs:
  3077. case SystemZ::BI__builtin_s390_vstrczbs:
  3078. case SystemZ::BI__builtin_s390_vstrczhs:
  3079. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  3080. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  3081. case SystemZ::BI__builtin_s390_vfminsb:
  3082. case SystemZ::BI__builtin_s390_vfmaxsb:
  3083. case SystemZ::BI__builtin_s390_vfmindb:
  3084. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  3085. }
  3086. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3087. }
  3088. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  3089. /// This checks that the target supports __builtin_cpu_supports and
  3090. /// that the string argument is constant and valid.
  3091. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  3092. Expr *Arg = TheCall->getArg(0);
  3093. // Check if the argument is a string literal.
  3094. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3095. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3096. << Arg->getSourceRange();
  3097. // Check the contents of the string.
  3098. StringRef Feature =
  3099. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3100. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  3101. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
  3102. << Arg->getSourceRange();
  3103. return false;
  3104. }
  3105. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  3106. /// This checks that the target supports __builtin_cpu_is and
  3107. /// that the string argument is constant and valid.
  3108. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  3109. Expr *Arg = TheCall->getArg(0);
  3110. // Check if the argument is a string literal.
  3111. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3112. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3113. << Arg->getSourceRange();
  3114. // Check the contents of the string.
  3115. StringRef Feature =
  3116. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3117. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  3118. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
  3119. << Arg->getSourceRange();
  3120. return false;
  3121. }
  3122. // Check if the rounding mode is legal.
  3123. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  3124. // Indicates if this instruction has rounding control or just SAE.
  3125. bool HasRC = false;
  3126. unsigned ArgNum = 0;
  3127. switch (BuiltinID) {
  3128. default:
  3129. return false;
  3130. case X86::BI__builtin_ia32_vcvttsd2si32:
  3131. case X86::BI__builtin_ia32_vcvttsd2si64:
  3132. case X86::BI__builtin_ia32_vcvttsd2usi32:
  3133. case X86::BI__builtin_ia32_vcvttsd2usi64:
  3134. case X86::BI__builtin_ia32_vcvttss2si32:
  3135. case X86::BI__builtin_ia32_vcvttss2si64:
  3136. case X86::BI__builtin_ia32_vcvttss2usi32:
  3137. case X86::BI__builtin_ia32_vcvttss2usi64:
  3138. ArgNum = 1;
  3139. break;
  3140. case X86::BI__builtin_ia32_maxpd512:
  3141. case X86::BI__builtin_ia32_maxps512:
  3142. case X86::BI__builtin_ia32_minpd512:
  3143. case X86::BI__builtin_ia32_minps512:
  3144. ArgNum = 2;
  3145. break;
  3146. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  3147. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  3148. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  3149. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  3150. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  3151. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  3152. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  3153. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  3154. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  3155. case X86::BI__builtin_ia32_exp2pd_mask:
  3156. case X86::BI__builtin_ia32_exp2ps_mask:
  3157. case X86::BI__builtin_ia32_getexppd512_mask:
  3158. case X86::BI__builtin_ia32_getexpps512_mask:
  3159. case X86::BI__builtin_ia32_rcp28pd_mask:
  3160. case X86::BI__builtin_ia32_rcp28ps_mask:
  3161. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  3162. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  3163. case X86::BI__builtin_ia32_vcomisd:
  3164. case X86::BI__builtin_ia32_vcomiss:
  3165. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  3166. ArgNum = 3;
  3167. break;
  3168. case X86::BI__builtin_ia32_cmppd512_mask:
  3169. case X86::BI__builtin_ia32_cmpps512_mask:
  3170. case X86::BI__builtin_ia32_cmpsd_mask:
  3171. case X86::BI__builtin_ia32_cmpss_mask:
  3172. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  3173. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  3174. case X86::BI__builtin_ia32_getexpss128_round_mask:
  3175. case X86::BI__builtin_ia32_maxsd_round_mask:
  3176. case X86::BI__builtin_ia32_maxss_round_mask:
  3177. case X86::BI__builtin_ia32_minsd_round_mask:
  3178. case X86::BI__builtin_ia32_minss_round_mask:
  3179. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  3180. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  3181. case X86::BI__builtin_ia32_reducepd512_mask:
  3182. case X86::BI__builtin_ia32_reduceps512_mask:
  3183. case X86::BI__builtin_ia32_rndscalepd_mask:
  3184. case X86::BI__builtin_ia32_rndscaleps_mask:
  3185. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  3186. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  3187. ArgNum = 4;
  3188. break;
  3189. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3190. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3191. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3192. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3193. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3194. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3195. case X86::BI__builtin_ia32_fixupimmss_mask:
  3196. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3197. case X86::BI__builtin_ia32_rangepd512_mask:
  3198. case X86::BI__builtin_ia32_rangeps512_mask:
  3199. case X86::BI__builtin_ia32_rangesd128_round_mask:
  3200. case X86::BI__builtin_ia32_rangess128_round_mask:
  3201. case X86::BI__builtin_ia32_reducesd_mask:
  3202. case X86::BI__builtin_ia32_reducess_mask:
  3203. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3204. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3205. ArgNum = 5;
  3206. break;
  3207. case X86::BI__builtin_ia32_vcvtsd2si64:
  3208. case X86::BI__builtin_ia32_vcvtsd2si32:
  3209. case X86::BI__builtin_ia32_vcvtsd2usi32:
  3210. case X86::BI__builtin_ia32_vcvtsd2usi64:
  3211. case X86::BI__builtin_ia32_vcvtss2si32:
  3212. case X86::BI__builtin_ia32_vcvtss2si64:
  3213. case X86::BI__builtin_ia32_vcvtss2usi32:
  3214. case X86::BI__builtin_ia32_vcvtss2usi64:
  3215. case X86::BI__builtin_ia32_sqrtpd512:
  3216. case X86::BI__builtin_ia32_sqrtps512:
  3217. ArgNum = 1;
  3218. HasRC = true;
  3219. break;
  3220. case X86::BI__builtin_ia32_addpd512:
  3221. case X86::BI__builtin_ia32_addps512:
  3222. case X86::BI__builtin_ia32_divpd512:
  3223. case X86::BI__builtin_ia32_divps512:
  3224. case X86::BI__builtin_ia32_mulpd512:
  3225. case X86::BI__builtin_ia32_mulps512:
  3226. case X86::BI__builtin_ia32_subpd512:
  3227. case X86::BI__builtin_ia32_subps512:
  3228. case X86::BI__builtin_ia32_cvtsi2sd64:
  3229. case X86::BI__builtin_ia32_cvtsi2ss32:
  3230. case X86::BI__builtin_ia32_cvtsi2ss64:
  3231. case X86::BI__builtin_ia32_cvtusi2sd64:
  3232. case X86::BI__builtin_ia32_cvtusi2ss32:
  3233. case X86::BI__builtin_ia32_cvtusi2ss64:
  3234. ArgNum = 2;
  3235. HasRC = true;
  3236. break;
  3237. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  3238. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  3239. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  3240. case X86::BI__builtin_ia32_cvtpd2dq512_mask:
  3241. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  3242. case X86::BI__builtin_ia32_cvtpd2udq512_mask:
  3243. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  3244. case X86::BI__builtin_ia32_cvtps2dq512_mask:
  3245. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  3246. case X86::BI__builtin_ia32_cvtps2udq512_mask:
  3247. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  3248. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  3249. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  3250. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  3251. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  3252. ArgNum = 3;
  3253. HasRC = true;
  3254. break;
  3255. case X86::BI__builtin_ia32_addss_round_mask:
  3256. case X86::BI__builtin_ia32_addsd_round_mask:
  3257. case X86::BI__builtin_ia32_divss_round_mask:
  3258. case X86::BI__builtin_ia32_divsd_round_mask:
  3259. case X86::BI__builtin_ia32_mulss_round_mask:
  3260. case X86::BI__builtin_ia32_mulsd_round_mask:
  3261. case X86::BI__builtin_ia32_subss_round_mask:
  3262. case X86::BI__builtin_ia32_subsd_round_mask:
  3263. case X86::BI__builtin_ia32_scalefpd512_mask:
  3264. case X86::BI__builtin_ia32_scalefps512_mask:
  3265. case X86::BI__builtin_ia32_scalefsd_round_mask:
  3266. case X86::BI__builtin_ia32_scalefss_round_mask:
  3267. case X86::BI__builtin_ia32_getmantpd512_mask:
  3268. case X86::BI__builtin_ia32_getmantps512_mask:
  3269. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  3270. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  3271. case X86::BI__builtin_ia32_sqrtss_round_mask:
  3272. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  3273. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  3274. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  3275. case X86::BI__builtin_ia32_vfmaddss3_mask:
  3276. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  3277. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  3278. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  3279. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  3280. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  3281. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  3282. case X86::BI__builtin_ia32_vfmaddps512_mask:
  3283. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  3284. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  3285. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  3286. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  3287. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  3288. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  3289. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  3290. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  3291. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  3292. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  3293. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  3294. ArgNum = 4;
  3295. HasRC = true;
  3296. break;
  3297. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3298. case X86::BI__builtin_ia32_getmantss_round_mask:
  3299. ArgNum = 5;
  3300. HasRC = true;
  3301. break;
  3302. }
  3303. llvm::APSInt Result;
  3304. // We can't check the value of a dependent argument.
  3305. Expr *Arg = TheCall->getArg(ArgNum);
  3306. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3307. return false;
  3308. // Check constant-ness first.
  3309. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3310. return true;
  3311. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  3312. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  3313. // combined with ROUND_NO_EXC.
  3314. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  3315. Result == 8/*ROUND_NO_EXC*/ ||
  3316. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  3317. return false;
  3318. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
  3319. << Arg->getSourceRange();
  3320. }
  3321. // Check if the gather/scatter scale is legal.
  3322. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  3323. CallExpr *TheCall) {
  3324. unsigned ArgNum = 0;
  3325. switch (BuiltinID) {
  3326. default:
  3327. return false;
  3328. case X86::BI__builtin_ia32_gatherpfdpd:
  3329. case X86::BI__builtin_ia32_gatherpfdps:
  3330. case X86::BI__builtin_ia32_gatherpfqpd:
  3331. case X86::BI__builtin_ia32_gatherpfqps:
  3332. case X86::BI__builtin_ia32_scatterpfdpd:
  3333. case X86::BI__builtin_ia32_scatterpfdps:
  3334. case X86::BI__builtin_ia32_scatterpfqpd:
  3335. case X86::BI__builtin_ia32_scatterpfqps:
  3336. ArgNum = 3;
  3337. break;
  3338. case X86::BI__builtin_ia32_gatherd_pd:
  3339. case X86::BI__builtin_ia32_gatherd_pd256:
  3340. case X86::BI__builtin_ia32_gatherq_pd:
  3341. case X86::BI__builtin_ia32_gatherq_pd256:
  3342. case X86::BI__builtin_ia32_gatherd_ps:
  3343. case X86::BI__builtin_ia32_gatherd_ps256:
  3344. case X86::BI__builtin_ia32_gatherq_ps:
  3345. case X86::BI__builtin_ia32_gatherq_ps256:
  3346. case X86::BI__builtin_ia32_gatherd_q:
  3347. case X86::BI__builtin_ia32_gatherd_q256:
  3348. case X86::BI__builtin_ia32_gatherq_q:
  3349. case X86::BI__builtin_ia32_gatherq_q256:
  3350. case X86::BI__builtin_ia32_gatherd_d:
  3351. case X86::BI__builtin_ia32_gatherd_d256:
  3352. case X86::BI__builtin_ia32_gatherq_d:
  3353. case X86::BI__builtin_ia32_gatherq_d256:
  3354. case X86::BI__builtin_ia32_gather3div2df:
  3355. case X86::BI__builtin_ia32_gather3div2di:
  3356. case X86::BI__builtin_ia32_gather3div4df:
  3357. case X86::BI__builtin_ia32_gather3div4di:
  3358. case X86::BI__builtin_ia32_gather3div4sf:
  3359. case X86::BI__builtin_ia32_gather3div4si:
  3360. case X86::BI__builtin_ia32_gather3div8sf:
  3361. case X86::BI__builtin_ia32_gather3div8si:
  3362. case X86::BI__builtin_ia32_gather3siv2df:
  3363. case X86::BI__builtin_ia32_gather3siv2di:
  3364. case X86::BI__builtin_ia32_gather3siv4df:
  3365. case X86::BI__builtin_ia32_gather3siv4di:
  3366. case X86::BI__builtin_ia32_gather3siv4sf:
  3367. case X86::BI__builtin_ia32_gather3siv4si:
  3368. case X86::BI__builtin_ia32_gather3siv8sf:
  3369. case X86::BI__builtin_ia32_gather3siv8si:
  3370. case X86::BI__builtin_ia32_gathersiv8df:
  3371. case X86::BI__builtin_ia32_gathersiv16sf:
  3372. case X86::BI__builtin_ia32_gatherdiv8df:
  3373. case X86::BI__builtin_ia32_gatherdiv16sf:
  3374. case X86::BI__builtin_ia32_gathersiv8di:
  3375. case X86::BI__builtin_ia32_gathersiv16si:
  3376. case X86::BI__builtin_ia32_gatherdiv8di:
  3377. case X86::BI__builtin_ia32_gatherdiv16si:
  3378. case X86::BI__builtin_ia32_scatterdiv2df:
  3379. case X86::BI__builtin_ia32_scatterdiv2di:
  3380. case X86::BI__builtin_ia32_scatterdiv4df:
  3381. case X86::BI__builtin_ia32_scatterdiv4di:
  3382. case X86::BI__builtin_ia32_scatterdiv4sf:
  3383. case X86::BI__builtin_ia32_scatterdiv4si:
  3384. case X86::BI__builtin_ia32_scatterdiv8sf:
  3385. case X86::BI__builtin_ia32_scatterdiv8si:
  3386. case X86::BI__builtin_ia32_scattersiv2df:
  3387. case X86::BI__builtin_ia32_scattersiv2di:
  3388. case X86::BI__builtin_ia32_scattersiv4df:
  3389. case X86::BI__builtin_ia32_scattersiv4di:
  3390. case X86::BI__builtin_ia32_scattersiv4sf:
  3391. case X86::BI__builtin_ia32_scattersiv4si:
  3392. case X86::BI__builtin_ia32_scattersiv8sf:
  3393. case X86::BI__builtin_ia32_scattersiv8si:
  3394. case X86::BI__builtin_ia32_scattersiv8df:
  3395. case X86::BI__builtin_ia32_scattersiv16sf:
  3396. case X86::BI__builtin_ia32_scatterdiv8df:
  3397. case X86::BI__builtin_ia32_scatterdiv16sf:
  3398. case X86::BI__builtin_ia32_scattersiv8di:
  3399. case X86::BI__builtin_ia32_scattersiv16si:
  3400. case X86::BI__builtin_ia32_scatterdiv8di:
  3401. case X86::BI__builtin_ia32_scatterdiv16si:
  3402. ArgNum = 4;
  3403. break;
  3404. }
  3405. llvm::APSInt Result;
  3406. // We can't check the value of a dependent argument.
  3407. Expr *Arg = TheCall->getArg(ArgNum);
  3408. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3409. return false;
  3410. // Check constant-ness first.
  3411. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3412. return true;
  3413. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  3414. return false;
  3415. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
  3416. << Arg->getSourceRange();
  3417. }
  3418. static bool isX86_32Builtin(unsigned BuiltinID) {
  3419. // These builtins only work on x86-32 targets.
  3420. switch (BuiltinID) {
  3421. case X86::BI__builtin_ia32_readeflags_u32:
  3422. case X86::BI__builtin_ia32_writeeflags_u32:
  3423. return true;
  3424. }
  3425. return false;
  3426. }
  3427. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  3428. if (BuiltinID == X86::BI__builtin_cpu_supports)
  3429. return SemaBuiltinCpuSupports(*this, TheCall);
  3430. if (BuiltinID == X86::BI__builtin_cpu_is)
  3431. return SemaBuiltinCpuIs(*this, TheCall);
  3432. // Check for 32-bit only builtins on a 64-bit target.
  3433. const llvm::Triple &TT = Context.getTargetInfo().getTriple();
  3434. if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
  3435. return Diag(TheCall->getCallee()->getBeginLoc(),
  3436. diag::err_32_bit_builtin_64_bit_tgt);
  3437. // If the intrinsic has rounding or SAE make sure its valid.
  3438. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  3439. return true;
  3440. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  3441. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  3442. return true;
  3443. // For intrinsics which take an immediate value as part of the instruction,
  3444. // range check them here.
  3445. int i = 0, l = 0, u = 0;
  3446. switch (BuiltinID) {
  3447. default:
  3448. return false;
  3449. case X86::BI__builtin_ia32_vec_ext_v2si:
  3450. case X86::BI__builtin_ia32_vec_ext_v2di:
  3451. case X86::BI__builtin_ia32_vextractf128_pd256:
  3452. case X86::BI__builtin_ia32_vextractf128_ps256:
  3453. case X86::BI__builtin_ia32_vextractf128_si256:
  3454. case X86::BI__builtin_ia32_extract128i256:
  3455. case X86::BI__builtin_ia32_extractf64x4_mask:
  3456. case X86::BI__builtin_ia32_extracti64x4_mask:
  3457. case X86::BI__builtin_ia32_extractf32x8_mask:
  3458. case X86::BI__builtin_ia32_extracti32x8_mask:
  3459. case X86::BI__builtin_ia32_extractf64x2_256_mask:
  3460. case X86::BI__builtin_ia32_extracti64x2_256_mask:
  3461. case X86::BI__builtin_ia32_extractf32x4_256_mask:
  3462. case X86::BI__builtin_ia32_extracti32x4_256_mask:
  3463. i = 1; l = 0; u = 1;
  3464. break;
  3465. case X86::BI__builtin_ia32_vec_set_v2di:
  3466. case X86::BI__builtin_ia32_vinsertf128_pd256:
  3467. case X86::BI__builtin_ia32_vinsertf128_ps256:
  3468. case X86::BI__builtin_ia32_vinsertf128_si256:
  3469. case X86::BI__builtin_ia32_insert128i256:
  3470. case X86::BI__builtin_ia32_insertf32x8:
  3471. case X86::BI__builtin_ia32_inserti32x8:
  3472. case X86::BI__builtin_ia32_insertf64x4:
  3473. case X86::BI__builtin_ia32_inserti64x4:
  3474. case X86::BI__builtin_ia32_insertf64x2_256:
  3475. case X86::BI__builtin_ia32_inserti64x2_256:
  3476. case X86::BI__builtin_ia32_insertf32x4_256:
  3477. case X86::BI__builtin_ia32_inserti32x4_256:
  3478. i = 2; l = 0; u = 1;
  3479. break;
  3480. case X86::BI__builtin_ia32_vpermilpd:
  3481. case X86::BI__builtin_ia32_vec_ext_v4hi:
  3482. case X86::BI__builtin_ia32_vec_ext_v4si:
  3483. case X86::BI__builtin_ia32_vec_ext_v4sf:
  3484. case X86::BI__builtin_ia32_vec_ext_v4di:
  3485. case X86::BI__builtin_ia32_extractf32x4_mask:
  3486. case X86::BI__builtin_ia32_extracti32x4_mask:
  3487. case X86::BI__builtin_ia32_extractf64x2_512_mask:
  3488. case X86::BI__builtin_ia32_extracti64x2_512_mask:
  3489. i = 1; l = 0; u = 3;
  3490. break;
  3491. case X86::BI_mm_prefetch:
  3492. case X86::BI__builtin_ia32_vec_ext_v8hi:
  3493. case X86::BI__builtin_ia32_vec_ext_v8si:
  3494. i = 1; l = 0; u = 7;
  3495. break;
  3496. case X86::BI__builtin_ia32_sha1rnds4:
  3497. case X86::BI__builtin_ia32_blendpd:
  3498. case X86::BI__builtin_ia32_shufpd:
  3499. case X86::BI__builtin_ia32_vec_set_v4hi:
  3500. case X86::BI__builtin_ia32_vec_set_v4si:
  3501. case X86::BI__builtin_ia32_vec_set_v4di:
  3502. case X86::BI__builtin_ia32_shuf_f32x4_256:
  3503. case X86::BI__builtin_ia32_shuf_f64x2_256:
  3504. case X86::BI__builtin_ia32_shuf_i32x4_256:
  3505. case X86::BI__builtin_ia32_shuf_i64x2_256:
  3506. case X86::BI__builtin_ia32_insertf64x2_512:
  3507. case X86::BI__builtin_ia32_inserti64x2_512:
  3508. case X86::BI__builtin_ia32_insertf32x4:
  3509. case X86::BI__builtin_ia32_inserti32x4:
  3510. i = 2; l = 0; u = 3;
  3511. break;
  3512. case X86::BI__builtin_ia32_vpermil2pd:
  3513. case X86::BI__builtin_ia32_vpermil2pd256:
  3514. case X86::BI__builtin_ia32_vpermil2ps:
  3515. case X86::BI__builtin_ia32_vpermil2ps256:
  3516. i = 3; l = 0; u = 3;
  3517. break;
  3518. case X86::BI__builtin_ia32_cmpb128_mask:
  3519. case X86::BI__builtin_ia32_cmpw128_mask:
  3520. case X86::BI__builtin_ia32_cmpd128_mask:
  3521. case X86::BI__builtin_ia32_cmpq128_mask:
  3522. case X86::BI__builtin_ia32_cmpb256_mask:
  3523. case X86::BI__builtin_ia32_cmpw256_mask:
  3524. case X86::BI__builtin_ia32_cmpd256_mask:
  3525. case X86::BI__builtin_ia32_cmpq256_mask:
  3526. case X86::BI__builtin_ia32_cmpb512_mask:
  3527. case X86::BI__builtin_ia32_cmpw512_mask:
  3528. case X86::BI__builtin_ia32_cmpd512_mask:
  3529. case X86::BI__builtin_ia32_cmpq512_mask:
  3530. case X86::BI__builtin_ia32_ucmpb128_mask:
  3531. case X86::BI__builtin_ia32_ucmpw128_mask:
  3532. case X86::BI__builtin_ia32_ucmpd128_mask:
  3533. case X86::BI__builtin_ia32_ucmpq128_mask:
  3534. case X86::BI__builtin_ia32_ucmpb256_mask:
  3535. case X86::BI__builtin_ia32_ucmpw256_mask:
  3536. case X86::BI__builtin_ia32_ucmpd256_mask:
  3537. case X86::BI__builtin_ia32_ucmpq256_mask:
  3538. case X86::BI__builtin_ia32_ucmpb512_mask:
  3539. case X86::BI__builtin_ia32_ucmpw512_mask:
  3540. case X86::BI__builtin_ia32_ucmpd512_mask:
  3541. case X86::BI__builtin_ia32_ucmpq512_mask:
  3542. case X86::BI__builtin_ia32_vpcomub:
  3543. case X86::BI__builtin_ia32_vpcomuw:
  3544. case X86::BI__builtin_ia32_vpcomud:
  3545. case X86::BI__builtin_ia32_vpcomuq:
  3546. case X86::BI__builtin_ia32_vpcomb:
  3547. case X86::BI__builtin_ia32_vpcomw:
  3548. case X86::BI__builtin_ia32_vpcomd:
  3549. case X86::BI__builtin_ia32_vpcomq:
  3550. case X86::BI__builtin_ia32_vec_set_v8hi:
  3551. case X86::BI__builtin_ia32_vec_set_v8si:
  3552. i = 2; l = 0; u = 7;
  3553. break;
  3554. case X86::BI__builtin_ia32_vpermilpd256:
  3555. case X86::BI__builtin_ia32_roundps:
  3556. case X86::BI__builtin_ia32_roundpd:
  3557. case X86::BI__builtin_ia32_roundps256:
  3558. case X86::BI__builtin_ia32_roundpd256:
  3559. case X86::BI__builtin_ia32_getmantpd128_mask:
  3560. case X86::BI__builtin_ia32_getmantpd256_mask:
  3561. case X86::BI__builtin_ia32_getmantps128_mask:
  3562. case X86::BI__builtin_ia32_getmantps256_mask:
  3563. case X86::BI__builtin_ia32_getmantpd512_mask:
  3564. case X86::BI__builtin_ia32_getmantps512_mask:
  3565. case X86::BI__builtin_ia32_vec_ext_v16qi:
  3566. case X86::BI__builtin_ia32_vec_ext_v16hi:
  3567. i = 1; l = 0; u = 15;
  3568. break;
  3569. case X86::BI__builtin_ia32_pblendd128:
  3570. case X86::BI__builtin_ia32_blendps:
  3571. case X86::BI__builtin_ia32_blendpd256:
  3572. case X86::BI__builtin_ia32_shufpd256:
  3573. case X86::BI__builtin_ia32_roundss:
  3574. case X86::BI__builtin_ia32_roundsd:
  3575. case X86::BI__builtin_ia32_rangepd128_mask:
  3576. case X86::BI__builtin_ia32_rangepd256_mask:
  3577. case X86::BI__builtin_ia32_rangepd512_mask:
  3578. case X86::BI__builtin_ia32_rangeps128_mask:
  3579. case X86::BI__builtin_ia32_rangeps256_mask:
  3580. case X86::BI__builtin_ia32_rangeps512_mask:
  3581. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3582. case X86::BI__builtin_ia32_getmantss_round_mask:
  3583. case X86::BI__builtin_ia32_vec_set_v16qi:
  3584. case X86::BI__builtin_ia32_vec_set_v16hi:
  3585. i = 2; l = 0; u = 15;
  3586. break;
  3587. case X86::BI__builtin_ia32_vec_ext_v32qi:
  3588. i = 1; l = 0; u = 31;
  3589. break;
  3590. case X86::BI__builtin_ia32_cmpps:
  3591. case X86::BI__builtin_ia32_cmpss:
  3592. case X86::BI__builtin_ia32_cmppd:
  3593. case X86::BI__builtin_ia32_cmpsd:
  3594. case X86::BI__builtin_ia32_cmpps256:
  3595. case X86::BI__builtin_ia32_cmppd256:
  3596. case X86::BI__builtin_ia32_cmpps128_mask:
  3597. case X86::BI__builtin_ia32_cmppd128_mask:
  3598. case X86::BI__builtin_ia32_cmpps256_mask:
  3599. case X86::BI__builtin_ia32_cmppd256_mask:
  3600. case X86::BI__builtin_ia32_cmpps512_mask:
  3601. case X86::BI__builtin_ia32_cmppd512_mask:
  3602. case X86::BI__builtin_ia32_cmpsd_mask:
  3603. case X86::BI__builtin_ia32_cmpss_mask:
  3604. case X86::BI__builtin_ia32_vec_set_v32qi:
  3605. i = 2; l = 0; u = 31;
  3606. break;
  3607. case X86::BI__builtin_ia32_permdf256:
  3608. case X86::BI__builtin_ia32_permdi256:
  3609. case X86::BI__builtin_ia32_permdf512:
  3610. case X86::BI__builtin_ia32_permdi512:
  3611. case X86::BI__builtin_ia32_vpermilps:
  3612. case X86::BI__builtin_ia32_vpermilps256:
  3613. case X86::BI__builtin_ia32_vpermilpd512:
  3614. case X86::BI__builtin_ia32_vpermilps512:
  3615. case X86::BI__builtin_ia32_pshufd:
  3616. case X86::BI__builtin_ia32_pshufd256:
  3617. case X86::BI__builtin_ia32_pshufd512:
  3618. case X86::BI__builtin_ia32_pshufhw:
  3619. case X86::BI__builtin_ia32_pshufhw256:
  3620. case X86::BI__builtin_ia32_pshufhw512:
  3621. case X86::BI__builtin_ia32_pshuflw:
  3622. case X86::BI__builtin_ia32_pshuflw256:
  3623. case X86::BI__builtin_ia32_pshuflw512:
  3624. case X86::BI__builtin_ia32_vcvtps2ph:
  3625. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  3626. case X86::BI__builtin_ia32_vcvtps2ph256:
  3627. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  3628. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  3629. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  3630. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  3631. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  3632. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  3633. case X86::BI__builtin_ia32_rndscaleps_mask:
  3634. case X86::BI__builtin_ia32_rndscalepd_mask:
  3635. case X86::BI__builtin_ia32_reducepd128_mask:
  3636. case X86::BI__builtin_ia32_reducepd256_mask:
  3637. case X86::BI__builtin_ia32_reducepd512_mask:
  3638. case X86::BI__builtin_ia32_reduceps128_mask:
  3639. case X86::BI__builtin_ia32_reduceps256_mask:
  3640. case X86::BI__builtin_ia32_reduceps512_mask:
  3641. case X86::BI__builtin_ia32_prold512:
  3642. case X86::BI__builtin_ia32_prolq512:
  3643. case X86::BI__builtin_ia32_prold128:
  3644. case X86::BI__builtin_ia32_prold256:
  3645. case X86::BI__builtin_ia32_prolq128:
  3646. case X86::BI__builtin_ia32_prolq256:
  3647. case X86::BI__builtin_ia32_prord512:
  3648. case X86::BI__builtin_ia32_prorq512:
  3649. case X86::BI__builtin_ia32_prord128:
  3650. case X86::BI__builtin_ia32_prord256:
  3651. case X86::BI__builtin_ia32_prorq128:
  3652. case X86::BI__builtin_ia32_prorq256:
  3653. case X86::BI__builtin_ia32_fpclasspd128_mask:
  3654. case X86::BI__builtin_ia32_fpclasspd256_mask:
  3655. case X86::BI__builtin_ia32_fpclassps128_mask:
  3656. case X86::BI__builtin_ia32_fpclassps256_mask:
  3657. case X86::BI__builtin_ia32_fpclassps512_mask:
  3658. case X86::BI__builtin_ia32_fpclasspd512_mask:
  3659. case X86::BI__builtin_ia32_fpclasssd_mask:
  3660. case X86::BI__builtin_ia32_fpclassss_mask:
  3661. case X86::BI__builtin_ia32_pslldqi128_byteshift:
  3662. case X86::BI__builtin_ia32_pslldqi256_byteshift:
  3663. case X86::BI__builtin_ia32_pslldqi512_byteshift:
  3664. case X86::BI__builtin_ia32_psrldqi128_byteshift:
  3665. case X86::BI__builtin_ia32_psrldqi256_byteshift:
  3666. case X86::BI__builtin_ia32_psrldqi512_byteshift:
  3667. case X86::BI__builtin_ia32_kshiftliqi:
  3668. case X86::BI__builtin_ia32_kshiftlihi:
  3669. case X86::BI__builtin_ia32_kshiftlisi:
  3670. case X86::BI__builtin_ia32_kshiftlidi:
  3671. case X86::BI__builtin_ia32_kshiftriqi:
  3672. case X86::BI__builtin_ia32_kshiftrihi:
  3673. case X86::BI__builtin_ia32_kshiftrisi:
  3674. case X86::BI__builtin_ia32_kshiftridi:
  3675. i = 1; l = 0; u = 255;
  3676. break;
  3677. case X86::BI__builtin_ia32_vperm2f128_pd256:
  3678. case X86::BI__builtin_ia32_vperm2f128_ps256:
  3679. case X86::BI__builtin_ia32_vperm2f128_si256:
  3680. case X86::BI__builtin_ia32_permti256:
  3681. case X86::BI__builtin_ia32_pblendw128:
  3682. case X86::BI__builtin_ia32_pblendw256:
  3683. case X86::BI__builtin_ia32_blendps256:
  3684. case X86::BI__builtin_ia32_pblendd256:
  3685. case X86::BI__builtin_ia32_palignr128:
  3686. case X86::BI__builtin_ia32_palignr256:
  3687. case X86::BI__builtin_ia32_palignr512:
  3688. case X86::BI__builtin_ia32_alignq512:
  3689. case X86::BI__builtin_ia32_alignd512:
  3690. case X86::BI__builtin_ia32_alignd128:
  3691. case X86::BI__builtin_ia32_alignd256:
  3692. case X86::BI__builtin_ia32_alignq128:
  3693. case X86::BI__builtin_ia32_alignq256:
  3694. case X86::BI__builtin_ia32_vcomisd:
  3695. case X86::BI__builtin_ia32_vcomiss:
  3696. case X86::BI__builtin_ia32_shuf_f32x4:
  3697. case X86::BI__builtin_ia32_shuf_f64x2:
  3698. case X86::BI__builtin_ia32_shuf_i32x4:
  3699. case X86::BI__builtin_ia32_shuf_i64x2:
  3700. case X86::BI__builtin_ia32_shufpd512:
  3701. case X86::BI__builtin_ia32_shufps:
  3702. case X86::BI__builtin_ia32_shufps256:
  3703. case X86::BI__builtin_ia32_shufps512:
  3704. case X86::BI__builtin_ia32_dbpsadbw128:
  3705. case X86::BI__builtin_ia32_dbpsadbw256:
  3706. case X86::BI__builtin_ia32_dbpsadbw512:
  3707. case X86::BI__builtin_ia32_vpshldd128:
  3708. case X86::BI__builtin_ia32_vpshldd256:
  3709. case X86::BI__builtin_ia32_vpshldd512:
  3710. case X86::BI__builtin_ia32_vpshldq128:
  3711. case X86::BI__builtin_ia32_vpshldq256:
  3712. case X86::BI__builtin_ia32_vpshldq512:
  3713. case X86::BI__builtin_ia32_vpshldw128:
  3714. case X86::BI__builtin_ia32_vpshldw256:
  3715. case X86::BI__builtin_ia32_vpshldw512:
  3716. case X86::BI__builtin_ia32_vpshrdd128:
  3717. case X86::BI__builtin_ia32_vpshrdd256:
  3718. case X86::BI__builtin_ia32_vpshrdd512:
  3719. case X86::BI__builtin_ia32_vpshrdq128:
  3720. case X86::BI__builtin_ia32_vpshrdq256:
  3721. case X86::BI__builtin_ia32_vpshrdq512:
  3722. case X86::BI__builtin_ia32_vpshrdw128:
  3723. case X86::BI__builtin_ia32_vpshrdw256:
  3724. case X86::BI__builtin_ia32_vpshrdw512:
  3725. i = 2; l = 0; u = 255;
  3726. break;
  3727. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3728. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3729. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3730. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3731. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3732. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3733. case X86::BI__builtin_ia32_fixupimmss_mask:
  3734. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3735. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  3736. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  3737. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  3738. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  3739. case X86::BI__builtin_ia32_fixupimmps128_mask:
  3740. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  3741. case X86::BI__builtin_ia32_fixupimmps256_mask:
  3742. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  3743. case X86::BI__builtin_ia32_pternlogd512_mask:
  3744. case X86::BI__builtin_ia32_pternlogd512_maskz:
  3745. case X86::BI__builtin_ia32_pternlogq512_mask:
  3746. case X86::BI__builtin_ia32_pternlogq512_maskz:
  3747. case X86::BI__builtin_ia32_pternlogd128_mask:
  3748. case X86::BI__builtin_ia32_pternlogd128_maskz:
  3749. case X86::BI__builtin_ia32_pternlogd256_mask:
  3750. case X86::BI__builtin_ia32_pternlogd256_maskz:
  3751. case X86::BI__builtin_ia32_pternlogq128_mask:
  3752. case X86::BI__builtin_ia32_pternlogq128_maskz:
  3753. case X86::BI__builtin_ia32_pternlogq256_mask:
  3754. case X86::BI__builtin_ia32_pternlogq256_maskz:
  3755. i = 3; l = 0; u = 255;
  3756. break;
  3757. case X86::BI__builtin_ia32_gatherpfdpd:
  3758. case X86::BI__builtin_ia32_gatherpfdps:
  3759. case X86::BI__builtin_ia32_gatherpfqpd:
  3760. case X86::BI__builtin_ia32_gatherpfqps:
  3761. case X86::BI__builtin_ia32_scatterpfdpd:
  3762. case X86::BI__builtin_ia32_scatterpfdps:
  3763. case X86::BI__builtin_ia32_scatterpfqpd:
  3764. case X86::BI__builtin_ia32_scatterpfqps:
  3765. i = 4; l = 2; u = 3;
  3766. break;
  3767. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3768. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3769. i = 4; l = 0; u = 255;
  3770. break;
  3771. }
  3772. // Note that we don't force a hard error on the range check here, allowing
  3773. // template-generated or macro-generated dead code to potentially have out-of-
  3774. // range values. These need to code generate, but don't need to necessarily
  3775. // make any sense. We use a warning that defaults to an error.
  3776. return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
  3777. }
  3778. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  3779. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  3780. /// Returns true when the format fits the function and the FormatStringInfo has
  3781. /// been populated.
  3782. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  3783. FormatStringInfo *FSI) {
  3784. FSI->HasVAListArg = Format->getFirstArg() == 0;
  3785. FSI->FormatIdx = Format->getFormatIdx() - 1;
  3786. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  3787. // The way the format attribute works in GCC, the implicit this argument
  3788. // of member functions is counted. However, it doesn't appear in our own
  3789. // lists, so decrement format_idx in that case.
  3790. if (IsCXXMember) {
  3791. if(FSI->FormatIdx == 0)
  3792. return false;
  3793. --FSI->FormatIdx;
  3794. if (FSI->FirstDataArg != 0)
  3795. --FSI->FirstDataArg;
  3796. }
  3797. return true;
  3798. }
  3799. /// Checks if a the given expression evaluates to null.
  3800. ///
  3801. /// Returns true if the value evaluates to null.
  3802. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  3803. // If the expression has non-null type, it doesn't evaluate to null.
  3804. if (auto nullability
  3805. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  3806. if (*nullability == NullabilityKind::NonNull)
  3807. return false;
  3808. }
  3809. // As a special case, transparent unions initialized with zero are
  3810. // considered null for the purposes of the nonnull attribute.
  3811. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  3812. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  3813. if (const CompoundLiteralExpr *CLE =
  3814. dyn_cast<CompoundLiteralExpr>(Expr))
  3815. if (const InitListExpr *ILE =
  3816. dyn_cast<InitListExpr>(CLE->getInitializer()))
  3817. Expr = ILE->getInit(0);
  3818. }
  3819. bool Result;
  3820. return (!Expr->isValueDependent() &&
  3821. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  3822. !Result);
  3823. }
  3824. static void CheckNonNullArgument(Sema &S,
  3825. const Expr *ArgExpr,
  3826. SourceLocation CallSiteLoc) {
  3827. if (CheckNonNullExpr(S, ArgExpr))
  3828. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  3829. S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
  3830. }
  3831. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  3832. FormatStringInfo FSI;
  3833. if ((GetFormatStringType(Format) == FST_NSString) &&
  3834. getFormatStringInfo(Format, false, &FSI)) {
  3835. Idx = FSI.FormatIdx;
  3836. return true;
  3837. }
  3838. return false;
  3839. }
  3840. /// Diagnose use of %s directive in an NSString which is being passed
  3841. /// as formatting string to formatting method.
  3842. static void
  3843. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  3844. const NamedDecl *FDecl,
  3845. Expr **Args,
  3846. unsigned NumArgs) {
  3847. unsigned Idx = 0;
  3848. bool Format = false;
  3849. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  3850. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  3851. Idx = 2;
  3852. Format = true;
  3853. }
  3854. else
  3855. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3856. if (S.GetFormatNSStringIdx(I, Idx)) {
  3857. Format = true;
  3858. break;
  3859. }
  3860. }
  3861. if (!Format || NumArgs <= Idx)
  3862. return;
  3863. const Expr *FormatExpr = Args[Idx];
  3864. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  3865. FormatExpr = CSCE->getSubExpr();
  3866. const StringLiteral *FormatString;
  3867. if (const ObjCStringLiteral *OSL =
  3868. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  3869. FormatString = OSL->getString();
  3870. else
  3871. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  3872. if (!FormatString)
  3873. return;
  3874. if (S.FormatStringHasSArg(FormatString)) {
  3875. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  3876. << "%s" << 1 << 1;
  3877. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  3878. << FDecl->getDeclName();
  3879. }
  3880. }
  3881. /// Determine whether the given type has a non-null nullability annotation.
  3882. static bool isNonNullType(ASTContext &ctx, QualType type) {
  3883. if (auto nullability = type->getNullability(ctx))
  3884. return *nullability == NullabilityKind::NonNull;
  3885. return false;
  3886. }
  3887. static void CheckNonNullArguments(Sema &S,
  3888. const NamedDecl *FDecl,
  3889. const FunctionProtoType *Proto,
  3890. ArrayRef<const Expr *> Args,
  3891. SourceLocation CallSiteLoc) {
  3892. assert((FDecl || Proto) && "Need a function declaration or prototype");
  3893. // Check the attributes attached to the method/function itself.
  3894. llvm::SmallBitVector NonNullArgs;
  3895. if (FDecl) {
  3896. // Handle the nonnull attribute on the function/method declaration itself.
  3897. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  3898. if (!NonNull->args_size()) {
  3899. // Easy case: all pointer arguments are nonnull.
  3900. for (const auto *Arg : Args)
  3901. if (S.isValidPointerAttrType(Arg->getType()))
  3902. CheckNonNullArgument(S, Arg, CallSiteLoc);
  3903. return;
  3904. }
  3905. for (const ParamIdx &Idx : NonNull->args()) {
  3906. unsigned IdxAST = Idx.getASTIndex();
  3907. if (IdxAST >= Args.size())
  3908. continue;
  3909. if (NonNullArgs.empty())
  3910. NonNullArgs.resize(Args.size());
  3911. NonNullArgs.set(IdxAST);
  3912. }
  3913. }
  3914. }
  3915. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  3916. // Handle the nonnull attribute on the parameters of the
  3917. // function/method.
  3918. ArrayRef<ParmVarDecl*> parms;
  3919. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  3920. parms = FD->parameters();
  3921. else
  3922. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  3923. unsigned ParamIndex = 0;
  3924. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  3925. I != E; ++I, ++ParamIndex) {
  3926. const ParmVarDecl *PVD = *I;
  3927. if (PVD->hasAttr<NonNullAttr>() ||
  3928. isNonNullType(S.Context, PVD->getType())) {
  3929. if (NonNullArgs.empty())
  3930. NonNullArgs.resize(Args.size());
  3931. NonNullArgs.set(ParamIndex);
  3932. }
  3933. }
  3934. } else {
  3935. // If we have a non-function, non-method declaration but no
  3936. // function prototype, try to dig out the function prototype.
  3937. if (!Proto) {
  3938. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  3939. QualType type = VD->getType().getNonReferenceType();
  3940. if (auto pointerType = type->getAs<PointerType>())
  3941. type = pointerType->getPointeeType();
  3942. else if (auto blockType = type->getAs<BlockPointerType>())
  3943. type = blockType->getPointeeType();
  3944. // FIXME: data member pointers?
  3945. // Dig out the function prototype, if there is one.
  3946. Proto = type->getAs<FunctionProtoType>();
  3947. }
  3948. }
  3949. // Fill in non-null argument information from the nullability
  3950. // information on the parameter types (if we have them).
  3951. if (Proto) {
  3952. unsigned Index = 0;
  3953. for (auto paramType : Proto->getParamTypes()) {
  3954. if (isNonNullType(S.Context, paramType)) {
  3955. if (NonNullArgs.empty())
  3956. NonNullArgs.resize(Args.size());
  3957. NonNullArgs.set(Index);
  3958. }
  3959. ++Index;
  3960. }
  3961. }
  3962. }
  3963. // Check for non-null arguments.
  3964. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  3965. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  3966. if (NonNullArgs[ArgIndex])
  3967. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  3968. }
  3969. }
  3970. /// Handles the checks for format strings, non-POD arguments to vararg
  3971. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  3972. /// attributes.
  3973. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  3974. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  3975. bool IsMemberFunction, SourceLocation Loc,
  3976. SourceRange Range, VariadicCallType CallType) {
  3977. // FIXME: We should check as much as we can in the template definition.
  3978. if (CurContext->isDependentContext())
  3979. return;
  3980. // Printf and scanf checking.
  3981. llvm::SmallBitVector CheckedVarArgs;
  3982. if (FDecl) {
  3983. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3984. // Only create vector if there are format attributes.
  3985. CheckedVarArgs.resize(Args.size());
  3986. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  3987. CheckedVarArgs);
  3988. }
  3989. }
  3990. // Refuse POD arguments that weren't caught by the format string
  3991. // checks above.
  3992. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  3993. if (CallType != VariadicDoesNotApply &&
  3994. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  3995. unsigned NumParams = Proto ? Proto->getNumParams()
  3996. : FDecl && isa<FunctionDecl>(FDecl)
  3997. ? cast<FunctionDecl>(FDecl)->getNumParams()
  3998. : FDecl && isa<ObjCMethodDecl>(FDecl)
  3999. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  4000. : 0;
  4001. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  4002. // Args[ArgIdx] can be null in malformed code.
  4003. if (const Expr *Arg = Args[ArgIdx]) {
  4004. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  4005. checkVariadicArgument(Arg, CallType);
  4006. }
  4007. }
  4008. }
  4009. if (FDecl || Proto) {
  4010. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  4011. // Type safety checking.
  4012. if (FDecl) {
  4013. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  4014. CheckArgumentWithTypeTag(I, Args, Loc);
  4015. }
  4016. }
  4017. if (FD)
  4018. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  4019. }
  4020. /// CheckConstructorCall - Check a constructor call for correctness and safety
  4021. /// properties not enforced by the C type system.
  4022. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  4023. ArrayRef<const Expr *> Args,
  4024. const FunctionProtoType *Proto,
  4025. SourceLocation Loc) {
  4026. VariadicCallType CallType =
  4027. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  4028. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  4029. Loc, SourceRange(), CallType);
  4030. }
  4031. /// CheckFunctionCall - Check a direct function call for various correctness
  4032. /// and safety properties not strictly enforced by the C type system.
  4033. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  4034. const FunctionProtoType *Proto) {
  4035. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  4036. isa<CXXMethodDecl>(FDecl);
  4037. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  4038. IsMemberOperatorCall;
  4039. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  4040. TheCall->getCallee());
  4041. Expr** Args = TheCall->getArgs();
  4042. unsigned NumArgs = TheCall->getNumArgs();
  4043. Expr *ImplicitThis = nullptr;
  4044. if (IsMemberOperatorCall) {
  4045. // If this is a call to a member operator, hide the first argument
  4046. // from checkCall.
  4047. // FIXME: Our choice of AST representation here is less than ideal.
  4048. ImplicitThis = Args[0];
  4049. ++Args;
  4050. --NumArgs;
  4051. } else if (IsMemberFunction)
  4052. ImplicitThis =
  4053. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  4054. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  4055. IsMemberFunction, TheCall->getRParenLoc(),
  4056. TheCall->getCallee()->getSourceRange(), CallType);
  4057. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  4058. // None of the checks below are needed for functions that don't have
  4059. // simple names (e.g., C++ conversion functions).
  4060. if (!FnInfo)
  4061. return false;
  4062. CheckAbsoluteValueFunction(TheCall, FDecl);
  4063. CheckMaxUnsignedZero(TheCall, FDecl);
  4064. if (getLangOpts().ObjC)
  4065. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  4066. unsigned CMId = FDecl->getMemoryFunctionKind();
  4067. if (CMId == 0)
  4068. return false;
  4069. // Handle memory setting and copying functions.
  4070. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  4071. CheckStrlcpycatArguments(TheCall, FnInfo);
  4072. else if (CMId == Builtin::BIstrncat)
  4073. CheckStrncatArguments(TheCall, FnInfo);
  4074. else
  4075. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  4076. return false;
  4077. }
  4078. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  4079. ArrayRef<const Expr *> Args) {
  4080. VariadicCallType CallType =
  4081. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  4082. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  4083. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  4084. CallType);
  4085. return false;
  4086. }
  4087. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  4088. const FunctionProtoType *Proto) {
  4089. QualType Ty;
  4090. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  4091. Ty = V->getType().getNonReferenceType();
  4092. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  4093. Ty = F->getType().getNonReferenceType();
  4094. else
  4095. return false;
  4096. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  4097. !Ty->isFunctionProtoType())
  4098. return false;
  4099. VariadicCallType CallType;
  4100. if (!Proto || !Proto->isVariadic()) {
  4101. CallType = VariadicDoesNotApply;
  4102. } else if (Ty->isBlockPointerType()) {
  4103. CallType = VariadicBlock;
  4104. } else { // Ty->isFunctionPointerType()
  4105. CallType = VariadicFunction;
  4106. }
  4107. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  4108. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4109. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4110. TheCall->getCallee()->getSourceRange(), CallType);
  4111. return false;
  4112. }
  4113. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  4114. /// such as function pointers returned from functions.
  4115. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  4116. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  4117. TheCall->getCallee());
  4118. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  4119. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4120. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4121. TheCall->getCallee()->getSourceRange(), CallType);
  4122. return false;
  4123. }
  4124. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  4125. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  4126. return false;
  4127. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  4128. switch (Op) {
  4129. case AtomicExpr::AO__c11_atomic_init:
  4130. case AtomicExpr::AO__opencl_atomic_init:
  4131. llvm_unreachable("There is no ordering argument for an init");
  4132. case AtomicExpr::AO__c11_atomic_load:
  4133. case AtomicExpr::AO__opencl_atomic_load:
  4134. case AtomicExpr::AO__atomic_load_n:
  4135. case AtomicExpr::AO__atomic_load:
  4136. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  4137. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4138. case AtomicExpr::AO__c11_atomic_store:
  4139. case AtomicExpr::AO__opencl_atomic_store:
  4140. case AtomicExpr::AO__atomic_store:
  4141. case AtomicExpr::AO__atomic_store_n:
  4142. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  4143. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  4144. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4145. default:
  4146. return true;
  4147. }
  4148. }
  4149. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  4150. AtomicExpr::AtomicOp Op) {
  4151. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  4152. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4153. // All the non-OpenCL operations take one of the following forms.
  4154. // The OpenCL operations take the __c11 forms with one extra argument for
  4155. // synchronization scope.
  4156. enum {
  4157. // C __c11_atomic_init(A *, C)
  4158. Init,
  4159. // C __c11_atomic_load(A *, int)
  4160. Load,
  4161. // void __atomic_load(A *, CP, int)
  4162. LoadCopy,
  4163. // void __atomic_store(A *, CP, int)
  4164. Copy,
  4165. // C __c11_atomic_add(A *, M, int)
  4166. Arithmetic,
  4167. // C __atomic_exchange_n(A *, CP, int)
  4168. Xchg,
  4169. // void __atomic_exchange(A *, C *, CP, int)
  4170. GNUXchg,
  4171. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  4172. C11CmpXchg,
  4173. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  4174. GNUCmpXchg
  4175. } Form = Init;
  4176. const unsigned NumForm = GNUCmpXchg + 1;
  4177. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  4178. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  4179. // where:
  4180. // C is an appropriate type,
  4181. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  4182. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  4183. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  4184. // the int parameters are for orderings.
  4185. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  4186. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  4187. "need to update code for modified forms");
  4188. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  4189. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  4190. AtomicExpr::AO__atomic_load,
  4191. "need to update code for modified C11 atomics");
  4192. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  4193. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  4194. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  4195. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  4196. IsOpenCL;
  4197. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  4198. Op == AtomicExpr::AO__atomic_store_n ||
  4199. Op == AtomicExpr::AO__atomic_exchange_n ||
  4200. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  4201. bool IsAddSub = false;
  4202. bool IsMinMax = false;
  4203. switch (Op) {
  4204. case AtomicExpr::AO__c11_atomic_init:
  4205. case AtomicExpr::AO__opencl_atomic_init:
  4206. Form = Init;
  4207. break;
  4208. case AtomicExpr::AO__c11_atomic_load:
  4209. case AtomicExpr::AO__opencl_atomic_load:
  4210. case AtomicExpr::AO__atomic_load_n:
  4211. Form = Load;
  4212. break;
  4213. case AtomicExpr::AO__atomic_load:
  4214. Form = LoadCopy;
  4215. break;
  4216. case AtomicExpr::AO__c11_atomic_store:
  4217. case AtomicExpr::AO__opencl_atomic_store:
  4218. case AtomicExpr::AO__atomic_store:
  4219. case AtomicExpr::AO__atomic_store_n:
  4220. Form = Copy;
  4221. break;
  4222. case AtomicExpr::AO__c11_atomic_fetch_add:
  4223. case AtomicExpr::AO__c11_atomic_fetch_sub:
  4224. case AtomicExpr::AO__opencl_atomic_fetch_add:
  4225. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  4226. case AtomicExpr::AO__opencl_atomic_fetch_min:
  4227. case AtomicExpr::AO__opencl_atomic_fetch_max:
  4228. case AtomicExpr::AO__atomic_fetch_add:
  4229. case AtomicExpr::AO__atomic_fetch_sub:
  4230. case AtomicExpr::AO__atomic_add_fetch:
  4231. case AtomicExpr::AO__atomic_sub_fetch:
  4232. IsAddSub = true;
  4233. LLVM_FALLTHROUGH;
  4234. case AtomicExpr::AO__c11_atomic_fetch_and:
  4235. case AtomicExpr::AO__c11_atomic_fetch_or:
  4236. case AtomicExpr::AO__c11_atomic_fetch_xor:
  4237. case AtomicExpr::AO__opencl_atomic_fetch_and:
  4238. case AtomicExpr::AO__opencl_atomic_fetch_or:
  4239. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  4240. case AtomicExpr::AO__atomic_fetch_and:
  4241. case AtomicExpr::AO__atomic_fetch_or:
  4242. case AtomicExpr::AO__atomic_fetch_xor:
  4243. case AtomicExpr::AO__atomic_fetch_nand:
  4244. case AtomicExpr::AO__atomic_and_fetch:
  4245. case AtomicExpr::AO__atomic_or_fetch:
  4246. case AtomicExpr::AO__atomic_xor_fetch:
  4247. case AtomicExpr::AO__atomic_nand_fetch:
  4248. Form = Arithmetic;
  4249. break;
  4250. case AtomicExpr::AO__atomic_fetch_min:
  4251. case AtomicExpr::AO__atomic_fetch_max:
  4252. IsMinMax = true;
  4253. Form = Arithmetic;
  4254. break;
  4255. case AtomicExpr::AO__c11_atomic_exchange:
  4256. case AtomicExpr::AO__opencl_atomic_exchange:
  4257. case AtomicExpr::AO__atomic_exchange_n:
  4258. Form = Xchg;
  4259. break;
  4260. case AtomicExpr::AO__atomic_exchange:
  4261. Form = GNUXchg;
  4262. break;
  4263. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  4264. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  4265. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  4266. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  4267. Form = C11CmpXchg;
  4268. break;
  4269. case AtomicExpr::AO__atomic_compare_exchange:
  4270. case AtomicExpr::AO__atomic_compare_exchange_n:
  4271. Form = GNUCmpXchg;
  4272. break;
  4273. }
  4274. unsigned AdjustedNumArgs = NumArgs[Form];
  4275. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  4276. ++AdjustedNumArgs;
  4277. // Check we have the right number of arguments.
  4278. if (TheCall->getNumArgs() < AdjustedNumArgs) {
  4279. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  4280. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4281. << TheCall->getCallee()->getSourceRange();
  4282. return ExprError();
  4283. } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
  4284. Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
  4285. diag::err_typecheck_call_too_many_args)
  4286. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4287. << TheCall->getCallee()->getSourceRange();
  4288. return ExprError();
  4289. }
  4290. // Inspect the first argument of the atomic operation.
  4291. Expr *Ptr = TheCall->getArg(0);
  4292. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  4293. if (ConvertedPtr.isInvalid())
  4294. return ExprError();
  4295. Ptr = ConvertedPtr.get();
  4296. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  4297. if (!pointerType) {
  4298. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4299. << Ptr->getType() << Ptr->getSourceRange();
  4300. return ExprError();
  4301. }
  4302. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  4303. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  4304. QualType ValType = AtomTy; // 'C'
  4305. if (IsC11) {
  4306. if (!AtomTy->isAtomicType()) {
  4307. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
  4308. << Ptr->getType() << Ptr->getSourceRange();
  4309. return ExprError();
  4310. }
  4311. if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
  4312. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  4313. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
  4314. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  4315. << Ptr->getSourceRange();
  4316. return ExprError();
  4317. }
  4318. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  4319. } else if (Form != Load && Form != LoadCopy) {
  4320. if (ValType.isConstQualified()) {
  4321. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
  4322. << Ptr->getType() << Ptr->getSourceRange();
  4323. return ExprError();
  4324. }
  4325. }
  4326. // For an arithmetic operation, the implied arithmetic must be well-formed.
  4327. if (Form == Arithmetic) {
  4328. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  4329. if (IsAddSub && !ValType->isIntegerType()
  4330. && !ValType->isPointerType()) {
  4331. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4332. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4333. return ExprError();
  4334. }
  4335. if (IsMinMax) {
  4336. const BuiltinType *BT = ValType->getAs<BuiltinType>();
  4337. if (!BT || (BT->getKind() != BuiltinType::Int &&
  4338. BT->getKind() != BuiltinType::UInt)) {
  4339. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
  4340. return ExprError();
  4341. }
  4342. }
  4343. if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
  4344. Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
  4345. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4346. return ExprError();
  4347. }
  4348. if (IsC11 && ValType->isPointerType() &&
  4349. RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
  4350. diag::err_incomplete_type)) {
  4351. return ExprError();
  4352. }
  4353. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  4354. // For __atomic_*_n operations, the value type must be a scalar integral or
  4355. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  4356. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4357. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4358. return ExprError();
  4359. }
  4360. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  4361. !AtomTy->isScalarType()) {
  4362. // For GNU atomics, require a trivially-copyable type. This is not part of
  4363. // the GNU atomics specification, but we enforce it for sanity.
  4364. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
  4365. << Ptr->getType() << Ptr->getSourceRange();
  4366. return ExprError();
  4367. }
  4368. switch (ValType.getObjCLifetime()) {
  4369. case Qualifiers::OCL_None:
  4370. case Qualifiers::OCL_ExplicitNone:
  4371. // okay
  4372. break;
  4373. case Qualifiers::OCL_Weak:
  4374. case Qualifiers::OCL_Strong:
  4375. case Qualifiers::OCL_Autoreleasing:
  4376. // FIXME: Can this happen? By this point, ValType should be known
  4377. // to be trivially copyable.
  4378. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4379. << ValType << Ptr->getSourceRange();
  4380. return ExprError();
  4381. }
  4382. // All atomic operations have an overload which takes a pointer to a volatile
  4383. // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
  4384. // into the result or the other operands. Similarly atomic_load takes a
  4385. // pointer to a const 'A'.
  4386. ValType.removeLocalVolatile();
  4387. ValType.removeLocalConst();
  4388. QualType ResultType = ValType;
  4389. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  4390. Form == Init)
  4391. ResultType = Context.VoidTy;
  4392. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  4393. ResultType = Context.BoolTy;
  4394. // The type of a parameter passed 'by value'. In the GNU atomics, such
  4395. // arguments are actually passed as pointers.
  4396. QualType ByValType = ValType; // 'CP'
  4397. bool IsPassedByAddress = false;
  4398. if (!IsC11 && !IsN) {
  4399. ByValType = Ptr->getType();
  4400. IsPassedByAddress = true;
  4401. }
  4402. // The first argument's non-CV pointer type is used to deduce the type of
  4403. // subsequent arguments, except for:
  4404. // - weak flag (always converted to bool)
  4405. // - memory order (always converted to int)
  4406. // - scope (always converted to int)
  4407. for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
  4408. QualType Ty;
  4409. if (i < NumVals[Form] + 1) {
  4410. switch (i) {
  4411. case 0:
  4412. // The first argument is always a pointer. It has a fixed type.
  4413. // It is always dereferenced, a nullptr is undefined.
  4414. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4415. // Nothing else to do: we already know all we want about this pointer.
  4416. continue;
  4417. case 1:
  4418. // The second argument is the non-atomic operand. For arithmetic, this
  4419. // is always passed by value, and for a compare_exchange it is always
  4420. // passed by address. For the rest, GNU uses by-address and C11 uses
  4421. // by-value.
  4422. assert(Form != Load);
  4423. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  4424. Ty = ValType;
  4425. else if (Form == Copy || Form == Xchg) {
  4426. if (IsPassedByAddress)
  4427. // The value pointer is always dereferenced, a nullptr is undefined.
  4428. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4429. Ty = ByValType;
  4430. } else if (Form == Arithmetic)
  4431. Ty = Context.getPointerDiffType();
  4432. else {
  4433. Expr *ValArg = TheCall->getArg(i);
  4434. // The value pointer is always dereferenced, a nullptr is undefined.
  4435. CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
  4436. LangAS AS = LangAS::Default;
  4437. // Keep address space of non-atomic pointer type.
  4438. if (const PointerType *PtrTy =
  4439. ValArg->getType()->getAs<PointerType>()) {
  4440. AS = PtrTy->getPointeeType().getAddressSpace();
  4441. }
  4442. Ty = Context.getPointerType(
  4443. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  4444. }
  4445. break;
  4446. case 2:
  4447. // The third argument to compare_exchange / GNU exchange is the desired
  4448. // value, either by-value (for the C11 and *_n variant) or as a pointer.
  4449. if (IsPassedByAddress)
  4450. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4451. Ty = ByValType;
  4452. break;
  4453. case 3:
  4454. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  4455. Ty = Context.BoolTy;
  4456. break;
  4457. }
  4458. } else {
  4459. // The order(s) and scope are always converted to int.
  4460. Ty = Context.IntTy;
  4461. }
  4462. InitializedEntity Entity =
  4463. InitializedEntity::InitializeParameter(Context, Ty, false);
  4464. ExprResult Arg = TheCall->getArg(i);
  4465. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4466. if (Arg.isInvalid())
  4467. return true;
  4468. TheCall->setArg(i, Arg.get());
  4469. }
  4470. // Permute the arguments into a 'consistent' order.
  4471. SmallVector<Expr*, 5> SubExprs;
  4472. SubExprs.push_back(Ptr);
  4473. switch (Form) {
  4474. case Init:
  4475. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  4476. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4477. break;
  4478. case Load:
  4479. SubExprs.push_back(TheCall->getArg(1)); // Order
  4480. break;
  4481. case LoadCopy:
  4482. case Copy:
  4483. case Arithmetic:
  4484. case Xchg:
  4485. SubExprs.push_back(TheCall->getArg(2)); // Order
  4486. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4487. break;
  4488. case GNUXchg:
  4489. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  4490. SubExprs.push_back(TheCall->getArg(3)); // Order
  4491. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4492. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4493. break;
  4494. case C11CmpXchg:
  4495. SubExprs.push_back(TheCall->getArg(3)); // Order
  4496. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4497. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  4498. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4499. break;
  4500. case GNUCmpXchg:
  4501. SubExprs.push_back(TheCall->getArg(4)); // Order
  4502. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4503. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  4504. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4505. SubExprs.push_back(TheCall->getArg(3)); // Weak
  4506. break;
  4507. }
  4508. if (SubExprs.size() >= 2 && Form != Init) {
  4509. llvm::APSInt Result(32);
  4510. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  4511. !isValidOrderingForOp(Result.getSExtValue(), Op))
  4512. Diag(SubExprs[1]->getBeginLoc(),
  4513. diag::warn_atomic_op_has_invalid_memory_order)
  4514. << SubExprs[1]->getSourceRange();
  4515. }
  4516. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  4517. auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
  4518. llvm::APSInt Result(32);
  4519. if (Scope->isIntegerConstantExpr(Result, Context) &&
  4520. !ScopeModel->isValid(Result.getZExtValue())) {
  4521. Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
  4522. << Scope->getSourceRange();
  4523. }
  4524. SubExprs.push_back(Scope);
  4525. }
  4526. AtomicExpr *AE =
  4527. new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
  4528. ResultType, Op, TheCall->getRParenLoc());
  4529. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  4530. Op == AtomicExpr::AO__c11_atomic_store ||
  4531. Op == AtomicExpr::AO__opencl_atomic_load ||
  4532. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  4533. Context.AtomicUsesUnsupportedLibcall(AE))
  4534. Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
  4535. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  4536. Op == AtomicExpr::AO__opencl_atomic_load)
  4537. ? 0
  4538. : 1);
  4539. return AE;
  4540. }
  4541. /// checkBuiltinArgument - Given a call to a builtin function, perform
  4542. /// normal type-checking on the given argument, updating the call in
  4543. /// place. This is useful when a builtin function requires custom
  4544. /// type-checking for some of its arguments but not necessarily all of
  4545. /// them.
  4546. ///
  4547. /// Returns true on error.
  4548. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  4549. FunctionDecl *Fn = E->getDirectCallee();
  4550. assert(Fn && "builtin call without direct callee!");
  4551. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  4552. InitializedEntity Entity =
  4553. InitializedEntity::InitializeParameter(S.Context, Param);
  4554. ExprResult Arg = E->getArg(0);
  4555. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4556. if (Arg.isInvalid())
  4557. return true;
  4558. E->setArg(ArgIndex, Arg.get());
  4559. return false;
  4560. }
  4561. /// We have a call to a function like __sync_fetch_and_add, which is an
  4562. /// overloaded function based on the pointer type of its first argument.
  4563. /// The main BuildCallExpr routines have already promoted the types of
  4564. /// arguments because all of these calls are prototyped as void(...).
  4565. ///
  4566. /// This function goes through and does final semantic checking for these
  4567. /// builtins, as well as generating any warnings.
  4568. ExprResult
  4569. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  4570. CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
  4571. Expr *Callee = TheCall->getCallee();
  4572. DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
  4573. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4574. // Ensure that we have at least one argument to do type inference from.
  4575. if (TheCall->getNumArgs() < 1) {
  4576. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4577. << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
  4578. return ExprError();
  4579. }
  4580. // Inspect the first argument of the atomic builtin. This should always be
  4581. // a pointer type, whose element is an integral scalar or pointer type.
  4582. // Because it is a pointer type, we don't have to worry about any implicit
  4583. // casts here.
  4584. // FIXME: We don't allow floating point scalars as input.
  4585. Expr *FirstArg = TheCall->getArg(0);
  4586. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  4587. if (FirstArgResult.isInvalid())
  4588. return ExprError();
  4589. FirstArg = FirstArgResult.get();
  4590. TheCall->setArg(0, FirstArg);
  4591. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  4592. if (!pointerType) {
  4593. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4594. << FirstArg->getType() << FirstArg->getSourceRange();
  4595. return ExprError();
  4596. }
  4597. QualType ValType = pointerType->getPointeeType();
  4598. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4599. !ValType->isBlockPointerType()) {
  4600. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
  4601. << FirstArg->getType() << FirstArg->getSourceRange();
  4602. return ExprError();
  4603. }
  4604. if (ValType.isConstQualified()) {
  4605. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
  4606. << FirstArg->getType() << FirstArg->getSourceRange();
  4607. return ExprError();
  4608. }
  4609. switch (ValType.getObjCLifetime()) {
  4610. case Qualifiers::OCL_None:
  4611. case Qualifiers::OCL_ExplicitNone:
  4612. // okay
  4613. break;
  4614. case Qualifiers::OCL_Weak:
  4615. case Qualifiers::OCL_Strong:
  4616. case Qualifiers::OCL_Autoreleasing:
  4617. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4618. << ValType << FirstArg->getSourceRange();
  4619. return ExprError();
  4620. }
  4621. // Strip any qualifiers off ValType.
  4622. ValType = ValType.getUnqualifiedType();
  4623. // The majority of builtins return a value, but a few have special return
  4624. // types, so allow them to override appropriately below.
  4625. QualType ResultType = ValType;
  4626. // We need to figure out which concrete builtin this maps onto. For example,
  4627. // __sync_fetch_and_add with a 2 byte object turns into
  4628. // __sync_fetch_and_add_2.
  4629. #define BUILTIN_ROW(x) \
  4630. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  4631. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  4632. static const unsigned BuiltinIndices[][5] = {
  4633. BUILTIN_ROW(__sync_fetch_and_add),
  4634. BUILTIN_ROW(__sync_fetch_and_sub),
  4635. BUILTIN_ROW(__sync_fetch_and_or),
  4636. BUILTIN_ROW(__sync_fetch_and_and),
  4637. BUILTIN_ROW(__sync_fetch_and_xor),
  4638. BUILTIN_ROW(__sync_fetch_and_nand),
  4639. BUILTIN_ROW(__sync_add_and_fetch),
  4640. BUILTIN_ROW(__sync_sub_and_fetch),
  4641. BUILTIN_ROW(__sync_and_and_fetch),
  4642. BUILTIN_ROW(__sync_or_and_fetch),
  4643. BUILTIN_ROW(__sync_xor_and_fetch),
  4644. BUILTIN_ROW(__sync_nand_and_fetch),
  4645. BUILTIN_ROW(__sync_val_compare_and_swap),
  4646. BUILTIN_ROW(__sync_bool_compare_and_swap),
  4647. BUILTIN_ROW(__sync_lock_test_and_set),
  4648. BUILTIN_ROW(__sync_lock_release),
  4649. BUILTIN_ROW(__sync_swap)
  4650. };
  4651. #undef BUILTIN_ROW
  4652. // Determine the index of the size.
  4653. unsigned SizeIndex;
  4654. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  4655. case 1: SizeIndex = 0; break;
  4656. case 2: SizeIndex = 1; break;
  4657. case 4: SizeIndex = 2; break;
  4658. case 8: SizeIndex = 3; break;
  4659. case 16: SizeIndex = 4; break;
  4660. default:
  4661. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
  4662. << FirstArg->getType() << FirstArg->getSourceRange();
  4663. return ExprError();
  4664. }
  4665. // Each of these builtins has one pointer argument, followed by some number of
  4666. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  4667. // that we ignore. Find out which row of BuiltinIndices to read from as well
  4668. // as the number of fixed args.
  4669. unsigned BuiltinID = FDecl->getBuiltinID();
  4670. unsigned BuiltinIndex, NumFixed = 1;
  4671. bool WarnAboutSemanticsChange = false;
  4672. switch (BuiltinID) {
  4673. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  4674. case Builtin::BI__sync_fetch_and_add:
  4675. case Builtin::BI__sync_fetch_and_add_1:
  4676. case Builtin::BI__sync_fetch_and_add_2:
  4677. case Builtin::BI__sync_fetch_and_add_4:
  4678. case Builtin::BI__sync_fetch_and_add_8:
  4679. case Builtin::BI__sync_fetch_and_add_16:
  4680. BuiltinIndex = 0;
  4681. break;
  4682. case Builtin::BI__sync_fetch_and_sub:
  4683. case Builtin::BI__sync_fetch_and_sub_1:
  4684. case Builtin::BI__sync_fetch_and_sub_2:
  4685. case Builtin::BI__sync_fetch_and_sub_4:
  4686. case Builtin::BI__sync_fetch_and_sub_8:
  4687. case Builtin::BI__sync_fetch_and_sub_16:
  4688. BuiltinIndex = 1;
  4689. break;
  4690. case Builtin::BI__sync_fetch_and_or:
  4691. case Builtin::BI__sync_fetch_and_or_1:
  4692. case Builtin::BI__sync_fetch_and_or_2:
  4693. case Builtin::BI__sync_fetch_and_or_4:
  4694. case Builtin::BI__sync_fetch_and_or_8:
  4695. case Builtin::BI__sync_fetch_and_or_16:
  4696. BuiltinIndex = 2;
  4697. break;
  4698. case Builtin::BI__sync_fetch_and_and:
  4699. case Builtin::BI__sync_fetch_and_and_1:
  4700. case Builtin::BI__sync_fetch_and_and_2:
  4701. case Builtin::BI__sync_fetch_and_and_4:
  4702. case Builtin::BI__sync_fetch_and_and_8:
  4703. case Builtin::BI__sync_fetch_and_and_16:
  4704. BuiltinIndex = 3;
  4705. break;
  4706. case Builtin::BI__sync_fetch_and_xor:
  4707. case Builtin::BI__sync_fetch_and_xor_1:
  4708. case Builtin::BI__sync_fetch_and_xor_2:
  4709. case Builtin::BI__sync_fetch_and_xor_4:
  4710. case Builtin::BI__sync_fetch_and_xor_8:
  4711. case Builtin::BI__sync_fetch_and_xor_16:
  4712. BuiltinIndex = 4;
  4713. break;
  4714. case Builtin::BI__sync_fetch_and_nand:
  4715. case Builtin::BI__sync_fetch_and_nand_1:
  4716. case Builtin::BI__sync_fetch_and_nand_2:
  4717. case Builtin::BI__sync_fetch_and_nand_4:
  4718. case Builtin::BI__sync_fetch_and_nand_8:
  4719. case Builtin::BI__sync_fetch_and_nand_16:
  4720. BuiltinIndex = 5;
  4721. WarnAboutSemanticsChange = true;
  4722. break;
  4723. case Builtin::BI__sync_add_and_fetch:
  4724. case Builtin::BI__sync_add_and_fetch_1:
  4725. case Builtin::BI__sync_add_and_fetch_2:
  4726. case Builtin::BI__sync_add_and_fetch_4:
  4727. case Builtin::BI__sync_add_and_fetch_8:
  4728. case Builtin::BI__sync_add_and_fetch_16:
  4729. BuiltinIndex = 6;
  4730. break;
  4731. case Builtin::BI__sync_sub_and_fetch:
  4732. case Builtin::BI__sync_sub_and_fetch_1:
  4733. case Builtin::BI__sync_sub_and_fetch_2:
  4734. case Builtin::BI__sync_sub_and_fetch_4:
  4735. case Builtin::BI__sync_sub_and_fetch_8:
  4736. case Builtin::BI__sync_sub_and_fetch_16:
  4737. BuiltinIndex = 7;
  4738. break;
  4739. case Builtin::BI__sync_and_and_fetch:
  4740. case Builtin::BI__sync_and_and_fetch_1:
  4741. case Builtin::BI__sync_and_and_fetch_2:
  4742. case Builtin::BI__sync_and_and_fetch_4:
  4743. case Builtin::BI__sync_and_and_fetch_8:
  4744. case Builtin::BI__sync_and_and_fetch_16:
  4745. BuiltinIndex = 8;
  4746. break;
  4747. case Builtin::BI__sync_or_and_fetch:
  4748. case Builtin::BI__sync_or_and_fetch_1:
  4749. case Builtin::BI__sync_or_and_fetch_2:
  4750. case Builtin::BI__sync_or_and_fetch_4:
  4751. case Builtin::BI__sync_or_and_fetch_8:
  4752. case Builtin::BI__sync_or_and_fetch_16:
  4753. BuiltinIndex = 9;
  4754. break;
  4755. case Builtin::BI__sync_xor_and_fetch:
  4756. case Builtin::BI__sync_xor_and_fetch_1:
  4757. case Builtin::BI__sync_xor_and_fetch_2:
  4758. case Builtin::BI__sync_xor_and_fetch_4:
  4759. case Builtin::BI__sync_xor_and_fetch_8:
  4760. case Builtin::BI__sync_xor_and_fetch_16:
  4761. BuiltinIndex = 10;
  4762. break;
  4763. case Builtin::BI__sync_nand_and_fetch:
  4764. case Builtin::BI__sync_nand_and_fetch_1:
  4765. case Builtin::BI__sync_nand_and_fetch_2:
  4766. case Builtin::BI__sync_nand_and_fetch_4:
  4767. case Builtin::BI__sync_nand_and_fetch_8:
  4768. case Builtin::BI__sync_nand_and_fetch_16:
  4769. BuiltinIndex = 11;
  4770. WarnAboutSemanticsChange = true;
  4771. break;
  4772. case Builtin::BI__sync_val_compare_and_swap:
  4773. case Builtin::BI__sync_val_compare_and_swap_1:
  4774. case Builtin::BI__sync_val_compare_and_swap_2:
  4775. case Builtin::BI__sync_val_compare_and_swap_4:
  4776. case Builtin::BI__sync_val_compare_and_swap_8:
  4777. case Builtin::BI__sync_val_compare_and_swap_16:
  4778. BuiltinIndex = 12;
  4779. NumFixed = 2;
  4780. break;
  4781. case Builtin::BI__sync_bool_compare_and_swap:
  4782. case Builtin::BI__sync_bool_compare_and_swap_1:
  4783. case Builtin::BI__sync_bool_compare_and_swap_2:
  4784. case Builtin::BI__sync_bool_compare_and_swap_4:
  4785. case Builtin::BI__sync_bool_compare_and_swap_8:
  4786. case Builtin::BI__sync_bool_compare_and_swap_16:
  4787. BuiltinIndex = 13;
  4788. NumFixed = 2;
  4789. ResultType = Context.BoolTy;
  4790. break;
  4791. case Builtin::BI__sync_lock_test_and_set:
  4792. case Builtin::BI__sync_lock_test_and_set_1:
  4793. case Builtin::BI__sync_lock_test_and_set_2:
  4794. case Builtin::BI__sync_lock_test_and_set_4:
  4795. case Builtin::BI__sync_lock_test_and_set_8:
  4796. case Builtin::BI__sync_lock_test_and_set_16:
  4797. BuiltinIndex = 14;
  4798. break;
  4799. case Builtin::BI__sync_lock_release:
  4800. case Builtin::BI__sync_lock_release_1:
  4801. case Builtin::BI__sync_lock_release_2:
  4802. case Builtin::BI__sync_lock_release_4:
  4803. case Builtin::BI__sync_lock_release_8:
  4804. case Builtin::BI__sync_lock_release_16:
  4805. BuiltinIndex = 15;
  4806. NumFixed = 0;
  4807. ResultType = Context.VoidTy;
  4808. break;
  4809. case Builtin::BI__sync_swap:
  4810. case Builtin::BI__sync_swap_1:
  4811. case Builtin::BI__sync_swap_2:
  4812. case Builtin::BI__sync_swap_4:
  4813. case Builtin::BI__sync_swap_8:
  4814. case Builtin::BI__sync_swap_16:
  4815. BuiltinIndex = 16;
  4816. break;
  4817. }
  4818. // Now that we know how many fixed arguments we expect, first check that we
  4819. // have at least that many.
  4820. if (TheCall->getNumArgs() < 1+NumFixed) {
  4821. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4822. << 0 << 1 + NumFixed << TheCall->getNumArgs()
  4823. << Callee->getSourceRange();
  4824. return ExprError();
  4825. }
  4826. Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
  4827. << Callee->getSourceRange();
  4828. if (WarnAboutSemanticsChange) {
  4829. Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
  4830. << Callee->getSourceRange();
  4831. }
  4832. // Get the decl for the concrete builtin from this, we can tell what the
  4833. // concrete integer type we should convert to is.
  4834. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  4835. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  4836. FunctionDecl *NewBuiltinDecl;
  4837. if (NewBuiltinID == BuiltinID)
  4838. NewBuiltinDecl = FDecl;
  4839. else {
  4840. // Perform builtin lookup to avoid redeclaring it.
  4841. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  4842. LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
  4843. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  4844. assert(Res.getFoundDecl());
  4845. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  4846. if (!NewBuiltinDecl)
  4847. return ExprError();
  4848. }
  4849. // The first argument --- the pointer --- has a fixed type; we
  4850. // deduce the types of the rest of the arguments accordingly. Walk
  4851. // the remaining arguments, converting them to the deduced value type.
  4852. for (unsigned i = 0; i != NumFixed; ++i) {
  4853. ExprResult Arg = TheCall->getArg(i+1);
  4854. // GCC does an implicit conversion to the pointer or integer ValType. This
  4855. // can fail in some cases (1i -> int**), check for this error case now.
  4856. // Initialize the argument.
  4857. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  4858. ValType, /*consume*/ false);
  4859. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4860. if (Arg.isInvalid())
  4861. return ExprError();
  4862. // Okay, we have something that *can* be converted to the right type. Check
  4863. // to see if there is a potentially weird extension going on here. This can
  4864. // happen when you do an atomic operation on something like an char* and
  4865. // pass in 42. The 42 gets converted to char. This is even more strange
  4866. // for things like 45.123 -> char, etc.
  4867. // FIXME: Do this check.
  4868. TheCall->setArg(i+1, Arg.get());
  4869. }
  4870. // Create a new DeclRefExpr to refer to the new decl.
  4871. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  4872. Context,
  4873. DRE->getQualifierLoc(),
  4874. SourceLocation(),
  4875. NewBuiltinDecl,
  4876. /*enclosing*/ false,
  4877. DRE->getLocation(),
  4878. Context.BuiltinFnTy,
  4879. DRE->getValueKind());
  4880. // Set the callee in the CallExpr.
  4881. // FIXME: This loses syntactic information.
  4882. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  4883. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  4884. CK_BuiltinFnToFnPtr);
  4885. TheCall->setCallee(PromotedCall.get());
  4886. // Change the result type of the call to match the original value type. This
  4887. // is arbitrary, but the codegen for these builtins ins design to handle it
  4888. // gracefully.
  4889. TheCall->setType(ResultType);
  4890. return TheCallResult;
  4891. }
  4892. /// SemaBuiltinNontemporalOverloaded - We have a call to
  4893. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  4894. /// overloaded function based on the pointer type of its last argument.
  4895. ///
  4896. /// This function goes through and does final semantic checking for these
  4897. /// builtins.
  4898. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  4899. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  4900. DeclRefExpr *DRE =
  4901. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4902. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4903. unsigned BuiltinID = FDecl->getBuiltinID();
  4904. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  4905. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  4906. "Unexpected nontemporal load/store builtin!");
  4907. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  4908. unsigned numArgs = isStore ? 2 : 1;
  4909. // Ensure that we have the proper number of arguments.
  4910. if (checkArgCount(*this, TheCall, numArgs))
  4911. return ExprError();
  4912. // Inspect the last argument of the nontemporal builtin. This should always
  4913. // be a pointer type, from which we imply the type of the memory access.
  4914. // Because it is a pointer type, we don't have to worry about any implicit
  4915. // casts here.
  4916. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  4917. ExprResult PointerArgResult =
  4918. DefaultFunctionArrayLvalueConversion(PointerArg);
  4919. if (PointerArgResult.isInvalid())
  4920. return ExprError();
  4921. PointerArg = PointerArgResult.get();
  4922. TheCall->setArg(numArgs - 1, PointerArg);
  4923. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  4924. if (!pointerType) {
  4925. Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
  4926. << PointerArg->getType() << PointerArg->getSourceRange();
  4927. return ExprError();
  4928. }
  4929. QualType ValType = pointerType->getPointeeType();
  4930. // Strip any qualifiers off ValType.
  4931. ValType = ValType.getUnqualifiedType();
  4932. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4933. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  4934. !ValType->isVectorType()) {
  4935. Diag(DRE->getBeginLoc(),
  4936. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  4937. << PointerArg->getType() << PointerArg->getSourceRange();
  4938. return ExprError();
  4939. }
  4940. if (!isStore) {
  4941. TheCall->setType(ValType);
  4942. return TheCallResult;
  4943. }
  4944. ExprResult ValArg = TheCall->getArg(0);
  4945. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4946. Context, ValType, /*consume*/ false);
  4947. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  4948. if (ValArg.isInvalid())
  4949. return ExprError();
  4950. TheCall->setArg(0, ValArg.get());
  4951. TheCall->setType(Context.VoidTy);
  4952. return TheCallResult;
  4953. }
  4954. /// CheckObjCString - Checks that the argument to the builtin
  4955. /// CFString constructor is correct
  4956. /// Note: It might also make sense to do the UTF-16 conversion here (would
  4957. /// simplify the backend).
  4958. bool Sema::CheckObjCString(Expr *Arg) {
  4959. Arg = Arg->IgnoreParenCasts();
  4960. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  4961. if (!Literal || !Literal->isAscii()) {
  4962. Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
  4963. << Arg->getSourceRange();
  4964. return true;
  4965. }
  4966. if (Literal->containsNonAsciiOrNull()) {
  4967. StringRef String = Literal->getString();
  4968. unsigned NumBytes = String.size();
  4969. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  4970. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  4971. llvm::UTF16 *ToPtr = &ToBuf[0];
  4972. llvm::ConversionResult Result =
  4973. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  4974. ToPtr + NumBytes, llvm::strictConversion);
  4975. // Check for conversion failure.
  4976. if (Result != llvm::conversionOK)
  4977. Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
  4978. << Arg->getSourceRange();
  4979. }
  4980. return false;
  4981. }
  4982. /// CheckObjCString - Checks that the format string argument to the os_log()
  4983. /// and os_trace() functions is correct, and converts it to const char *.
  4984. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  4985. Arg = Arg->IgnoreParenCasts();
  4986. auto *Literal = dyn_cast<StringLiteral>(Arg);
  4987. if (!Literal) {
  4988. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  4989. Literal = ObjcLiteral->getString();
  4990. }
  4991. }
  4992. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  4993. return ExprError(
  4994. Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
  4995. << Arg->getSourceRange());
  4996. }
  4997. ExprResult Result(Literal);
  4998. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  4999. InitializedEntity Entity =
  5000. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  5001. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  5002. return Result;
  5003. }
  5004. /// Check that the user is calling the appropriate va_start builtin for the
  5005. /// target and calling convention.
  5006. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  5007. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  5008. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  5009. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  5010. bool IsWindows = TT.isOSWindows();
  5011. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  5012. if (IsX64 || IsAArch64) {
  5013. CallingConv CC = CC_C;
  5014. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  5015. CC = FD->getType()->getAs<FunctionType>()->getCallConv();
  5016. if (IsMSVAStart) {
  5017. // Don't allow this in System V ABI functions.
  5018. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  5019. return S.Diag(Fn->getBeginLoc(),
  5020. diag::err_ms_va_start_used_in_sysv_function);
  5021. } else {
  5022. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  5023. // On x64 Windows, don't allow this in System V ABI functions.
  5024. // (Yes, that means there's no corresponding way to support variadic
  5025. // System V ABI functions on Windows.)
  5026. if ((IsWindows && CC == CC_X86_64SysV) ||
  5027. (!IsWindows && CC == CC_Win64))
  5028. return S.Diag(Fn->getBeginLoc(),
  5029. diag::err_va_start_used_in_wrong_abi_function)
  5030. << !IsWindows;
  5031. }
  5032. return false;
  5033. }
  5034. if (IsMSVAStart)
  5035. return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
  5036. return false;
  5037. }
  5038. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  5039. ParmVarDecl **LastParam = nullptr) {
  5040. // Determine whether the current function, block, or obj-c method is variadic
  5041. // and get its parameter list.
  5042. bool IsVariadic = false;
  5043. ArrayRef<ParmVarDecl *> Params;
  5044. DeclContext *Caller = S.CurContext;
  5045. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  5046. IsVariadic = Block->isVariadic();
  5047. Params = Block->parameters();
  5048. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  5049. IsVariadic = FD->isVariadic();
  5050. Params = FD->parameters();
  5051. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  5052. IsVariadic = MD->isVariadic();
  5053. // FIXME: This isn't correct for methods (results in bogus warning).
  5054. Params = MD->parameters();
  5055. } else if (isa<CapturedDecl>(Caller)) {
  5056. // We don't support va_start in a CapturedDecl.
  5057. S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
  5058. return true;
  5059. } else {
  5060. // This must be some other declcontext that parses exprs.
  5061. S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
  5062. return true;
  5063. }
  5064. if (!IsVariadic) {
  5065. S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
  5066. return true;
  5067. }
  5068. if (LastParam)
  5069. *LastParam = Params.empty() ? nullptr : Params.back();
  5070. return false;
  5071. }
  5072. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  5073. /// for validity. Emit an error and return true on failure; return false
  5074. /// on success.
  5075. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  5076. Expr *Fn = TheCall->getCallee();
  5077. if (checkVAStartABI(*this, BuiltinID, Fn))
  5078. return true;
  5079. if (TheCall->getNumArgs() > 2) {
  5080. Diag(TheCall->getArg(2)->getBeginLoc(),
  5081. diag::err_typecheck_call_too_many_args)
  5082. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5083. << Fn->getSourceRange()
  5084. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5085. (*(TheCall->arg_end() - 1))->getEndLoc());
  5086. return true;
  5087. }
  5088. if (TheCall->getNumArgs() < 2) {
  5089. return Diag(TheCall->getEndLoc(),
  5090. diag::err_typecheck_call_too_few_args_at_least)
  5091. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  5092. }
  5093. // Type-check the first argument normally.
  5094. if (checkBuiltinArgument(*this, TheCall, 0))
  5095. return true;
  5096. // Check that the current function is variadic, and get its last parameter.
  5097. ParmVarDecl *LastParam;
  5098. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  5099. return true;
  5100. // Verify that the second argument to the builtin is the last argument of the
  5101. // current function or method.
  5102. bool SecondArgIsLastNamedArgument = false;
  5103. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  5104. // These are valid if SecondArgIsLastNamedArgument is false after the next
  5105. // block.
  5106. QualType Type;
  5107. SourceLocation ParamLoc;
  5108. bool IsCRegister = false;
  5109. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  5110. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  5111. SecondArgIsLastNamedArgument = PV == LastParam;
  5112. Type = PV->getType();
  5113. ParamLoc = PV->getLocation();
  5114. IsCRegister =
  5115. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  5116. }
  5117. }
  5118. if (!SecondArgIsLastNamedArgument)
  5119. Diag(TheCall->getArg(1)->getBeginLoc(),
  5120. diag::warn_second_arg_of_va_start_not_last_named_param);
  5121. else if (IsCRegister || Type->isReferenceType() ||
  5122. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  5123. // Promotable integers are UB, but enumerations need a bit of
  5124. // extra checking to see what their promotable type actually is.
  5125. if (!Type->isPromotableIntegerType())
  5126. return false;
  5127. if (!Type->isEnumeralType())
  5128. return true;
  5129. const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
  5130. return !(ED &&
  5131. Context.typesAreCompatible(ED->getPromotionType(), Type));
  5132. }()) {
  5133. unsigned Reason = 0;
  5134. if (Type->isReferenceType()) Reason = 1;
  5135. else if (IsCRegister) Reason = 2;
  5136. Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
  5137. Diag(ParamLoc, diag::note_parameter_type) << Type;
  5138. }
  5139. TheCall->setType(Context.VoidTy);
  5140. return false;
  5141. }
  5142. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  5143. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  5144. // const char *named_addr);
  5145. Expr *Func = Call->getCallee();
  5146. if (Call->getNumArgs() < 3)
  5147. return Diag(Call->getEndLoc(),
  5148. diag::err_typecheck_call_too_few_args_at_least)
  5149. << 0 /*function call*/ << 3 << Call->getNumArgs();
  5150. // Type-check the first argument normally.
  5151. if (checkBuiltinArgument(*this, Call, 0))
  5152. return true;
  5153. // Check that the current function is variadic.
  5154. if (checkVAStartIsInVariadicFunction(*this, Func))
  5155. return true;
  5156. // __va_start on Windows does not validate the parameter qualifiers
  5157. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  5158. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  5159. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  5160. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  5161. const QualType &ConstCharPtrTy =
  5162. Context.getPointerType(Context.CharTy.withConst());
  5163. if (!Arg1Ty->isPointerType() ||
  5164. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  5165. Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5166. << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
  5167. << 0 /* qualifier difference */
  5168. << 3 /* parameter mismatch */
  5169. << 2 << Arg1->getType() << ConstCharPtrTy;
  5170. const QualType SizeTy = Context.getSizeType();
  5171. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  5172. Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5173. << Arg2->getType() << SizeTy << 1 /* different class */
  5174. << 0 /* qualifier difference */
  5175. << 3 /* parameter mismatch */
  5176. << 3 << Arg2->getType() << SizeTy;
  5177. return false;
  5178. }
  5179. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  5180. /// friends. This is declared to take (...), so we have to check everything.
  5181. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  5182. if (TheCall->getNumArgs() < 2)
  5183. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5184. << 0 << 2 << TheCall->getNumArgs() /*function call*/;
  5185. if (TheCall->getNumArgs() > 2)
  5186. return Diag(TheCall->getArg(2)->getBeginLoc(),
  5187. diag::err_typecheck_call_too_many_args)
  5188. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5189. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5190. (*(TheCall->arg_end() - 1))->getEndLoc());
  5191. ExprResult OrigArg0 = TheCall->getArg(0);
  5192. ExprResult OrigArg1 = TheCall->getArg(1);
  5193. // Do standard promotions between the two arguments, returning their common
  5194. // type.
  5195. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  5196. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  5197. return true;
  5198. // Make sure any conversions are pushed back into the call; this is
  5199. // type safe since unordered compare builtins are declared as "_Bool
  5200. // foo(...)".
  5201. TheCall->setArg(0, OrigArg0.get());
  5202. TheCall->setArg(1, OrigArg1.get());
  5203. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  5204. return false;
  5205. // If the common type isn't a real floating type, then the arguments were
  5206. // invalid for this operation.
  5207. if (Res.isNull() || !Res->isRealFloatingType())
  5208. return Diag(OrigArg0.get()->getBeginLoc(),
  5209. diag::err_typecheck_call_invalid_ordered_compare)
  5210. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  5211. << SourceRange(OrigArg0.get()->getBeginLoc(),
  5212. OrigArg1.get()->getEndLoc());
  5213. return false;
  5214. }
  5215. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  5216. /// __builtin_isnan and friends. This is declared to take (...), so we have
  5217. /// to check everything. We expect the last argument to be a floating point
  5218. /// value.
  5219. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  5220. if (TheCall->getNumArgs() < NumArgs)
  5221. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5222. << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
  5223. if (TheCall->getNumArgs() > NumArgs)
  5224. return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
  5225. diag::err_typecheck_call_too_many_args)
  5226. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  5227. << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
  5228. (*(TheCall->arg_end() - 1))->getEndLoc());
  5229. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  5230. if (OrigArg->isTypeDependent())
  5231. return false;
  5232. // This operation requires a non-_Complex floating-point number.
  5233. if (!OrigArg->getType()->isRealFloatingType())
  5234. return Diag(OrigArg->getBeginLoc(),
  5235. diag::err_typecheck_call_invalid_unary_fp)
  5236. << OrigArg->getType() << OrigArg->getSourceRange();
  5237. // If this is an implicit conversion from float -> float, double, or
  5238. // long double, remove it.
  5239. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  5240. // Only remove standard FloatCasts, leaving other casts inplace
  5241. if (Cast->getCastKind() == CK_FloatingCast) {
  5242. Expr *CastArg = Cast->getSubExpr();
  5243. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  5244. assert(
  5245. (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  5246. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
  5247. Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
  5248. "promotion from float to either float, double, or long double is "
  5249. "the only expected cast here");
  5250. Cast->setSubExpr(nullptr);
  5251. TheCall->setArg(NumArgs-1, CastArg);
  5252. }
  5253. }
  5254. }
  5255. return false;
  5256. }
  5257. // Customized Sema Checking for VSX builtins that have the following signature:
  5258. // vector [...] builtinName(vector [...], vector [...], const int);
  5259. // Which takes the same type of vectors (any legal vector type) for the first
  5260. // two arguments and takes compile time constant for the third argument.
  5261. // Example builtins are :
  5262. // vector double vec_xxpermdi(vector double, vector double, int);
  5263. // vector short vec_xxsldwi(vector short, vector short, int);
  5264. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  5265. unsigned ExpectedNumArgs = 3;
  5266. if (TheCall->getNumArgs() < ExpectedNumArgs)
  5267. return Diag(TheCall->getEndLoc(),
  5268. diag::err_typecheck_call_too_few_args_at_least)
  5269. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5270. << TheCall->getSourceRange();
  5271. if (TheCall->getNumArgs() > ExpectedNumArgs)
  5272. return Diag(TheCall->getEndLoc(),
  5273. diag::err_typecheck_call_too_many_args_at_most)
  5274. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5275. << TheCall->getSourceRange();
  5276. // Check the third argument is a compile time constant
  5277. llvm::APSInt Value;
  5278. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  5279. return Diag(TheCall->getBeginLoc(),
  5280. diag::err_vsx_builtin_nonconstant_argument)
  5281. << 3 /* argument index */ << TheCall->getDirectCallee()
  5282. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5283. TheCall->getArg(2)->getEndLoc());
  5284. QualType Arg1Ty = TheCall->getArg(0)->getType();
  5285. QualType Arg2Ty = TheCall->getArg(1)->getType();
  5286. // Check the type of argument 1 and argument 2 are vectors.
  5287. SourceLocation BuiltinLoc = TheCall->getBeginLoc();
  5288. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  5289. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  5290. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  5291. << TheCall->getDirectCallee()
  5292. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5293. TheCall->getArg(1)->getEndLoc());
  5294. }
  5295. // Check the first two arguments are the same type.
  5296. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  5297. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  5298. << TheCall->getDirectCallee()
  5299. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5300. TheCall->getArg(1)->getEndLoc());
  5301. }
  5302. // When default clang type checking is turned off and the customized type
  5303. // checking is used, the returning type of the function must be explicitly
  5304. // set. Otherwise it is _Bool by default.
  5305. TheCall->setType(Arg1Ty);
  5306. return false;
  5307. }
  5308. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  5309. // This is declared to take (...), so we have to check everything.
  5310. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  5311. if (TheCall->getNumArgs() < 2)
  5312. return ExprError(Diag(TheCall->getEndLoc(),
  5313. diag::err_typecheck_call_too_few_args_at_least)
  5314. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5315. << TheCall->getSourceRange());
  5316. // Determine which of the following types of shufflevector we're checking:
  5317. // 1) unary, vector mask: (lhs, mask)
  5318. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  5319. QualType resType = TheCall->getArg(0)->getType();
  5320. unsigned numElements = 0;
  5321. if (!TheCall->getArg(0)->isTypeDependent() &&
  5322. !TheCall->getArg(1)->isTypeDependent()) {
  5323. QualType LHSType = TheCall->getArg(0)->getType();
  5324. QualType RHSType = TheCall->getArg(1)->getType();
  5325. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  5326. return ExprError(
  5327. Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
  5328. << TheCall->getDirectCallee()
  5329. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5330. TheCall->getArg(1)->getEndLoc()));
  5331. numElements = LHSType->getAs<VectorType>()->getNumElements();
  5332. unsigned numResElements = TheCall->getNumArgs() - 2;
  5333. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  5334. // with mask. If so, verify that RHS is an integer vector type with the
  5335. // same number of elts as lhs.
  5336. if (TheCall->getNumArgs() == 2) {
  5337. if (!RHSType->hasIntegerRepresentation() ||
  5338. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  5339. return ExprError(Diag(TheCall->getBeginLoc(),
  5340. diag::err_vec_builtin_incompatible_vector)
  5341. << TheCall->getDirectCallee()
  5342. << SourceRange(TheCall->getArg(1)->getBeginLoc(),
  5343. TheCall->getArg(1)->getEndLoc()));
  5344. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  5345. return ExprError(Diag(TheCall->getBeginLoc(),
  5346. diag::err_vec_builtin_incompatible_vector)
  5347. << TheCall->getDirectCallee()
  5348. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5349. TheCall->getArg(1)->getEndLoc()));
  5350. } else if (numElements != numResElements) {
  5351. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  5352. resType = Context.getVectorType(eltType, numResElements,
  5353. VectorType::GenericVector);
  5354. }
  5355. }
  5356. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  5357. if (TheCall->getArg(i)->isTypeDependent() ||
  5358. TheCall->getArg(i)->isValueDependent())
  5359. continue;
  5360. llvm::APSInt Result(32);
  5361. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  5362. return ExprError(Diag(TheCall->getBeginLoc(),
  5363. diag::err_shufflevector_nonconstant_argument)
  5364. << TheCall->getArg(i)->getSourceRange());
  5365. // Allow -1 which will be translated to undef in the IR.
  5366. if (Result.isSigned() && Result.isAllOnesValue())
  5367. continue;
  5368. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  5369. return ExprError(Diag(TheCall->getBeginLoc(),
  5370. diag::err_shufflevector_argument_too_large)
  5371. << TheCall->getArg(i)->getSourceRange());
  5372. }
  5373. SmallVector<Expr*, 32> exprs;
  5374. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  5375. exprs.push_back(TheCall->getArg(i));
  5376. TheCall->setArg(i, nullptr);
  5377. }
  5378. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  5379. TheCall->getCallee()->getBeginLoc(),
  5380. TheCall->getRParenLoc());
  5381. }
  5382. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  5383. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  5384. SourceLocation BuiltinLoc,
  5385. SourceLocation RParenLoc) {
  5386. ExprValueKind VK = VK_RValue;
  5387. ExprObjectKind OK = OK_Ordinary;
  5388. QualType DstTy = TInfo->getType();
  5389. QualType SrcTy = E->getType();
  5390. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  5391. return ExprError(Diag(BuiltinLoc,
  5392. diag::err_convertvector_non_vector)
  5393. << E->getSourceRange());
  5394. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  5395. return ExprError(Diag(BuiltinLoc,
  5396. diag::err_convertvector_non_vector_type));
  5397. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  5398. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  5399. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  5400. if (SrcElts != DstElts)
  5401. return ExprError(Diag(BuiltinLoc,
  5402. diag::err_convertvector_incompatible_vector)
  5403. << E->getSourceRange());
  5404. }
  5405. return new (Context)
  5406. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5407. }
  5408. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  5409. // This is declared to take (const void*, ...) and can take two
  5410. // optional constant int args.
  5411. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  5412. unsigned NumArgs = TheCall->getNumArgs();
  5413. if (NumArgs > 3)
  5414. return Diag(TheCall->getEndLoc(),
  5415. diag::err_typecheck_call_too_many_args_at_most)
  5416. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5417. // Argument 0 is checked for us and the remaining arguments must be
  5418. // constant integers.
  5419. for (unsigned i = 1; i != NumArgs; ++i)
  5420. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  5421. return true;
  5422. return false;
  5423. }
  5424. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  5425. // __assume does not evaluate its arguments, and should warn if its argument
  5426. // has side effects.
  5427. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  5428. Expr *Arg = TheCall->getArg(0);
  5429. if (Arg->isInstantiationDependent()) return false;
  5430. if (Arg->HasSideEffects(Context))
  5431. Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
  5432. << Arg->getSourceRange()
  5433. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  5434. return false;
  5435. }
  5436. /// Handle __builtin_alloca_with_align. This is declared
  5437. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  5438. /// than 8.
  5439. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  5440. // The alignment must be a constant integer.
  5441. Expr *Arg = TheCall->getArg(1);
  5442. // We can't check the value of a dependent argument.
  5443. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5444. if (const auto *UE =
  5445. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  5446. if (UE->getKind() == UETT_AlignOf ||
  5447. UE->getKind() == UETT_PreferredAlignOf)
  5448. Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
  5449. << Arg->getSourceRange();
  5450. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  5451. if (!Result.isPowerOf2())
  5452. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5453. << Arg->getSourceRange();
  5454. if (Result < Context.getCharWidth())
  5455. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
  5456. << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
  5457. if (Result > std::numeric_limits<int32_t>::max())
  5458. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
  5459. << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
  5460. }
  5461. return false;
  5462. }
  5463. /// Handle __builtin_assume_aligned. This is declared
  5464. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  5465. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  5466. unsigned NumArgs = TheCall->getNumArgs();
  5467. if (NumArgs > 3)
  5468. return Diag(TheCall->getEndLoc(),
  5469. diag::err_typecheck_call_too_many_args_at_most)
  5470. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5471. // The alignment must be a constant integer.
  5472. Expr *Arg = TheCall->getArg(1);
  5473. // We can't check the value of a dependent argument.
  5474. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5475. llvm::APSInt Result;
  5476. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5477. return true;
  5478. if (!Result.isPowerOf2())
  5479. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5480. << Arg->getSourceRange();
  5481. }
  5482. if (NumArgs > 2) {
  5483. ExprResult Arg(TheCall->getArg(2));
  5484. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  5485. Context.getSizeType(), false);
  5486. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5487. if (Arg.isInvalid()) return true;
  5488. TheCall->setArg(2, Arg.get());
  5489. }
  5490. return false;
  5491. }
  5492. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  5493. unsigned BuiltinID =
  5494. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  5495. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  5496. unsigned NumArgs = TheCall->getNumArgs();
  5497. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  5498. if (NumArgs < NumRequiredArgs) {
  5499. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5500. << 0 /* function call */ << NumRequiredArgs << NumArgs
  5501. << TheCall->getSourceRange();
  5502. }
  5503. if (NumArgs >= NumRequiredArgs + 0x100) {
  5504. return Diag(TheCall->getEndLoc(),
  5505. diag::err_typecheck_call_too_many_args_at_most)
  5506. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  5507. << TheCall->getSourceRange();
  5508. }
  5509. unsigned i = 0;
  5510. // For formatting call, check buffer arg.
  5511. if (!IsSizeCall) {
  5512. ExprResult Arg(TheCall->getArg(i));
  5513. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5514. Context, Context.VoidPtrTy, false);
  5515. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5516. if (Arg.isInvalid())
  5517. return true;
  5518. TheCall->setArg(i, Arg.get());
  5519. i++;
  5520. }
  5521. // Check string literal arg.
  5522. unsigned FormatIdx = i;
  5523. {
  5524. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  5525. if (Arg.isInvalid())
  5526. return true;
  5527. TheCall->setArg(i, Arg.get());
  5528. i++;
  5529. }
  5530. // Make sure variadic args are scalar.
  5531. unsigned FirstDataArg = i;
  5532. while (i < NumArgs) {
  5533. ExprResult Arg = DefaultVariadicArgumentPromotion(
  5534. TheCall->getArg(i), VariadicFunction, nullptr);
  5535. if (Arg.isInvalid())
  5536. return true;
  5537. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  5538. if (ArgSize.getQuantity() >= 0x100) {
  5539. return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
  5540. << i << (int)ArgSize.getQuantity() << 0xff
  5541. << TheCall->getSourceRange();
  5542. }
  5543. TheCall->setArg(i, Arg.get());
  5544. i++;
  5545. }
  5546. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  5547. // call to avoid duplicate diagnostics.
  5548. if (!IsSizeCall) {
  5549. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  5550. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  5551. bool Success = CheckFormatArguments(
  5552. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  5553. VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
  5554. CheckedVarArgs);
  5555. if (!Success)
  5556. return true;
  5557. }
  5558. if (IsSizeCall) {
  5559. TheCall->setType(Context.getSizeType());
  5560. } else {
  5561. TheCall->setType(Context.VoidPtrTy);
  5562. }
  5563. return false;
  5564. }
  5565. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  5566. /// TheCall is a constant expression.
  5567. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  5568. llvm::APSInt &Result) {
  5569. Expr *Arg = TheCall->getArg(ArgNum);
  5570. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5571. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  5572. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  5573. if (!Arg->isIntegerConstantExpr(Result, Context))
  5574. return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
  5575. << FDecl->getDeclName() << Arg->getSourceRange();
  5576. return false;
  5577. }
  5578. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  5579. /// TheCall is a constant expression in the range [Low, High].
  5580. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  5581. int Low, int High, bool RangeIsError) {
  5582. llvm::APSInt Result;
  5583. // We can't check the value of a dependent argument.
  5584. Expr *Arg = TheCall->getArg(ArgNum);
  5585. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5586. return false;
  5587. // Check constant-ness first.
  5588. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5589. return true;
  5590. if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
  5591. if (RangeIsError)
  5592. return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
  5593. << Result.toString(10) << Low << High << Arg->getSourceRange();
  5594. else
  5595. // Defer the warning until we know if the code will be emitted so that
  5596. // dead code can ignore this.
  5597. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  5598. PDiag(diag::warn_argument_invalid_range)
  5599. << Result.toString(10) << Low << High
  5600. << Arg->getSourceRange());
  5601. }
  5602. return false;
  5603. }
  5604. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  5605. /// TheCall is a constant expression is a multiple of Num..
  5606. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  5607. unsigned Num) {
  5608. llvm::APSInt Result;
  5609. // We can't check the value of a dependent argument.
  5610. Expr *Arg = TheCall->getArg(ArgNum);
  5611. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5612. return false;
  5613. // Check constant-ness first.
  5614. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5615. return true;
  5616. if (Result.getSExtValue() % Num != 0)
  5617. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
  5618. << Num << Arg->getSourceRange();
  5619. return false;
  5620. }
  5621. /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
  5622. bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
  5623. if (BuiltinID == AArch64::BI__builtin_arm_irg) {
  5624. if (checkArgCount(*this, TheCall, 2))
  5625. return true;
  5626. Expr *Arg0 = TheCall->getArg(0);
  5627. Expr *Arg1 = TheCall->getArg(1);
  5628. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5629. if (FirstArg.isInvalid())
  5630. return true;
  5631. QualType FirstArgType = FirstArg.get()->getType();
  5632. if (!FirstArgType->isAnyPointerType())
  5633. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5634. << "first" << FirstArgType << Arg0->getSourceRange();
  5635. TheCall->setArg(0, FirstArg.get());
  5636. ExprResult SecArg = DefaultLvalueConversion(Arg1);
  5637. if (SecArg.isInvalid())
  5638. return true;
  5639. QualType SecArgType = SecArg.get()->getType();
  5640. if (!SecArgType->isIntegerType())
  5641. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5642. << "second" << SecArgType << Arg1->getSourceRange();
  5643. // Derive the return type from the pointer argument.
  5644. TheCall->setType(FirstArgType);
  5645. return false;
  5646. }
  5647. if (BuiltinID == AArch64::BI__builtin_arm_addg) {
  5648. if (checkArgCount(*this, TheCall, 2))
  5649. return true;
  5650. Expr *Arg0 = TheCall->getArg(0);
  5651. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5652. if (FirstArg.isInvalid())
  5653. return true;
  5654. QualType FirstArgType = FirstArg.get()->getType();
  5655. if (!FirstArgType->isAnyPointerType())
  5656. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5657. << "first" << FirstArgType << Arg0->getSourceRange();
  5658. TheCall->setArg(0, FirstArg.get());
  5659. // Derive the return type from the pointer argument.
  5660. TheCall->setType(FirstArgType);
  5661. // Second arg must be an constant in range [0,15]
  5662. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5663. }
  5664. if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
  5665. if (checkArgCount(*this, TheCall, 2))
  5666. return true;
  5667. Expr *Arg0 = TheCall->getArg(0);
  5668. Expr *Arg1 = TheCall->getArg(1);
  5669. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5670. if (FirstArg.isInvalid())
  5671. return true;
  5672. QualType FirstArgType = FirstArg.get()->getType();
  5673. if (!FirstArgType->isAnyPointerType())
  5674. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5675. << "first" << FirstArgType << Arg0->getSourceRange();
  5676. QualType SecArgType = Arg1->getType();
  5677. if (!SecArgType->isIntegerType())
  5678. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5679. << "second" << SecArgType << Arg1->getSourceRange();
  5680. TheCall->setType(Context.IntTy);
  5681. return false;
  5682. }
  5683. if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
  5684. BuiltinID == AArch64::BI__builtin_arm_stg) {
  5685. if (checkArgCount(*this, TheCall, 1))
  5686. return true;
  5687. Expr *Arg0 = TheCall->getArg(0);
  5688. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5689. if (FirstArg.isInvalid())
  5690. return true;
  5691. QualType FirstArgType = FirstArg.get()->getType();
  5692. if (!FirstArgType->isAnyPointerType())
  5693. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5694. << "first" << FirstArgType << Arg0->getSourceRange();
  5695. TheCall->setArg(0, FirstArg.get());
  5696. // Derive the return type from the pointer argument.
  5697. if (BuiltinID == AArch64::BI__builtin_arm_ldg)
  5698. TheCall->setType(FirstArgType);
  5699. return false;
  5700. }
  5701. if (BuiltinID == AArch64::BI__builtin_arm_subp) {
  5702. Expr *ArgA = TheCall->getArg(0);
  5703. Expr *ArgB = TheCall->getArg(1);
  5704. ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
  5705. ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
  5706. if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
  5707. return true;
  5708. QualType ArgTypeA = ArgExprA.get()->getType();
  5709. QualType ArgTypeB = ArgExprB.get()->getType();
  5710. auto isNull = [&] (Expr *E) -> bool {
  5711. return E->isNullPointerConstant(
  5712. Context, Expr::NPC_ValueDependentIsNotNull); };
  5713. // argument should be either a pointer or null
  5714. if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
  5715. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5716. << "first" << ArgTypeA << ArgA->getSourceRange();
  5717. if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
  5718. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5719. << "second" << ArgTypeB << ArgB->getSourceRange();
  5720. // Ensure Pointee types are compatible
  5721. if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
  5722. ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
  5723. QualType pointeeA = ArgTypeA->getPointeeType();
  5724. QualType pointeeB = ArgTypeB->getPointeeType();
  5725. if (!Context.typesAreCompatible(
  5726. Context.getCanonicalType(pointeeA).getUnqualifiedType(),
  5727. Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
  5728. return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
  5729. << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
  5730. << ArgB->getSourceRange();
  5731. }
  5732. }
  5733. // at least one argument should be pointer type
  5734. if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
  5735. return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
  5736. << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
  5737. if (isNull(ArgA)) // adopt type of the other pointer
  5738. ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
  5739. if (isNull(ArgB))
  5740. ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
  5741. TheCall->setArg(0, ArgExprA.get());
  5742. TheCall->setArg(1, ArgExprB.get());
  5743. TheCall->setType(Context.LongLongTy);
  5744. return false;
  5745. }
  5746. assert(false && "Unhandled ARM MTE intrinsic");
  5747. return true;
  5748. }
  5749. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  5750. /// TheCall is an ARM/AArch64 special register string literal.
  5751. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  5752. int ArgNum, unsigned ExpectedFieldNum,
  5753. bool AllowName) {
  5754. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  5755. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  5756. BuiltinID == ARM::BI__builtin_arm_rsr ||
  5757. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  5758. BuiltinID == ARM::BI__builtin_arm_wsr ||
  5759. BuiltinID == ARM::BI__builtin_arm_wsrp;
  5760. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  5761. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  5762. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  5763. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  5764. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  5765. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  5766. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  5767. // We can't check the value of a dependent argument.
  5768. Expr *Arg = TheCall->getArg(ArgNum);
  5769. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5770. return false;
  5771. // Check if the argument is a string literal.
  5772. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  5773. return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  5774. << Arg->getSourceRange();
  5775. // Check the type of special register given.
  5776. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  5777. SmallVector<StringRef, 6> Fields;
  5778. Reg.split(Fields, ":");
  5779. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  5780. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5781. << Arg->getSourceRange();
  5782. // If the string is the name of a register then we cannot check that it is
  5783. // valid here but if the string is of one the forms described in ACLE then we
  5784. // can check that the supplied fields are integers and within the valid
  5785. // ranges.
  5786. if (Fields.size() > 1) {
  5787. bool FiveFields = Fields.size() == 5;
  5788. bool ValidString = true;
  5789. if (IsARMBuiltin) {
  5790. ValidString &= Fields[0].startswith_lower("cp") ||
  5791. Fields[0].startswith_lower("p");
  5792. if (ValidString)
  5793. Fields[0] =
  5794. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  5795. ValidString &= Fields[2].startswith_lower("c");
  5796. if (ValidString)
  5797. Fields[2] = Fields[2].drop_front(1);
  5798. if (FiveFields) {
  5799. ValidString &= Fields[3].startswith_lower("c");
  5800. if (ValidString)
  5801. Fields[3] = Fields[3].drop_front(1);
  5802. }
  5803. }
  5804. SmallVector<int, 5> Ranges;
  5805. if (FiveFields)
  5806. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  5807. else
  5808. Ranges.append({15, 7, 15});
  5809. for (unsigned i=0; i<Fields.size(); ++i) {
  5810. int IntField;
  5811. ValidString &= !Fields[i].getAsInteger(10, IntField);
  5812. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  5813. }
  5814. if (!ValidString)
  5815. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5816. << Arg->getSourceRange();
  5817. } else if (IsAArch64Builtin && Fields.size() == 1) {
  5818. // If the register name is one of those that appear in the condition below
  5819. // and the special register builtin being used is one of the write builtins,
  5820. // then we require that the argument provided for writing to the register
  5821. // is an integer constant expression. This is because it will be lowered to
  5822. // an MSR (immediate) instruction, so we need to know the immediate at
  5823. // compile time.
  5824. if (TheCall->getNumArgs() != 2)
  5825. return false;
  5826. std::string RegLower = Reg.lower();
  5827. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  5828. RegLower != "pan" && RegLower != "uao")
  5829. return false;
  5830. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5831. }
  5832. return false;
  5833. }
  5834. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  5835. /// This checks that the target supports __builtin_longjmp and
  5836. /// that val is a constant 1.
  5837. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  5838. if (!Context.getTargetInfo().hasSjLjLowering())
  5839. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
  5840. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5841. Expr *Arg = TheCall->getArg(1);
  5842. llvm::APSInt Result;
  5843. // TODO: This is less than ideal. Overload this to take a value.
  5844. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5845. return true;
  5846. if (Result != 1)
  5847. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
  5848. << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
  5849. return false;
  5850. }
  5851. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  5852. /// This checks that the target supports __builtin_setjmp.
  5853. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  5854. if (!Context.getTargetInfo().hasSjLjLowering())
  5855. return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
  5856. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5857. return false;
  5858. }
  5859. namespace {
  5860. class UncoveredArgHandler {
  5861. enum { Unknown = -1, AllCovered = -2 };
  5862. signed FirstUncoveredArg = Unknown;
  5863. SmallVector<const Expr *, 4> DiagnosticExprs;
  5864. public:
  5865. UncoveredArgHandler() = default;
  5866. bool hasUncoveredArg() const {
  5867. return (FirstUncoveredArg >= 0);
  5868. }
  5869. unsigned getUncoveredArg() const {
  5870. assert(hasUncoveredArg() && "no uncovered argument");
  5871. return FirstUncoveredArg;
  5872. }
  5873. void setAllCovered() {
  5874. // A string has been found with all arguments covered, so clear out
  5875. // the diagnostics.
  5876. DiagnosticExprs.clear();
  5877. FirstUncoveredArg = AllCovered;
  5878. }
  5879. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  5880. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  5881. // Don't update if a previous string covers all arguments.
  5882. if (FirstUncoveredArg == AllCovered)
  5883. return;
  5884. // UncoveredArgHandler tracks the highest uncovered argument index
  5885. // and with it all the strings that match this index.
  5886. if (NewFirstUncoveredArg == FirstUncoveredArg)
  5887. DiagnosticExprs.push_back(StrExpr);
  5888. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  5889. DiagnosticExprs.clear();
  5890. DiagnosticExprs.push_back(StrExpr);
  5891. FirstUncoveredArg = NewFirstUncoveredArg;
  5892. }
  5893. }
  5894. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  5895. };
  5896. enum StringLiteralCheckType {
  5897. SLCT_NotALiteral,
  5898. SLCT_UncheckedLiteral,
  5899. SLCT_CheckedLiteral
  5900. };
  5901. } // namespace
  5902. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  5903. BinaryOperatorKind BinOpKind,
  5904. bool AddendIsRight) {
  5905. unsigned BitWidth = Offset.getBitWidth();
  5906. unsigned AddendBitWidth = Addend.getBitWidth();
  5907. // There might be negative interim results.
  5908. if (Addend.isUnsigned()) {
  5909. Addend = Addend.zext(++AddendBitWidth);
  5910. Addend.setIsSigned(true);
  5911. }
  5912. // Adjust the bit width of the APSInts.
  5913. if (AddendBitWidth > BitWidth) {
  5914. Offset = Offset.sext(AddendBitWidth);
  5915. BitWidth = AddendBitWidth;
  5916. } else if (BitWidth > AddendBitWidth) {
  5917. Addend = Addend.sext(BitWidth);
  5918. }
  5919. bool Ov = false;
  5920. llvm::APSInt ResOffset = Offset;
  5921. if (BinOpKind == BO_Add)
  5922. ResOffset = Offset.sadd_ov(Addend, Ov);
  5923. else {
  5924. assert(AddendIsRight && BinOpKind == BO_Sub &&
  5925. "operator must be add or sub with addend on the right");
  5926. ResOffset = Offset.ssub_ov(Addend, Ov);
  5927. }
  5928. // We add an offset to a pointer here so we should support an offset as big as
  5929. // possible.
  5930. if (Ov) {
  5931. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  5932. "index (intermediate) result too big");
  5933. Offset = Offset.sext(2 * BitWidth);
  5934. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  5935. return;
  5936. }
  5937. Offset = ResOffset;
  5938. }
  5939. namespace {
  5940. // This is a wrapper class around StringLiteral to support offsetted string
  5941. // literals as format strings. It takes the offset into account when returning
  5942. // the string and its length or the source locations to display notes correctly.
  5943. class FormatStringLiteral {
  5944. const StringLiteral *FExpr;
  5945. int64_t Offset;
  5946. public:
  5947. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  5948. : FExpr(fexpr), Offset(Offset) {}
  5949. StringRef getString() const {
  5950. return FExpr->getString().drop_front(Offset);
  5951. }
  5952. unsigned getByteLength() const {
  5953. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  5954. }
  5955. unsigned getLength() const { return FExpr->getLength() - Offset; }
  5956. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  5957. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  5958. QualType getType() const { return FExpr->getType(); }
  5959. bool isAscii() const { return FExpr->isAscii(); }
  5960. bool isWide() const { return FExpr->isWide(); }
  5961. bool isUTF8() const { return FExpr->isUTF8(); }
  5962. bool isUTF16() const { return FExpr->isUTF16(); }
  5963. bool isUTF32() const { return FExpr->isUTF32(); }
  5964. bool isPascal() const { return FExpr->isPascal(); }
  5965. SourceLocation getLocationOfByte(
  5966. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  5967. const TargetInfo &Target, unsigned *StartToken = nullptr,
  5968. unsigned *StartTokenByteOffset = nullptr) const {
  5969. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  5970. StartToken, StartTokenByteOffset);
  5971. }
  5972. SourceLocation getBeginLoc() const LLVM_READONLY {
  5973. return FExpr->getBeginLoc().getLocWithOffset(Offset);
  5974. }
  5975. SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
  5976. };
  5977. } // namespace
  5978. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  5979. const Expr *OrigFormatExpr,
  5980. ArrayRef<const Expr *> Args,
  5981. bool HasVAListArg, unsigned format_idx,
  5982. unsigned firstDataArg,
  5983. Sema::FormatStringType Type,
  5984. bool inFunctionCall,
  5985. Sema::VariadicCallType CallType,
  5986. llvm::SmallBitVector &CheckedVarArgs,
  5987. UncoveredArgHandler &UncoveredArg);
  5988. // Determine if an expression is a string literal or constant string.
  5989. // If this function returns false on the arguments to a function expecting a
  5990. // format string, we will usually need to emit a warning.
  5991. // True string literals are then checked by CheckFormatString.
  5992. static StringLiteralCheckType
  5993. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  5994. bool HasVAListArg, unsigned format_idx,
  5995. unsigned firstDataArg, Sema::FormatStringType Type,
  5996. Sema::VariadicCallType CallType, bool InFunctionCall,
  5997. llvm::SmallBitVector &CheckedVarArgs,
  5998. UncoveredArgHandler &UncoveredArg,
  5999. llvm::APSInt Offset) {
  6000. tryAgain:
  6001. assert(Offset.isSigned() && "invalid offset");
  6002. if (E->isTypeDependent() || E->isValueDependent())
  6003. return SLCT_NotALiteral;
  6004. E = E->IgnoreParenCasts();
  6005. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  6006. // Technically -Wformat-nonliteral does not warn about this case.
  6007. // The behavior of printf and friends in this case is implementation
  6008. // dependent. Ideally if the format string cannot be null then
  6009. // it should have a 'nonnull' attribute in the function prototype.
  6010. return SLCT_UncheckedLiteral;
  6011. switch (E->getStmtClass()) {
  6012. case Stmt::BinaryConditionalOperatorClass:
  6013. case Stmt::ConditionalOperatorClass: {
  6014. // The expression is a literal if both sub-expressions were, and it was
  6015. // completely checked only if both sub-expressions were checked.
  6016. const AbstractConditionalOperator *C =
  6017. cast<AbstractConditionalOperator>(E);
  6018. // Determine whether it is necessary to check both sub-expressions, for
  6019. // example, because the condition expression is a constant that can be
  6020. // evaluated at compile time.
  6021. bool CheckLeft = true, CheckRight = true;
  6022. bool Cond;
  6023. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
  6024. if (Cond)
  6025. CheckRight = false;
  6026. else
  6027. CheckLeft = false;
  6028. }
  6029. // We need to maintain the offsets for the right and the left hand side
  6030. // separately to check if every possible indexed expression is a valid
  6031. // string literal. They might have different offsets for different string
  6032. // literals in the end.
  6033. StringLiteralCheckType Left;
  6034. if (!CheckLeft)
  6035. Left = SLCT_UncheckedLiteral;
  6036. else {
  6037. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  6038. HasVAListArg, format_idx, firstDataArg,
  6039. Type, CallType, InFunctionCall,
  6040. CheckedVarArgs, UncoveredArg, Offset);
  6041. if (Left == SLCT_NotALiteral || !CheckRight) {
  6042. return Left;
  6043. }
  6044. }
  6045. StringLiteralCheckType Right =
  6046. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  6047. HasVAListArg, format_idx, firstDataArg,
  6048. Type, CallType, InFunctionCall, CheckedVarArgs,
  6049. UncoveredArg, Offset);
  6050. return (CheckLeft && Left < Right) ? Left : Right;
  6051. }
  6052. case Stmt::ImplicitCastExprClass:
  6053. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  6054. goto tryAgain;
  6055. case Stmt::OpaqueValueExprClass:
  6056. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  6057. E = src;
  6058. goto tryAgain;
  6059. }
  6060. return SLCT_NotALiteral;
  6061. case Stmt::PredefinedExprClass:
  6062. // While __func__, etc., are technically not string literals, they
  6063. // cannot contain format specifiers and thus are not a security
  6064. // liability.
  6065. return SLCT_UncheckedLiteral;
  6066. case Stmt::DeclRefExprClass: {
  6067. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  6068. // As an exception, do not flag errors for variables binding to
  6069. // const string literals.
  6070. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  6071. bool isConstant = false;
  6072. QualType T = DR->getType();
  6073. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  6074. isConstant = AT->getElementType().isConstant(S.Context);
  6075. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  6076. isConstant = T.isConstant(S.Context) &&
  6077. PT->getPointeeType().isConstant(S.Context);
  6078. } else if (T->isObjCObjectPointerType()) {
  6079. // In ObjC, there is usually no "const ObjectPointer" type,
  6080. // so don't check if the pointee type is constant.
  6081. isConstant = T.isConstant(S.Context);
  6082. }
  6083. if (isConstant) {
  6084. if (const Expr *Init = VD->getAnyInitializer()) {
  6085. // Look through initializers like const char c[] = { "foo" }
  6086. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  6087. if (InitList->isStringLiteralInit())
  6088. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  6089. }
  6090. return checkFormatStringExpr(S, Init, Args,
  6091. HasVAListArg, format_idx,
  6092. firstDataArg, Type, CallType,
  6093. /*InFunctionCall*/ false, CheckedVarArgs,
  6094. UncoveredArg, Offset);
  6095. }
  6096. }
  6097. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  6098. // special check to see if the format string is a function parameter
  6099. // of the function calling the printf function. If the function
  6100. // has an attribute indicating it is a printf-like function, then we
  6101. // should suppress warnings concerning non-literals being used in a call
  6102. // to a vprintf function. For example:
  6103. //
  6104. // void
  6105. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  6106. // va_list ap;
  6107. // va_start(ap, fmt);
  6108. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  6109. // ...
  6110. // }
  6111. if (HasVAListArg) {
  6112. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  6113. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  6114. int PVIndex = PV->getFunctionScopeIndex() + 1;
  6115. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  6116. // adjust for implicit parameter
  6117. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  6118. if (MD->isInstance())
  6119. ++PVIndex;
  6120. // We also check if the formats are compatible.
  6121. // We can't pass a 'scanf' string to a 'printf' function.
  6122. if (PVIndex == PVFormat->getFormatIdx() &&
  6123. Type == S.GetFormatStringType(PVFormat))
  6124. return SLCT_UncheckedLiteral;
  6125. }
  6126. }
  6127. }
  6128. }
  6129. }
  6130. return SLCT_NotALiteral;
  6131. }
  6132. case Stmt::CallExprClass:
  6133. case Stmt::CXXMemberCallExprClass: {
  6134. const CallExpr *CE = cast<CallExpr>(E);
  6135. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  6136. bool IsFirst = true;
  6137. StringLiteralCheckType CommonResult;
  6138. for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
  6139. const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
  6140. StringLiteralCheckType Result = checkFormatStringExpr(
  6141. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6142. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  6143. if (IsFirst) {
  6144. CommonResult = Result;
  6145. IsFirst = false;
  6146. }
  6147. }
  6148. if (!IsFirst)
  6149. return CommonResult;
  6150. if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
  6151. unsigned BuiltinID = FD->getBuiltinID();
  6152. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  6153. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  6154. const Expr *Arg = CE->getArg(0);
  6155. return checkFormatStringExpr(S, Arg, Args,
  6156. HasVAListArg, format_idx,
  6157. firstDataArg, Type, CallType,
  6158. InFunctionCall, CheckedVarArgs,
  6159. UncoveredArg, Offset);
  6160. }
  6161. }
  6162. }
  6163. return SLCT_NotALiteral;
  6164. }
  6165. case Stmt::ObjCMessageExprClass: {
  6166. const auto *ME = cast<ObjCMessageExpr>(E);
  6167. if (const auto *ND = ME->getMethodDecl()) {
  6168. if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
  6169. const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
  6170. return checkFormatStringExpr(
  6171. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6172. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  6173. }
  6174. }
  6175. return SLCT_NotALiteral;
  6176. }
  6177. case Stmt::ObjCStringLiteralClass:
  6178. case Stmt::StringLiteralClass: {
  6179. const StringLiteral *StrE = nullptr;
  6180. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  6181. StrE = ObjCFExpr->getString();
  6182. else
  6183. StrE = cast<StringLiteral>(E);
  6184. if (StrE) {
  6185. if (Offset.isNegative() || Offset > StrE->getLength()) {
  6186. // TODO: It would be better to have an explicit warning for out of
  6187. // bounds literals.
  6188. return SLCT_NotALiteral;
  6189. }
  6190. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  6191. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  6192. firstDataArg, Type, InFunctionCall, CallType,
  6193. CheckedVarArgs, UncoveredArg);
  6194. return SLCT_CheckedLiteral;
  6195. }
  6196. return SLCT_NotALiteral;
  6197. }
  6198. case Stmt::BinaryOperatorClass: {
  6199. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  6200. // A string literal + an int offset is still a string literal.
  6201. if (BinOp->isAdditiveOp()) {
  6202. Expr::EvalResult LResult, RResult;
  6203. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
  6204. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
  6205. if (LIsInt != RIsInt) {
  6206. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  6207. if (LIsInt) {
  6208. if (BinOpKind == BO_Add) {
  6209. sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
  6210. E = BinOp->getRHS();
  6211. goto tryAgain;
  6212. }
  6213. } else {
  6214. sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
  6215. E = BinOp->getLHS();
  6216. goto tryAgain;
  6217. }
  6218. }
  6219. }
  6220. return SLCT_NotALiteral;
  6221. }
  6222. case Stmt::UnaryOperatorClass: {
  6223. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  6224. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  6225. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  6226. Expr::EvalResult IndexResult;
  6227. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
  6228. sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
  6229. /*RHS is int*/ true);
  6230. E = ASE->getBase();
  6231. goto tryAgain;
  6232. }
  6233. }
  6234. return SLCT_NotALiteral;
  6235. }
  6236. default:
  6237. return SLCT_NotALiteral;
  6238. }
  6239. }
  6240. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  6241. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  6242. .Case("scanf", FST_Scanf)
  6243. .Cases("printf", "printf0", FST_Printf)
  6244. .Cases("NSString", "CFString", FST_NSString)
  6245. .Case("strftime", FST_Strftime)
  6246. .Case("strfmon", FST_Strfmon)
  6247. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  6248. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  6249. .Case("os_trace", FST_OSLog)
  6250. .Case("os_log", FST_OSLog)
  6251. .Default(FST_Unknown);
  6252. }
  6253. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  6254. /// functions) for correct use of format strings.
  6255. /// Returns true if a format string has been fully checked.
  6256. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  6257. ArrayRef<const Expr *> Args,
  6258. bool IsCXXMember,
  6259. VariadicCallType CallType,
  6260. SourceLocation Loc, SourceRange Range,
  6261. llvm::SmallBitVector &CheckedVarArgs) {
  6262. FormatStringInfo FSI;
  6263. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  6264. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  6265. FSI.FirstDataArg, GetFormatStringType(Format),
  6266. CallType, Loc, Range, CheckedVarArgs);
  6267. return false;
  6268. }
  6269. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  6270. bool HasVAListArg, unsigned format_idx,
  6271. unsigned firstDataArg, FormatStringType Type,
  6272. VariadicCallType CallType,
  6273. SourceLocation Loc, SourceRange Range,
  6274. llvm::SmallBitVector &CheckedVarArgs) {
  6275. // CHECK: printf/scanf-like function is called with no format string.
  6276. if (format_idx >= Args.size()) {
  6277. Diag(Loc, diag::warn_missing_format_string) << Range;
  6278. return false;
  6279. }
  6280. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  6281. // CHECK: format string is not a string literal.
  6282. //
  6283. // Dynamically generated format strings are difficult to
  6284. // automatically vet at compile time. Requiring that format strings
  6285. // are string literals: (1) permits the checking of format strings by
  6286. // the compiler and thereby (2) can practically remove the source of
  6287. // many format string exploits.
  6288. // Format string can be either ObjC string (e.g. @"%d") or
  6289. // C string (e.g. "%d")
  6290. // ObjC string uses the same format specifiers as C string, so we can use
  6291. // the same format string checking logic for both ObjC and C strings.
  6292. UncoveredArgHandler UncoveredArg;
  6293. StringLiteralCheckType CT =
  6294. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  6295. format_idx, firstDataArg, Type, CallType,
  6296. /*IsFunctionCall*/ true, CheckedVarArgs,
  6297. UncoveredArg,
  6298. /*no string offset*/ llvm::APSInt(64, false) = 0);
  6299. // Generate a diagnostic where an uncovered argument is detected.
  6300. if (UncoveredArg.hasUncoveredArg()) {
  6301. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  6302. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  6303. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  6304. }
  6305. if (CT != SLCT_NotALiteral)
  6306. // Literal format string found, check done!
  6307. return CT == SLCT_CheckedLiteral;
  6308. // Strftime is particular as it always uses a single 'time' argument,
  6309. // so it is safe to pass a non-literal string.
  6310. if (Type == FST_Strftime)
  6311. return false;
  6312. // Do not emit diag when the string param is a macro expansion and the
  6313. // format is either NSString or CFString. This is a hack to prevent
  6314. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  6315. // which are usually used in place of NS and CF string literals.
  6316. SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
  6317. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  6318. return false;
  6319. // If there are no arguments specified, warn with -Wformat-security, otherwise
  6320. // warn only with -Wformat-nonliteral.
  6321. if (Args.size() == firstDataArg) {
  6322. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  6323. << OrigFormatExpr->getSourceRange();
  6324. switch (Type) {
  6325. default:
  6326. break;
  6327. case FST_Kprintf:
  6328. case FST_FreeBSDKPrintf:
  6329. case FST_Printf:
  6330. Diag(FormatLoc, diag::note_format_security_fixit)
  6331. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  6332. break;
  6333. case FST_NSString:
  6334. Diag(FormatLoc, diag::note_format_security_fixit)
  6335. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  6336. break;
  6337. }
  6338. } else {
  6339. Diag(FormatLoc, diag::warn_format_nonliteral)
  6340. << OrigFormatExpr->getSourceRange();
  6341. }
  6342. return false;
  6343. }
  6344. namespace {
  6345. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  6346. protected:
  6347. Sema &S;
  6348. const FormatStringLiteral *FExpr;
  6349. const Expr *OrigFormatExpr;
  6350. const Sema::FormatStringType FSType;
  6351. const unsigned FirstDataArg;
  6352. const unsigned NumDataArgs;
  6353. const char *Beg; // Start of format string.
  6354. const bool HasVAListArg;
  6355. ArrayRef<const Expr *> Args;
  6356. unsigned FormatIdx;
  6357. llvm::SmallBitVector CoveredArgs;
  6358. bool usesPositionalArgs = false;
  6359. bool atFirstArg = true;
  6360. bool inFunctionCall;
  6361. Sema::VariadicCallType CallType;
  6362. llvm::SmallBitVector &CheckedVarArgs;
  6363. UncoveredArgHandler &UncoveredArg;
  6364. public:
  6365. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  6366. const Expr *origFormatExpr,
  6367. const Sema::FormatStringType type, unsigned firstDataArg,
  6368. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  6369. ArrayRef<const Expr *> Args, unsigned formatIdx,
  6370. bool inFunctionCall, Sema::VariadicCallType callType,
  6371. llvm::SmallBitVector &CheckedVarArgs,
  6372. UncoveredArgHandler &UncoveredArg)
  6373. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  6374. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  6375. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  6376. inFunctionCall(inFunctionCall), CallType(callType),
  6377. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  6378. CoveredArgs.resize(numDataArgs);
  6379. CoveredArgs.reset();
  6380. }
  6381. void DoneProcessing();
  6382. void HandleIncompleteSpecifier(const char *startSpecifier,
  6383. unsigned specifierLen) override;
  6384. void HandleInvalidLengthModifier(
  6385. const analyze_format_string::FormatSpecifier &FS,
  6386. const analyze_format_string::ConversionSpecifier &CS,
  6387. const char *startSpecifier, unsigned specifierLen,
  6388. unsigned DiagID);
  6389. void HandleNonStandardLengthModifier(
  6390. const analyze_format_string::FormatSpecifier &FS,
  6391. const char *startSpecifier, unsigned specifierLen);
  6392. void HandleNonStandardConversionSpecifier(
  6393. const analyze_format_string::ConversionSpecifier &CS,
  6394. const char *startSpecifier, unsigned specifierLen);
  6395. void HandlePosition(const char *startPos, unsigned posLen) override;
  6396. void HandleInvalidPosition(const char *startSpecifier,
  6397. unsigned specifierLen,
  6398. analyze_format_string::PositionContext p) override;
  6399. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  6400. void HandleNullChar(const char *nullCharacter) override;
  6401. template <typename Range>
  6402. static void
  6403. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  6404. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  6405. bool IsStringLocation, Range StringRange,
  6406. ArrayRef<FixItHint> Fixit = None);
  6407. protected:
  6408. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  6409. const char *startSpec,
  6410. unsigned specifierLen,
  6411. const char *csStart, unsigned csLen);
  6412. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6413. const char *startSpec,
  6414. unsigned specifierLen);
  6415. SourceRange getFormatStringRange();
  6416. CharSourceRange getSpecifierRange(const char *startSpecifier,
  6417. unsigned specifierLen);
  6418. SourceLocation getLocationOfByte(const char *x);
  6419. const Expr *getDataArg(unsigned i) const;
  6420. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  6421. const analyze_format_string::ConversionSpecifier &CS,
  6422. const char *startSpecifier, unsigned specifierLen,
  6423. unsigned argIndex);
  6424. template <typename Range>
  6425. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  6426. bool IsStringLocation, Range StringRange,
  6427. ArrayRef<FixItHint> Fixit = None);
  6428. };
  6429. } // namespace
  6430. SourceRange CheckFormatHandler::getFormatStringRange() {
  6431. return OrigFormatExpr->getSourceRange();
  6432. }
  6433. CharSourceRange CheckFormatHandler::
  6434. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  6435. SourceLocation Start = getLocationOfByte(startSpecifier);
  6436. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  6437. // Advance the end SourceLocation by one due to half-open ranges.
  6438. End = End.getLocWithOffset(1);
  6439. return CharSourceRange::getCharRange(Start, End);
  6440. }
  6441. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  6442. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  6443. S.getLangOpts(), S.Context.getTargetInfo());
  6444. }
  6445. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  6446. unsigned specifierLen){
  6447. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  6448. getLocationOfByte(startSpecifier),
  6449. /*IsStringLocation*/true,
  6450. getSpecifierRange(startSpecifier, specifierLen));
  6451. }
  6452. void CheckFormatHandler::HandleInvalidLengthModifier(
  6453. const analyze_format_string::FormatSpecifier &FS,
  6454. const analyze_format_string::ConversionSpecifier &CS,
  6455. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  6456. using namespace analyze_format_string;
  6457. const LengthModifier &LM = FS.getLengthModifier();
  6458. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6459. // See if we know how to fix this length modifier.
  6460. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6461. if (FixedLM) {
  6462. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6463. getLocationOfByte(LM.getStart()),
  6464. /*IsStringLocation*/true,
  6465. getSpecifierRange(startSpecifier, specifierLen));
  6466. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6467. << FixedLM->toString()
  6468. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6469. } else {
  6470. FixItHint Hint;
  6471. if (DiagID == diag::warn_format_nonsensical_length)
  6472. Hint = FixItHint::CreateRemoval(LMRange);
  6473. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6474. getLocationOfByte(LM.getStart()),
  6475. /*IsStringLocation*/true,
  6476. getSpecifierRange(startSpecifier, specifierLen),
  6477. Hint);
  6478. }
  6479. }
  6480. void CheckFormatHandler::HandleNonStandardLengthModifier(
  6481. const analyze_format_string::FormatSpecifier &FS,
  6482. const char *startSpecifier, unsigned specifierLen) {
  6483. using namespace analyze_format_string;
  6484. const LengthModifier &LM = FS.getLengthModifier();
  6485. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6486. // See if we know how to fix this length modifier.
  6487. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6488. if (FixedLM) {
  6489. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6490. << LM.toString() << 0,
  6491. getLocationOfByte(LM.getStart()),
  6492. /*IsStringLocation*/true,
  6493. getSpecifierRange(startSpecifier, specifierLen));
  6494. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6495. << FixedLM->toString()
  6496. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6497. } else {
  6498. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6499. << LM.toString() << 0,
  6500. getLocationOfByte(LM.getStart()),
  6501. /*IsStringLocation*/true,
  6502. getSpecifierRange(startSpecifier, specifierLen));
  6503. }
  6504. }
  6505. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  6506. const analyze_format_string::ConversionSpecifier &CS,
  6507. const char *startSpecifier, unsigned specifierLen) {
  6508. using namespace analyze_format_string;
  6509. // See if we know how to fix this conversion specifier.
  6510. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  6511. if (FixedCS) {
  6512. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6513. << CS.toString() << /*conversion specifier*/1,
  6514. getLocationOfByte(CS.getStart()),
  6515. /*IsStringLocation*/true,
  6516. getSpecifierRange(startSpecifier, specifierLen));
  6517. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  6518. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  6519. << FixedCS->toString()
  6520. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  6521. } else {
  6522. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6523. << CS.toString() << /*conversion specifier*/1,
  6524. getLocationOfByte(CS.getStart()),
  6525. /*IsStringLocation*/true,
  6526. getSpecifierRange(startSpecifier, specifierLen));
  6527. }
  6528. }
  6529. void CheckFormatHandler::HandlePosition(const char *startPos,
  6530. unsigned posLen) {
  6531. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  6532. getLocationOfByte(startPos),
  6533. /*IsStringLocation*/true,
  6534. getSpecifierRange(startPos, posLen));
  6535. }
  6536. void
  6537. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  6538. analyze_format_string::PositionContext p) {
  6539. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  6540. << (unsigned) p,
  6541. getLocationOfByte(startPos), /*IsStringLocation*/true,
  6542. getSpecifierRange(startPos, posLen));
  6543. }
  6544. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  6545. unsigned posLen) {
  6546. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  6547. getLocationOfByte(startPos),
  6548. /*IsStringLocation*/true,
  6549. getSpecifierRange(startPos, posLen));
  6550. }
  6551. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  6552. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  6553. // The presence of a null character is likely an error.
  6554. EmitFormatDiagnostic(
  6555. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  6556. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  6557. getFormatStringRange());
  6558. }
  6559. }
  6560. // Note that this may return NULL if there was an error parsing or building
  6561. // one of the argument expressions.
  6562. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  6563. return Args[FirstDataArg + i];
  6564. }
  6565. void CheckFormatHandler::DoneProcessing() {
  6566. // Does the number of data arguments exceed the number of
  6567. // format conversions in the format string?
  6568. if (!HasVAListArg) {
  6569. // Find any arguments that weren't covered.
  6570. CoveredArgs.flip();
  6571. signed notCoveredArg = CoveredArgs.find_first();
  6572. if (notCoveredArg >= 0) {
  6573. assert((unsigned)notCoveredArg < NumDataArgs);
  6574. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  6575. } else {
  6576. UncoveredArg.setAllCovered();
  6577. }
  6578. }
  6579. }
  6580. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  6581. const Expr *ArgExpr) {
  6582. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  6583. "Invalid state");
  6584. if (!ArgExpr)
  6585. return;
  6586. SourceLocation Loc = ArgExpr->getBeginLoc();
  6587. if (S.getSourceManager().isInSystemMacro(Loc))
  6588. return;
  6589. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  6590. for (auto E : DiagnosticExprs)
  6591. PDiag << E->getSourceRange();
  6592. CheckFormatHandler::EmitFormatDiagnostic(
  6593. S, IsFunctionCall, DiagnosticExprs[0],
  6594. PDiag, Loc, /*IsStringLocation*/false,
  6595. DiagnosticExprs[0]->getSourceRange());
  6596. }
  6597. bool
  6598. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  6599. SourceLocation Loc,
  6600. const char *startSpec,
  6601. unsigned specifierLen,
  6602. const char *csStart,
  6603. unsigned csLen) {
  6604. bool keepGoing = true;
  6605. if (argIndex < NumDataArgs) {
  6606. // Consider the argument coverered, even though the specifier doesn't
  6607. // make sense.
  6608. CoveredArgs.set(argIndex);
  6609. }
  6610. else {
  6611. // If argIndex exceeds the number of data arguments we
  6612. // don't issue a warning because that is just a cascade of warnings (and
  6613. // they may have intended '%%' anyway). We don't want to continue processing
  6614. // the format string after this point, however, as we will like just get
  6615. // gibberish when trying to match arguments.
  6616. keepGoing = false;
  6617. }
  6618. StringRef Specifier(csStart, csLen);
  6619. // If the specifier in non-printable, it could be the first byte of a UTF-8
  6620. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  6621. // hex value.
  6622. std::string CodePointStr;
  6623. if (!llvm::sys::locale::isPrint(*csStart)) {
  6624. llvm::UTF32 CodePoint;
  6625. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  6626. const llvm::UTF8 *E =
  6627. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  6628. llvm::ConversionResult Result =
  6629. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  6630. if (Result != llvm::conversionOK) {
  6631. unsigned char FirstChar = *csStart;
  6632. CodePoint = (llvm::UTF32)FirstChar;
  6633. }
  6634. llvm::raw_string_ostream OS(CodePointStr);
  6635. if (CodePoint < 256)
  6636. OS << "\\x" << llvm::format("%02x", CodePoint);
  6637. else if (CodePoint <= 0xFFFF)
  6638. OS << "\\u" << llvm::format("%04x", CodePoint);
  6639. else
  6640. OS << "\\U" << llvm::format("%08x", CodePoint);
  6641. OS.flush();
  6642. Specifier = CodePointStr;
  6643. }
  6644. EmitFormatDiagnostic(
  6645. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  6646. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  6647. return keepGoing;
  6648. }
  6649. void
  6650. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6651. const char *startSpec,
  6652. unsigned specifierLen) {
  6653. EmitFormatDiagnostic(
  6654. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  6655. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  6656. }
  6657. bool
  6658. CheckFormatHandler::CheckNumArgs(
  6659. const analyze_format_string::FormatSpecifier &FS,
  6660. const analyze_format_string::ConversionSpecifier &CS,
  6661. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  6662. if (argIndex >= NumDataArgs) {
  6663. PartialDiagnostic PDiag = FS.usesPositionalArg()
  6664. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  6665. << (argIndex+1) << NumDataArgs)
  6666. : S.PDiag(diag::warn_printf_insufficient_data_args);
  6667. EmitFormatDiagnostic(
  6668. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  6669. getSpecifierRange(startSpecifier, specifierLen));
  6670. // Since more arguments than conversion tokens are given, by extension
  6671. // all arguments are covered, so mark this as so.
  6672. UncoveredArg.setAllCovered();
  6673. return false;
  6674. }
  6675. return true;
  6676. }
  6677. template<typename Range>
  6678. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  6679. SourceLocation Loc,
  6680. bool IsStringLocation,
  6681. Range StringRange,
  6682. ArrayRef<FixItHint> FixIt) {
  6683. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  6684. Loc, IsStringLocation, StringRange, FixIt);
  6685. }
  6686. /// If the format string is not within the function call, emit a note
  6687. /// so that the function call and string are in diagnostic messages.
  6688. ///
  6689. /// \param InFunctionCall if true, the format string is within the function
  6690. /// call and only one diagnostic message will be produced. Otherwise, an
  6691. /// extra note will be emitted pointing to location of the format string.
  6692. ///
  6693. /// \param ArgumentExpr the expression that is passed as the format string
  6694. /// argument in the function call. Used for getting locations when two
  6695. /// diagnostics are emitted.
  6696. ///
  6697. /// \param PDiag the callee should already have provided any strings for the
  6698. /// diagnostic message. This function only adds locations and fixits
  6699. /// to diagnostics.
  6700. ///
  6701. /// \param Loc primary location for diagnostic. If two diagnostics are
  6702. /// required, one will be at Loc and a new SourceLocation will be created for
  6703. /// the other one.
  6704. ///
  6705. /// \param IsStringLocation if true, Loc points to the format string should be
  6706. /// used for the note. Otherwise, Loc points to the argument list and will
  6707. /// be used with PDiag.
  6708. ///
  6709. /// \param StringRange some or all of the string to highlight. This is
  6710. /// templated so it can accept either a CharSourceRange or a SourceRange.
  6711. ///
  6712. /// \param FixIt optional fix it hint for the format string.
  6713. template <typename Range>
  6714. void CheckFormatHandler::EmitFormatDiagnostic(
  6715. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  6716. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  6717. Range StringRange, ArrayRef<FixItHint> FixIt) {
  6718. if (InFunctionCall) {
  6719. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  6720. D << StringRange;
  6721. D << FixIt;
  6722. } else {
  6723. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  6724. << ArgumentExpr->getSourceRange();
  6725. const Sema::SemaDiagnosticBuilder &Note =
  6726. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  6727. diag::note_format_string_defined);
  6728. Note << StringRange;
  6729. Note << FixIt;
  6730. }
  6731. }
  6732. //===--- CHECK: Printf format string checking ------------------------------===//
  6733. namespace {
  6734. class CheckPrintfHandler : public CheckFormatHandler {
  6735. public:
  6736. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  6737. const Expr *origFormatExpr,
  6738. const Sema::FormatStringType type, unsigned firstDataArg,
  6739. unsigned numDataArgs, bool isObjC, const char *beg,
  6740. bool hasVAListArg, ArrayRef<const Expr *> Args,
  6741. unsigned formatIdx, bool inFunctionCall,
  6742. Sema::VariadicCallType CallType,
  6743. llvm::SmallBitVector &CheckedVarArgs,
  6744. UncoveredArgHandler &UncoveredArg)
  6745. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  6746. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  6747. inFunctionCall, CallType, CheckedVarArgs,
  6748. UncoveredArg) {}
  6749. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  6750. /// Returns true if '%@' specifiers are allowed in the format string.
  6751. bool allowsObjCArg() const {
  6752. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  6753. FSType == Sema::FST_OSTrace;
  6754. }
  6755. bool HandleInvalidPrintfConversionSpecifier(
  6756. const analyze_printf::PrintfSpecifier &FS,
  6757. const char *startSpecifier,
  6758. unsigned specifierLen) override;
  6759. void handleInvalidMaskType(StringRef MaskType) override;
  6760. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  6761. const char *startSpecifier,
  6762. unsigned specifierLen) override;
  6763. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  6764. const char *StartSpecifier,
  6765. unsigned SpecifierLen,
  6766. const Expr *E);
  6767. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  6768. const char *startSpecifier, unsigned specifierLen);
  6769. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  6770. const analyze_printf::OptionalAmount &Amt,
  6771. unsigned type,
  6772. const char *startSpecifier, unsigned specifierLen);
  6773. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6774. const analyze_printf::OptionalFlag &flag,
  6775. const char *startSpecifier, unsigned specifierLen);
  6776. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  6777. const analyze_printf::OptionalFlag &ignoredFlag,
  6778. const analyze_printf::OptionalFlag &flag,
  6779. const char *startSpecifier, unsigned specifierLen);
  6780. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  6781. const Expr *E);
  6782. void HandleEmptyObjCModifierFlag(const char *startFlag,
  6783. unsigned flagLen) override;
  6784. void HandleInvalidObjCModifierFlag(const char *startFlag,
  6785. unsigned flagLen) override;
  6786. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  6787. const char *flagsEnd,
  6788. const char *conversionPosition)
  6789. override;
  6790. };
  6791. } // namespace
  6792. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  6793. const analyze_printf::PrintfSpecifier &FS,
  6794. const char *startSpecifier,
  6795. unsigned specifierLen) {
  6796. const analyze_printf::PrintfConversionSpecifier &CS =
  6797. FS.getConversionSpecifier();
  6798. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  6799. getLocationOfByte(CS.getStart()),
  6800. startSpecifier, specifierLen,
  6801. CS.getStart(), CS.getLength());
  6802. }
  6803. void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
  6804. S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
  6805. }
  6806. bool CheckPrintfHandler::HandleAmount(
  6807. const analyze_format_string::OptionalAmount &Amt,
  6808. unsigned k, const char *startSpecifier,
  6809. unsigned specifierLen) {
  6810. if (Amt.hasDataArgument()) {
  6811. if (!HasVAListArg) {
  6812. unsigned argIndex = Amt.getArgIndex();
  6813. if (argIndex >= NumDataArgs) {
  6814. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  6815. << k,
  6816. getLocationOfByte(Amt.getStart()),
  6817. /*IsStringLocation*/true,
  6818. getSpecifierRange(startSpecifier, specifierLen));
  6819. // Don't do any more checking. We will just emit
  6820. // spurious errors.
  6821. return false;
  6822. }
  6823. // Type check the data argument. It should be an 'int'.
  6824. // Although not in conformance with C99, we also allow the argument to be
  6825. // an 'unsigned int' as that is a reasonably safe case. GCC also
  6826. // doesn't emit a warning for that case.
  6827. CoveredArgs.set(argIndex);
  6828. const Expr *Arg = getDataArg(argIndex);
  6829. if (!Arg)
  6830. return false;
  6831. QualType T = Arg->getType();
  6832. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  6833. assert(AT.isValid());
  6834. if (!AT.matchesType(S.Context, T)) {
  6835. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  6836. << k << AT.getRepresentativeTypeName(S.Context)
  6837. << T << Arg->getSourceRange(),
  6838. getLocationOfByte(Amt.getStart()),
  6839. /*IsStringLocation*/true,
  6840. getSpecifierRange(startSpecifier, specifierLen));
  6841. // Don't do any more checking. We will just emit
  6842. // spurious errors.
  6843. return false;
  6844. }
  6845. }
  6846. }
  6847. return true;
  6848. }
  6849. void CheckPrintfHandler::HandleInvalidAmount(
  6850. const analyze_printf::PrintfSpecifier &FS,
  6851. const analyze_printf::OptionalAmount &Amt,
  6852. unsigned type,
  6853. const char *startSpecifier,
  6854. unsigned specifierLen) {
  6855. const analyze_printf::PrintfConversionSpecifier &CS =
  6856. FS.getConversionSpecifier();
  6857. FixItHint fixit =
  6858. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  6859. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  6860. Amt.getConstantLength()))
  6861. : FixItHint();
  6862. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  6863. << type << CS.toString(),
  6864. getLocationOfByte(Amt.getStart()),
  6865. /*IsStringLocation*/true,
  6866. getSpecifierRange(startSpecifier, specifierLen),
  6867. fixit);
  6868. }
  6869. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6870. const analyze_printf::OptionalFlag &flag,
  6871. const char *startSpecifier,
  6872. unsigned specifierLen) {
  6873. // Warn about pointless flag with a fixit removal.
  6874. const analyze_printf::PrintfConversionSpecifier &CS =
  6875. FS.getConversionSpecifier();
  6876. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  6877. << flag.toString() << CS.toString(),
  6878. getLocationOfByte(flag.getPosition()),
  6879. /*IsStringLocation*/true,
  6880. getSpecifierRange(startSpecifier, specifierLen),
  6881. FixItHint::CreateRemoval(
  6882. getSpecifierRange(flag.getPosition(), 1)));
  6883. }
  6884. void CheckPrintfHandler::HandleIgnoredFlag(
  6885. const analyze_printf::PrintfSpecifier &FS,
  6886. const analyze_printf::OptionalFlag &ignoredFlag,
  6887. const analyze_printf::OptionalFlag &flag,
  6888. const char *startSpecifier,
  6889. unsigned specifierLen) {
  6890. // Warn about ignored flag with a fixit removal.
  6891. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  6892. << ignoredFlag.toString() << flag.toString(),
  6893. getLocationOfByte(ignoredFlag.getPosition()),
  6894. /*IsStringLocation*/true,
  6895. getSpecifierRange(startSpecifier, specifierLen),
  6896. FixItHint::CreateRemoval(
  6897. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  6898. }
  6899. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  6900. unsigned flagLen) {
  6901. // Warn about an empty flag.
  6902. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  6903. getLocationOfByte(startFlag),
  6904. /*IsStringLocation*/true,
  6905. getSpecifierRange(startFlag, flagLen));
  6906. }
  6907. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  6908. unsigned flagLen) {
  6909. // Warn about an invalid flag.
  6910. auto Range = getSpecifierRange(startFlag, flagLen);
  6911. StringRef flag(startFlag, flagLen);
  6912. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  6913. getLocationOfByte(startFlag),
  6914. /*IsStringLocation*/true,
  6915. Range, FixItHint::CreateRemoval(Range));
  6916. }
  6917. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  6918. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  6919. // Warn about using '[...]' without a '@' conversion.
  6920. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  6921. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  6922. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  6923. getLocationOfByte(conversionPosition),
  6924. /*IsStringLocation*/true,
  6925. Range, FixItHint::CreateRemoval(Range));
  6926. }
  6927. // Determines if the specified is a C++ class or struct containing
  6928. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  6929. // "c_str()").
  6930. template<typename MemberKind>
  6931. static llvm::SmallPtrSet<MemberKind*, 1>
  6932. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  6933. const RecordType *RT = Ty->getAs<RecordType>();
  6934. llvm::SmallPtrSet<MemberKind*, 1> Results;
  6935. if (!RT)
  6936. return Results;
  6937. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  6938. if (!RD || !RD->getDefinition())
  6939. return Results;
  6940. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  6941. Sema::LookupMemberName);
  6942. R.suppressDiagnostics();
  6943. // We just need to include all members of the right kind turned up by the
  6944. // filter, at this point.
  6945. if (S.LookupQualifiedName(R, RT->getDecl()))
  6946. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  6947. NamedDecl *decl = (*I)->getUnderlyingDecl();
  6948. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  6949. Results.insert(FK);
  6950. }
  6951. return Results;
  6952. }
  6953. /// Check if we could call '.c_str()' on an object.
  6954. ///
  6955. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  6956. /// allow the call, or if it would be ambiguous).
  6957. bool Sema::hasCStrMethod(const Expr *E) {
  6958. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6959. MethodSet Results =
  6960. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  6961. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6962. MI != ME; ++MI)
  6963. if ((*MI)->getMinRequiredArguments() == 0)
  6964. return true;
  6965. return false;
  6966. }
  6967. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  6968. // better diagnostic if so. AT is assumed to be valid.
  6969. // Returns true when a c_str() conversion method is found.
  6970. bool CheckPrintfHandler::checkForCStrMembers(
  6971. const analyze_printf::ArgType &AT, const Expr *E) {
  6972. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6973. MethodSet Results =
  6974. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  6975. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6976. MI != ME; ++MI) {
  6977. const CXXMethodDecl *Method = *MI;
  6978. if (Method->getMinRequiredArguments() == 0 &&
  6979. AT.matchesType(S.Context, Method->getReturnType())) {
  6980. // FIXME: Suggest parens if the expression needs them.
  6981. SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
  6982. S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
  6983. << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  6984. return true;
  6985. }
  6986. }
  6987. return false;
  6988. }
  6989. bool
  6990. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  6991. &FS,
  6992. const char *startSpecifier,
  6993. unsigned specifierLen) {
  6994. using namespace analyze_format_string;
  6995. using namespace analyze_printf;
  6996. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  6997. if (FS.consumesDataArgument()) {
  6998. if (atFirstArg) {
  6999. atFirstArg = false;
  7000. usesPositionalArgs = FS.usesPositionalArg();
  7001. }
  7002. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7003. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7004. startSpecifier, specifierLen);
  7005. return false;
  7006. }
  7007. }
  7008. // First check if the field width, precision, and conversion specifier
  7009. // have matching data arguments.
  7010. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  7011. startSpecifier, specifierLen)) {
  7012. return false;
  7013. }
  7014. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  7015. startSpecifier, specifierLen)) {
  7016. return false;
  7017. }
  7018. if (!CS.consumesDataArgument()) {
  7019. // FIXME: Technically specifying a precision or field width here
  7020. // makes no sense. Worth issuing a warning at some point.
  7021. return true;
  7022. }
  7023. // Consume the argument.
  7024. unsigned argIndex = FS.getArgIndex();
  7025. if (argIndex < NumDataArgs) {
  7026. // The check to see if the argIndex is valid will come later.
  7027. // We set the bit here because we may exit early from this
  7028. // function if we encounter some other error.
  7029. CoveredArgs.set(argIndex);
  7030. }
  7031. // FreeBSD kernel extensions.
  7032. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  7033. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  7034. // We need at least two arguments.
  7035. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  7036. return false;
  7037. // Claim the second argument.
  7038. CoveredArgs.set(argIndex + 1);
  7039. // Type check the first argument (int for %b, pointer for %D)
  7040. const Expr *Ex = getDataArg(argIndex);
  7041. const analyze_printf::ArgType &AT =
  7042. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  7043. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  7044. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  7045. EmitFormatDiagnostic(
  7046. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7047. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  7048. << false << Ex->getSourceRange(),
  7049. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7050. getSpecifierRange(startSpecifier, specifierLen));
  7051. // Type check the second argument (char * for both %b and %D)
  7052. Ex = getDataArg(argIndex + 1);
  7053. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  7054. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  7055. EmitFormatDiagnostic(
  7056. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7057. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  7058. << false << Ex->getSourceRange(),
  7059. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7060. getSpecifierRange(startSpecifier, specifierLen));
  7061. return true;
  7062. }
  7063. // Check for using an Objective-C specific conversion specifier
  7064. // in a non-ObjC literal.
  7065. if (!allowsObjCArg() && CS.isObjCArg()) {
  7066. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7067. specifierLen);
  7068. }
  7069. // %P can only be used with os_log.
  7070. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  7071. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7072. specifierLen);
  7073. }
  7074. // %n is not allowed with os_log.
  7075. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  7076. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  7077. getLocationOfByte(CS.getStart()),
  7078. /*IsStringLocation*/ false,
  7079. getSpecifierRange(startSpecifier, specifierLen));
  7080. return true;
  7081. }
  7082. // Only scalars are allowed for os_trace.
  7083. if (FSType == Sema::FST_OSTrace &&
  7084. (CS.getKind() == ConversionSpecifier::PArg ||
  7085. CS.getKind() == ConversionSpecifier::sArg ||
  7086. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  7087. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7088. specifierLen);
  7089. }
  7090. // Check for use of public/private annotation outside of os_log().
  7091. if (FSType != Sema::FST_OSLog) {
  7092. if (FS.isPublic().isSet()) {
  7093. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7094. << "public",
  7095. getLocationOfByte(FS.isPublic().getPosition()),
  7096. /*IsStringLocation*/ false,
  7097. getSpecifierRange(startSpecifier, specifierLen));
  7098. }
  7099. if (FS.isPrivate().isSet()) {
  7100. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7101. << "private",
  7102. getLocationOfByte(FS.isPrivate().getPosition()),
  7103. /*IsStringLocation*/ false,
  7104. getSpecifierRange(startSpecifier, specifierLen));
  7105. }
  7106. }
  7107. // Check for invalid use of field width
  7108. if (!FS.hasValidFieldWidth()) {
  7109. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  7110. startSpecifier, specifierLen);
  7111. }
  7112. // Check for invalid use of precision
  7113. if (!FS.hasValidPrecision()) {
  7114. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  7115. startSpecifier, specifierLen);
  7116. }
  7117. // Precision is mandatory for %P specifier.
  7118. if (CS.getKind() == ConversionSpecifier::PArg &&
  7119. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  7120. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  7121. getLocationOfByte(startSpecifier),
  7122. /*IsStringLocation*/ false,
  7123. getSpecifierRange(startSpecifier, specifierLen));
  7124. }
  7125. // Check each flag does not conflict with any other component.
  7126. if (!FS.hasValidThousandsGroupingPrefix())
  7127. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  7128. if (!FS.hasValidLeadingZeros())
  7129. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  7130. if (!FS.hasValidPlusPrefix())
  7131. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  7132. if (!FS.hasValidSpacePrefix())
  7133. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  7134. if (!FS.hasValidAlternativeForm())
  7135. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  7136. if (!FS.hasValidLeftJustified())
  7137. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  7138. // Check that flags are not ignored by another flag
  7139. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  7140. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  7141. startSpecifier, specifierLen);
  7142. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  7143. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  7144. startSpecifier, specifierLen);
  7145. // Check the length modifier is valid with the given conversion specifier.
  7146. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7147. S.getLangOpts()))
  7148. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7149. diag::warn_format_nonsensical_length);
  7150. else if (!FS.hasStandardLengthModifier())
  7151. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7152. else if (!FS.hasStandardLengthConversionCombination())
  7153. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7154. diag::warn_format_non_standard_conversion_spec);
  7155. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7156. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7157. // The remaining checks depend on the data arguments.
  7158. if (HasVAListArg)
  7159. return true;
  7160. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7161. return false;
  7162. const Expr *Arg = getDataArg(argIndex);
  7163. if (!Arg)
  7164. return true;
  7165. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  7166. }
  7167. static bool requiresParensToAddCast(const Expr *E) {
  7168. // FIXME: We should have a general way to reason about operator
  7169. // precedence and whether parens are actually needed here.
  7170. // Take care of a few common cases where they aren't.
  7171. const Expr *Inside = E->IgnoreImpCasts();
  7172. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  7173. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  7174. switch (Inside->getStmtClass()) {
  7175. case Stmt::ArraySubscriptExprClass:
  7176. case Stmt::CallExprClass:
  7177. case Stmt::CharacterLiteralClass:
  7178. case Stmt::CXXBoolLiteralExprClass:
  7179. case Stmt::DeclRefExprClass:
  7180. case Stmt::FloatingLiteralClass:
  7181. case Stmt::IntegerLiteralClass:
  7182. case Stmt::MemberExprClass:
  7183. case Stmt::ObjCArrayLiteralClass:
  7184. case Stmt::ObjCBoolLiteralExprClass:
  7185. case Stmt::ObjCBoxedExprClass:
  7186. case Stmt::ObjCDictionaryLiteralClass:
  7187. case Stmt::ObjCEncodeExprClass:
  7188. case Stmt::ObjCIvarRefExprClass:
  7189. case Stmt::ObjCMessageExprClass:
  7190. case Stmt::ObjCPropertyRefExprClass:
  7191. case Stmt::ObjCStringLiteralClass:
  7192. case Stmt::ObjCSubscriptRefExprClass:
  7193. case Stmt::ParenExprClass:
  7194. case Stmt::StringLiteralClass:
  7195. case Stmt::UnaryOperatorClass:
  7196. return false;
  7197. default:
  7198. return true;
  7199. }
  7200. }
  7201. static std::pair<QualType, StringRef>
  7202. shouldNotPrintDirectly(const ASTContext &Context,
  7203. QualType IntendedTy,
  7204. const Expr *E) {
  7205. // Use a 'while' to peel off layers of typedefs.
  7206. QualType TyTy = IntendedTy;
  7207. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  7208. StringRef Name = UserTy->getDecl()->getName();
  7209. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  7210. .Case("CFIndex", Context.getNSIntegerType())
  7211. .Case("NSInteger", Context.getNSIntegerType())
  7212. .Case("NSUInteger", Context.getNSUIntegerType())
  7213. .Case("SInt32", Context.IntTy)
  7214. .Case("UInt32", Context.UnsignedIntTy)
  7215. .Default(QualType());
  7216. if (!CastTy.isNull())
  7217. return std::make_pair(CastTy, Name);
  7218. TyTy = UserTy->desugar();
  7219. }
  7220. // Strip parens if necessary.
  7221. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  7222. return shouldNotPrintDirectly(Context,
  7223. PE->getSubExpr()->getType(),
  7224. PE->getSubExpr());
  7225. // If this is a conditional expression, then its result type is constructed
  7226. // via usual arithmetic conversions and thus there might be no necessary
  7227. // typedef sugar there. Recurse to operands to check for NSInteger &
  7228. // Co. usage condition.
  7229. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  7230. QualType TrueTy, FalseTy;
  7231. StringRef TrueName, FalseName;
  7232. std::tie(TrueTy, TrueName) =
  7233. shouldNotPrintDirectly(Context,
  7234. CO->getTrueExpr()->getType(),
  7235. CO->getTrueExpr());
  7236. std::tie(FalseTy, FalseName) =
  7237. shouldNotPrintDirectly(Context,
  7238. CO->getFalseExpr()->getType(),
  7239. CO->getFalseExpr());
  7240. if (TrueTy == FalseTy)
  7241. return std::make_pair(TrueTy, TrueName);
  7242. else if (TrueTy.isNull())
  7243. return std::make_pair(FalseTy, FalseName);
  7244. else if (FalseTy.isNull())
  7245. return std::make_pair(TrueTy, TrueName);
  7246. }
  7247. return std::make_pair(QualType(), StringRef());
  7248. }
  7249. /// Return true if \p ICE is an implicit argument promotion of an arithmetic
  7250. /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
  7251. /// type do not count.
  7252. static bool
  7253. isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
  7254. QualType From = ICE->getSubExpr()->getType();
  7255. QualType To = ICE->getType();
  7256. // It's an integer promotion if the destination type is the promoted
  7257. // source type.
  7258. if (ICE->getCastKind() == CK_IntegralCast &&
  7259. From->isPromotableIntegerType() &&
  7260. S.Context.getPromotedIntegerType(From) == To)
  7261. return true;
  7262. // Look through vector types, since we do default argument promotion for
  7263. // those in OpenCL.
  7264. if (const auto *VecTy = From->getAs<ExtVectorType>())
  7265. From = VecTy->getElementType();
  7266. if (const auto *VecTy = To->getAs<ExtVectorType>())
  7267. To = VecTy->getElementType();
  7268. // It's a floating promotion if the source type is a lower rank.
  7269. return ICE->getCastKind() == CK_FloatingCast &&
  7270. S.Context.getFloatingTypeOrder(From, To) < 0;
  7271. }
  7272. bool
  7273. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  7274. const char *StartSpecifier,
  7275. unsigned SpecifierLen,
  7276. const Expr *E) {
  7277. using namespace analyze_format_string;
  7278. using namespace analyze_printf;
  7279. // Now type check the data expression that matches the
  7280. // format specifier.
  7281. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  7282. if (!AT.isValid())
  7283. return true;
  7284. QualType ExprTy = E->getType();
  7285. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  7286. ExprTy = TET->getUnderlyingExpr()->getType();
  7287. }
  7288. const analyze_printf::ArgType::MatchKind Match =
  7289. AT.matchesType(S.Context, ExprTy);
  7290. bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
  7291. if (Match == analyze_printf::ArgType::Match)
  7292. return true;
  7293. // Look through argument promotions for our error message's reported type.
  7294. // This includes the integral and floating promotions, but excludes array
  7295. // and function pointer decay (seeing that an argument intended to be a
  7296. // string has type 'char [6]' is probably more confusing than 'char *') and
  7297. // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
  7298. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  7299. if (isArithmeticArgumentPromotion(S, ICE)) {
  7300. E = ICE->getSubExpr();
  7301. ExprTy = E->getType();
  7302. // Check if we didn't match because of an implicit cast from a 'char'
  7303. // or 'short' to an 'int'. This is done because printf is a varargs
  7304. // function.
  7305. if (ICE->getType() == S.Context.IntTy ||
  7306. ICE->getType() == S.Context.UnsignedIntTy) {
  7307. // All further checking is done on the subexpression.
  7308. if (AT.matchesType(S.Context, ExprTy))
  7309. return true;
  7310. }
  7311. }
  7312. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  7313. // Special case for 'a', which has type 'int' in C.
  7314. // Note, however, that we do /not/ want to treat multibyte constants like
  7315. // 'MooV' as characters! This form is deprecated but still exists.
  7316. if (ExprTy == S.Context.IntTy)
  7317. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  7318. ExprTy = S.Context.CharTy;
  7319. }
  7320. // Look through enums to their underlying type.
  7321. bool IsEnum = false;
  7322. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  7323. ExprTy = EnumTy->getDecl()->getIntegerType();
  7324. IsEnum = true;
  7325. }
  7326. // %C in an Objective-C context prints a unichar, not a wchar_t.
  7327. // If the argument is an integer of some kind, believe the %C and suggest
  7328. // a cast instead of changing the conversion specifier.
  7329. QualType IntendedTy = ExprTy;
  7330. if (isObjCContext() &&
  7331. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  7332. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  7333. !ExprTy->isCharType()) {
  7334. // 'unichar' is defined as a typedef of unsigned short, but we should
  7335. // prefer using the typedef if it is visible.
  7336. IntendedTy = S.Context.UnsignedShortTy;
  7337. // While we are here, check if the value is an IntegerLiteral that happens
  7338. // to be within the valid range.
  7339. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  7340. const llvm::APInt &V = IL->getValue();
  7341. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  7342. return true;
  7343. }
  7344. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
  7345. Sema::LookupOrdinaryName);
  7346. if (S.LookupName(Result, S.getCurScope())) {
  7347. NamedDecl *ND = Result.getFoundDecl();
  7348. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  7349. if (TD->getUnderlyingType() == IntendedTy)
  7350. IntendedTy = S.Context.getTypedefType(TD);
  7351. }
  7352. }
  7353. }
  7354. // Special-case some of Darwin's platform-independence types by suggesting
  7355. // casts to primitive types that are known to be large enough.
  7356. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  7357. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  7358. QualType CastTy;
  7359. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  7360. if (!CastTy.isNull()) {
  7361. // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
  7362. // (long in ASTContext). Only complain to pedants.
  7363. if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
  7364. (AT.isSizeT() || AT.isPtrdiffT()) &&
  7365. AT.matchesType(S.Context, CastTy))
  7366. Pedantic = true;
  7367. IntendedTy = CastTy;
  7368. ShouldNotPrintDirectly = true;
  7369. }
  7370. }
  7371. // We may be able to offer a FixItHint if it is a supported type.
  7372. PrintfSpecifier fixedFS = FS;
  7373. bool Success =
  7374. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  7375. if (Success) {
  7376. // Get the fix string from the fixed format specifier
  7377. SmallString<16> buf;
  7378. llvm::raw_svector_ostream os(buf);
  7379. fixedFS.toString(os);
  7380. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  7381. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  7382. unsigned Diag =
  7383. Pedantic
  7384. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7385. : diag::warn_format_conversion_argument_type_mismatch;
  7386. // In this case, the specifier is wrong and should be changed to match
  7387. // the argument.
  7388. EmitFormatDiagnostic(S.PDiag(Diag)
  7389. << AT.getRepresentativeTypeName(S.Context)
  7390. << IntendedTy << IsEnum << E->getSourceRange(),
  7391. E->getBeginLoc(),
  7392. /*IsStringLocation*/ false, SpecRange,
  7393. FixItHint::CreateReplacement(SpecRange, os.str()));
  7394. } else {
  7395. // The canonical type for formatting this value is different from the
  7396. // actual type of the expression. (This occurs, for example, with Darwin's
  7397. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  7398. // should be printed as 'long' for 64-bit compatibility.)
  7399. // Rather than emitting a normal format/argument mismatch, we want to
  7400. // add a cast to the recommended type (and correct the format string
  7401. // if necessary).
  7402. SmallString<16> CastBuf;
  7403. llvm::raw_svector_ostream CastFix(CastBuf);
  7404. CastFix << "(";
  7405. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  7406. CastFix << ")";
  7407. SmallVector<FixItHint,4> Hints;
  7408. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  7409. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  7410. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  7411. // If there's already a cast present, just replace it.
  7412. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  7413. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  7414. } else if (!requiresParensToAddCast(E)) {
  7415. // If the expression has high enough precedence,
  7416. // just write the C-style cast.
  7417. Hints.push_back(
  7418. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7419. } else {
  7420. // Otherwise, add parens around the expression as well as the cast.
  7421. CastFix << "(";
  7422. Hints.push_back(
  7423. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7424. SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
  7425. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  7426. }
  7427. if (ShouldNotPrintDirectly) {
  7428. // The expression has a type that should not be printed directly.
  7429. // We extract the name from the typedef because we don't want to show
  7430. // the underlying type in the diagnostic.
  7431. StringRef Name;
  7432. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  7433. Name = TypedefTy->getDecl()->getName();
  7434. else
  7435. Name = CastTyName;
  7436. unsigned Diag = Pedantic
  7437. ? diag::warn_format_argument_needs_cast_pedantic
  7438. : diag::warn_format_argument_needs_cast;
  7439. EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
  7440. << E->getSourceRange(),
  7441. E->getBeginLoc(), /*IsStringLocation=*/false,
  7442. SpecRange, Hints);
  7443. } else {
  7444. // In this case, the expression could be printed using a different
  7445. // specifier, but we've decided that the specifier is probably correct
  7446. // and we should cast instead. Just use the normal warning message.
  7447. EmitFormatDiagnostic(
  7448. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7449. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  7450. << E->getSourceRange(),
  7451. E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
  7452. }
  7453. }
  7454. } else {
  7455. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  7456. SpecifierLen);
  7457. // Since the warning for passing non-POD types to variadic functions
  7458. // was deferred until now, we emit a warning for non-POD
  7459. // arguments here.
  7460. switch (S.isValidVarArgType(ExprTy)) {
  7461. case Sema::VAK_Valid:
  7462. case Sema::VAK_ValidInCXX11: {
  7463. unsigned Diag =
  7464. Pedantic
  7465. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7466. : diag::warn_format_conversion_argument_type_mismatch;
  7467. EmitFormatDiagnostic(
  7468. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  7469. << IsEnum << CSR << E->getSourceRange(),
  7470. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7471. break;
  7472. }
  7473. case Sema::VAK_Undefined:
  7474. case Sema::VAK_MSVCUndefined:
  7475. EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  7476. << S.getLangOpts().CPlusPlus11 << ExprTy
  7477. << CallType
  7478. << AT.getRepresentativeTypeName(S.Context) << CSR
  7479. << E->getSourceRange(),
  7480. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7481. checkForCStrMembers(AT, E);
  7482. break;
  7483. case Sema::VAK_Invalid:
  7484. if (ExprTy->isObjCObjectType())
  7485. EmitFormatDiagnostic(
  7486. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  7487. << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
  7488. << AT.getRepresentativeTypeName(S.Context) << CSR
  7489. << E->getSourceRange(),
  7490. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7491. else
  7492. // FIXME: If this is an initializer list, suggest removing the braces
  7493. // or inserting a cast to the target type.
  7494. S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
  7495. << isa<InitListExpr>(E) << ExprTy << CallType
  7496. << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
  7497. break;
  7498. }
  7499. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  7500. "format string specifier index out of range");
  7501. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  7502. }
  7503. return true;
  7504. }
  7505. //===--- CHECK: Scanf format string checking ------------------------------===//
  7506. namespace {
  7507. class CheckScanfHandler : public CheckFormatHandler {
  7508. public:
  7509. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  7510. const Expr *origFormatExpr, Sema::FormatStringType type,
  7511. unsigned firstDataArg, unsigned numDataArgs,
  7512. const char *beg, bool hasVAListArg,
  7513. ArrayRef<const Expr *> Args, unsigned formatIdx,
  7514. bool inFunctionCall, Sema::VariadicCallType CallType,
  7515. llvm::SmallBitVector &CheckedVarArgs,
  7516. UncoveredArgHandler &UncoveredArg)
  7517. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  7518. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  7519. inFunctionCall, CallType, CheckedVarArgs,
  7520. UncoveredArg) {}
  7521. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  7522. const char *startSpecifier,
  7523. unsigned specifierLen) override;
  7524. bool HandleInvalidScanfConversionSpecifier(
  7525. const analyze_scanf::ScanfSpecifier &FS,
  7526. const char *startSpecifier,
  7527. unsigned specifierLen) override;
  7528. void HandleIncompleteScanList(const char *start, const char *end) override;
  7529. };
  7530. } // namespace
  7531. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  7532. const char *end) {
  7533. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  7534. getLocationOfByte(end), /*IsStringLocation*/true,
  7535. getSpecifierRange(start, end - start));
  7536. }
  7537. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  7538. const analyze_scanf::ScanfSpecifier &FS,
  7539. const char *startSpecifier,
  7540. unsigned specifierLen) {
  7541. const analyze_scanf::ScanfConversionSpecifier &CS =
  7542. FS.getConversionSpecifier();
  7543. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  7544. getLocationOfByte(CS.getStart()),
  7545. startSpecifier, specifierLen,
  7546. CS.getStart(), CS.getLength());
  7547. }
  7548. bool CheckScanfHandler::HandleScanfSpecifier(
  7549. const analyze_scanf::ScanfSpecifier &FS,
  7550. const char *startSpecifier,
  7551. unsigned specifierLen) {
  7552. using namespace analyze_scanf;
  7553. using namespace analyze_format_string;
  7554. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  7555. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  7556. // be used to decide if we are using positional arguments consistently.
  7557. if (FS.consumesDataArgument()) {
  7558. if (atFirstArg) {
  7559. atFirstArg = false;
  7560. usesPositionalArgs = FS.usesPositionalArg();
  7561. }
  7562. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7563. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7564. startSpecifier, specifierLen);
  7565. return false;
  7566. }
  7567. }
  7568. // Check if the field with is non-zero.
  7569. const OptionalAmount &Amt = FS.getFieldWidth();
  7570. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  7571. if (Amt.getConstantAmount() == 0) {
  7572. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  7573. Amt.getConstantLength());
  7574. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  7575. getLocationOfByte(Amt.getStart()),
  7576. /*IsStringLocation*/true, R,
  7577. FixItHint::CreateRemoval(R));
  7578. }
  7579. }
  7580. if (!FS.consumesDataArgument()) {
  7581. // FIXME: Technically specifying a precision or field width here
  7582. // makes no sense. Worth issuing a warning at some point.
  7583. return true;
  7584. }
  7585. // Consume the argument.
  7586. unsigned argIndex = FS.getArgIndex();
  7587. if (argIndex < NumDataArgs) {
  7588. // The check to see if the argIndex is valid will come later.
  7589. // We set the bit here because we may exit early from this
  7590. // function if we encounter some other error.
  7591. CoveredArgs.set(argIndex);
  7592. }
  7593. // Check the length modifier is valid with the given conversion specifier.
  7594. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7595. S.getLangOpts()))
  7596. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7597. diag::warn_format_nonsensical_length);
  7598. else if (!FS.hasStandardLengthModifier())
  7599. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7600. else if (!FS.hasStandardLengthConversionCombination())
  7601. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7602. diag::warn_format_non_standard_conversion_spec);
  7603. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7604. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7605. // The remaining checks depend on the data arguments.
  7606. if (HasVAListArg)
  7607. return true;
  7608. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7609. return false;
  7610. // Check that the argument type matches the format specifier.
  7611. const Expr *Ex = getDataArg(argIndex);
  7612. if (!Ex)
  7613. return true;
  7614. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  7615. if (!AT.isValid()) {
  7616. return true;
  7617. }
  7618. analyze_format_string::ArgType::MatchKind Match =
  7619. AT.matchesType(S.Context, Ex->getType());
  7620. bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
  7621. if (Match == analyze_format_string::ArgType::Match)
  7622. return true;
  7623. ScanfSpecifier fixedFS = FS;
  7624. bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  7625. S.getLangOpts(), S.Context);
  7626. unsigned Diag =
  7627. Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7628. : diag::warn_format_conversion_argument_type_mismatch;
  7629. if (Success) {
  7630. // Get the fix string from the fixed format specifier.
  7631. SmallString<128> buf;
  7632. llvm::raw_svector_ostream os(buf);
  7633. fixedFS.toString(os);
  7634. EmitFormatDiagnostic(
  7635. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
  7636. << Ex->getType() << false << Ex->getSourceRange(),
  7637. Ex->getBeginLoc(),
  7638. /*IsStringLocation*/ false,
  7639. getSpecifierRange(startSpecifier, specifierLen),
  7640. FixItHint::CreateReplacement(
  7641. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  7642. } else {
  7643. EmitFormatDiagnostic(S.PDiag(Diag)
  7644. << AT.getRepresentativeTypeName(S.Context)
  7645. << Ex->getType() << false << Ex->getSourceRange(),
  7646. Ex->getBeginLoc(),
  7647. /*IsStringLocation*/ false,
  7648. getSpecifierRange(startSpecifier, specifierLen));
  7649. }
  7650. return true;
  7651. }
  7652. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  7653. const Expr *OrigFormatExpr,
  7654. ArrayRef<const Expr *> Args,
  7655. bool HasVAListArg, unsigned format_idx,
  7656. unsigned firstDataArg,
  7657. Sema::FormatStringType Type,
  7658. bool inFunctionCall,
  7659. Sema::VariadicCallType CallType,
  7660. llvm::SmallBitVector &CheckedVarArgs,
  7661. UncoveredArgHandler &UncoveredArg) {
  7662. // CHECK: is the format string a wide literal?
  7663. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  7664. CheckFormatHandler::EmitFormatDiagnostic(
  7665. S, inFunctionCall, Args[format_idx],
  7666. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
  7667. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7668. return;
  7669. }
  7670. // Str - The format string. NOTE: this is NOT null-terminated!
  7671. StringRef StrRef = FExpr->getString();
  7672. const char *Str = StrRef.data();
  7673. // Account for cases where the string literal is truncated in a declaration.
  7674. const ConstantArrayType *T =
  7675. S.Context.getAsConstantArrayType(FExpr->getType());
  7676. assert(T && "String literal not of constant array type!");
  7677. size_t TypeSize = T->getSize().getZExtValue();
  7678. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7679. const unsigned numDataArgs = Args.size() - firstDataArg;
  7680. // Emit a warning if the string literal is truncated and does not contain an
  7681. // embedded null character.
  7682. if (TypeSize <= StrRef.size() &&
  7683. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  7684. CheckFormatHandler::EmitFormatDiagnostic(
  7685. S, inFunctionCall, Args[format_idx],
  7686. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  7687. FExpr->getBeginLoc(),
  7688. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  7689. return;
  7690. }
  7691. // CHECK: empty format string?
  7692. if (StrLen == 0 && numDataArgs > 0) {
  7693. CheckFormatHandler::EmitFormatDiagnostic(
  7694. S, inFunctionCall, Args[format_idx],
  7695. S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
  7696. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7697. return;
  7698. }
  7699. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  7700. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  7701. Type == Sema::FST_OSTrace) {
  7702. CheckPrintfHandler H(
  7703. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  7704. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  7705. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  7706. CheckedVarArgs, UncoveredArg);
  7707. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  7708. S.getLangOpts(),
  7709. S.Context.getTargetInfo(),
  7710. Type == Sema::FST_FreeBSDKPrintf))
  7711. H.DoneProcessing();
  7712. } else if (Type == Sema::FST_Scanf) {
  7713. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  7714. numDataArgs, Str, HasVAListArg, Args, format_idx,
  7715. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  7716. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  7717. S.getLangOpts(),
  7718. S.Context.getTargetInfo()))
  7719. H.DoneProcessing();
  7720. } // TODO: handle other formats
  7721. }
  7722. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  7723. // Str - The format string. NOTE: this is NOT null-terminated!
  7724. StringRef StrRef = FExpr->getString();
  7725. const char *Str = StrRef.data();
  7726. // Account for cases where the string literal is truncated in a declaration.
  7727. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  7728. assert(T && "String literal not of constant array type!");
  7729. size_t TypeSize = T->getSize().getZExtValue();
  7730. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7731. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  7732. getLangOpts(),
  7733. Context.getTargetInfo());
  7734. }
  7735. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  7736. // Returns the related absolute value function that is larger, of 0 if one
  7737. // does not exist.
  7738. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  7739. switch (AbsFunction) {
  7740. default:
  7741. return 0;
  7742. case Builtin::BI__builtin_abs:
  7743. return Builtin::BI__builtin_labs;
  7744. case Builtin::BI__builtin_labs:
  7745. return Builtin::BI__builtin_llabs;
  7746. case Builtin::BI__builtin_llabs:
  7747. return 0;
  7748. case Builtin::BI__builtin_fabsf:
  7749. return Builtin::BI__builtin_fabs;
  7750. case Builtin::BI__builtin_fabs:
  7751. return Builtin::BI__builtin_fabsl;
  7752. case Builtin::BI__builtin_fabsl:
  7753. return 0;
  7754. case Builtin::BI__builtin_cabsf:
  7755. return Builtin::BI__builtin_cabs;
  7756. case Builtin::BI__builtin_cabs:
  7757. return Builtin::BI__builtin_cabsl;
  7758. case Builtin::BI__builtin_cabsl:
  7759. return 0;
  7760. case Builtin::BIabs:
  7761. return Builtin::BIlabs;
  7762. case Builtin::BIlabs:
  7763. return Builtin::BIllabs;
  7764. case Builtin::BIllabs:
  7765. return 0;
  7766. case Builtin::BIfabsf:
  7767. return Builtin::BIfabs;
  7768. case Builtin::BIfabs:
  7769. return Builtin::BIfabsl;
  7770. case Builtin::BIfabsl:
  7771. return 0;
  7772. case Builtin::BIcabsf:
  7773. return Builtin::BIcabs;
  7774. case Builtin::BIcabs:
  7775. return Builtin::BIcabsl;
  7776. case Builtin::BIcabsl:
  7777. return 0;
  7778. }
  7779. }
  7780. // Returns the argument type of the absolute value function.
  7781. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  7782. unsigned AbsType) {
  7783. if (AbsType == 0)
  7784. return QualType();
  7785. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  7786. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  7787. if (Error != ASTContext::GE_None)
  7788. return QualType();
  7789. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  7790. if (!FT)
  7791. return QualType();
  7792. if (FT->getNumParams() != 1)
  7793. return QualType();
  7794. return FT->getParamType(0);
  7795. }
  7796. // Returns the best absolute value function, or zero, based on type and
  7797. // current absolute value function.
  7798. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  7799. unsigned AbsFunctionKind) {
  7800. unsigned BestKind = 0;
  7801. uint64_t ArgSize = Context.getTypeSize(ArgType);
  7802. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  7803. Kind = getLargerAbsoluteValueFunction(Kind)) {
  7804. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  7805. if (Context.getTypeSize(ParamType) >= ArgSize) {
  7806. if (BestKind == 0)
  7807. BestKind = Kind;
  7808. else if (Context.hasSameType(ParamType, ArgType)) {
  7809. BestKind = Kind;
  7810. break;
  7811. }
  7812. }
  7813. }
  7814. return BestKind;
  7815. }
  7816. enum AbsoluteValueKind {
  7817. AVK_Integer,
  7818. AVK_Floating,
  7819. AVK_Complex
  7820. };
  7821. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  7822. if (T->isIntegralOrEnumerationType())
  7823. return AVK_Integer;
  7824. if (T->isRealFloatingType())
  7825. return AVK_Floating;
  7826. if (T->isAnyComplexType())
  7827. return AVK_Complex;
  7828. llvm_unreachable("Type not integer, floating, or complex");
  7829. }
  7830. // Changes the absolute value function to a different type. Preserves whether
  7831. // the function is a builtin.
  7832. static unsigned changeAbsFunction(unsigned AbsKind,
  7833. AbsoluteValueKind ValueKind) {
  7834. switch (ValueKind) {
  7835. case AVK_Integer:
  7836. switch (AbsKind) {
  7837. default:
  7838. return 0;
  7839. case Builtin::BI__builtin_fabsf:
  7840. case Builtin::BI__builtin_fabs:
  7841. case Builtin::BI__builtin_fabsl:
  7842. case Builtin::BI__builtin_cabsf:
  7843. case Builtin::BI__builtin_cabs:
  7844. case Builtin::BI__builtin_cabsl:
  7845. return Builtin::BI__builtin_abs;
  7846. case Builtin::BIfabsf:
  7847. case Builtin::BIfabs:
  7848. case Builtin::BIfabsl:
  7849. case Builtin::BIcabsf:
  7850. case Builtin::BIcabs:
  7851. case Builtin::BIcabsl:
  7852. return Builtin::BIabs;
  7853. }
  7854. case AVK_Floating:
  7855. switch (AbsKind) {
  7856. default:
  7857. return 0;
  7858. case Builtin::BI__builtin_abs:
  7859. case Builtin::BI__builtin_labs:
  7860. case Builtin::BI__builtin_llabs:
  7861. case Builtin::BI__builtin_cabsf:
  7862. case Builtin::BI__builtin_cabs:
  7863. case Builtin::BI__builtin_cabsl:
  7864. return Builtin::BI__builtin_fabsf;
  7865. case Builtin::BIabs:
  7866. case Builtin::BIlabs:
  7867. case Builtin::BIllabs:
  7868. case Builtin::BIcabsf:
  7869. case Builtin::BIcabs:
  7870. case Builtin::BIcabsl:
  7871. return Builtin::BIfabsf;
  7872. }
  7873. case AVK_Complex:
  7874. switch (AbsKind) {
  7875. default:
  7876. return 0;
  7877. case Builtin::BI__builtin_abs:
  7878. case Builtin::BI__builtin_labs:
  7879. case Builtin::BI__builtin_llabs:
  7880. case Builtin::BI__builtin_fabsf:
  7881. case Builtin::BI__builtin_fabs:
  7882. case Builtin::BI__builtin_fabsl:
  7883. return Builtin::BI__builtin_cabsf;
  7884. case Builtin::BIabs:
  7885. case Builtin::BIlabs:
  7886. case Builtin::BIllabs:
  7887. case Builtin::BIfabsf:
  7888. case Builtin::BIfabs:
  7889. case Builtin::BIfabsl:
  7890. return Builtin::BIcabsf;
  7891. }
  7892. }
  7893. llvm_unreachable("Unable to convert function");
  7894. }
  7895. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  7896. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  7897. if (!FnInfo)
  7898. return 0;
  7899. switch (FDecl->getBuiltinID()) {
  7900. default:
  7901. return 0;
  7902. case Builtin::BI__builtin_abs:
  7903. case Builtin::BI__builtin_fabs:
  7904. case Builtin::BI__builtin_fabsf:
  7905. case Builtin::BI__builtin_fabsl:
  7906. case Builtin::BI__builtin_labs:
  7907. case Builtin::BI__builtin_llabs:
  7908. case Builtin::BI__builtin_cabs:
  7909. case Builtin::BI__builtin_cabsf:
  7910. case Builtin::BI__builtin_cabsl:
  7911. case Builtin::BIabs:
  7912. case Builtin::BIlabs:
  7913. case Builtin::BIllabs:
  7914. case Builtin::BIfabs:
  7915. case Builtin::BIfabsf:
  7916. case Builtin::BIfabsl:
  7917. case Builtin::BIcabs:
  7918. case Builtin::BIcabsf:
  7919. case Builtin::BIcabsl:
  7920. return FDecl->getBuiltinID();
  7921. }
  7922. llvm_unreachable("Unknown Builtin type");
  7923. }
  7924. // If the replacement is valid, emit a note with replacement function.
  7925. // Additionally, suggest including the proper header if not already included.
  7926. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  7927. unsigned AbsKind, QualType ArgType) {
  7928. bool EmitHeaderHint = true;
  7929. const char *HeaderName = nullptr;
  7930. const char *FunctionName = nullptr;
  7931. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  7932. FunctionName = "std::abs";
  7933. if (ArgType->isIntegralOrEnumerationType()) {
  7934. HeaderName = "cstdlib";
  7935. } else if (ArgType->isRealFloatingType()) {
  7936. HeaderName = "cmath";
  7937. } else {
  7938. llvm_unreachable("Invalid Type");
  7939. }
  7940. // Lookup all std::abs
  7941. if (NamespaceDecl *Std = S.getStdNamespace()) {
  7942. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  7943. R.suppressDiagnostics();
  7944. S.LookupQualifiedName(R, Std);
  7945. for (const auto *I : R) {
  7946. const FunctionDecl *FDecl = nullptr;
  7947. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  7948. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  7949. } else {
  7950. FDecl = dyn_cast<FunctionDecl>(I);
  7951. }
  7952. if (!FDecl)
  7953. continue;
  7954. // Found std::abs(), check that they are the right ones.
  7955. if (FDecl->getNumParams() != 1)
  7956. continue;
  7957. // Check that the parameter type can handle the argument.
  7958. QualType ParamType = FDecl->getParamDecl(0)->getType();
  7959. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  7960. S.Context.getTypeSize(ArgType) <=
  7961. S.Context.getTypeSize(ParamType)) {
  7962. // Found a function, don't need the header hint.
  7963. EmitHeaderHint = false;
  7964. break;
  7965. }
  7966. }
  7967. }
  7968. } else {
  7969. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  7970. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  7971. if (HeaderName) {
  7972. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  7973. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  7974. R.suppressDiagnostics();
  7975. S.LookupName(R, S.getCurScope());
  7976. if (R.isSingleResult()) {
  7977. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  7978. if (FD && FD->getBuiltinID() == AbsKind) {
  7979. EmitHeaderHint = false;
  7980. } else {
  7981. return;
  7982. }
  7983. } else if (!R.empty()) {
  7984. return;
  7985. }
  7986. }
  7987. }
  7988. S.Diag(Loc, diag::note_replace_abs_function)
  7989. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  7990. if (!HeaderName)
  7991. return;
  7992. if (!EmitHeaderHint)
  7993. return;
  7994. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  7995. << FunctionName;
  7996. }
  7997. template <std::size_t StrLen>
  7998. static bool IsStdFunction(const FunctionDecl *FDecl,
  7999. const char (&Str)[StrLen]) {
  8000. if (!FDecl)
  8001. return false;
  8002. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  8003. return false;
  8004. if (!FDecl->isInStdNamespace())
  8005. return false;
  8006. return true;
  8007. }
  8008. // Warn when using the wrong abs() function.
  8009. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  8010. const FunctionDecl *FDecl) {
  8011. if (Call->getNumArgs() != 1)
  8012. return;
  8013. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  8014. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  8015. if (AbsKind == 0 && !IsStdAbs)
  8016. return;
  8017. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8018. QualType ParamType = Call->getArg(0)->getType();
  8019. // Unsigned types cannot be negative. Suggest removing the absolute value
  8020. // function call.
  8021. if (ArgType->isUnsignedIntegerType()) {
  8022. const char *FunctionName =
  8023. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  8024. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  8025. Diag(Call->getExprLoc(), diag::note_remove_abs)
  8026. << FunctionName
  8027. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  8028. return;
  8029. }
  8030. // Taking the absolute value of a pointer is very suspicious, they probably
  8031. // wanted to index into an array, dereference a pointer, call a function, etc.
  8032. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  8033. unsigned DiagType = 0;
  8034. if (ArgType->isFunctionType())
  8035. DiagType = 1;
  8036. else if (ArgType->isArrayType())
  8037. DiagType = 2;
  8038. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  8039. return;
  8040. }
  8041. // std::abs has overloads which prevent most of the absolute value problems
  8042. // from occurring.
  8043. if (IsStdAbs)
  8044. return;
  8045. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  8046. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  8047. // The argument and parameter are the same kind. Check if they are the right
  8048. // size.
  8049. if (ArgValueKind == ParamValueKind) {
  8050. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  8051. return;
  8052. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  8053. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  8054. << FDecl << ArgType << ParamType;
  8055. if (NewAbsKind == 0)
  8056. return;
  8057. emitReplacement(*this, Call->getExprLoc(),
  8058. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8059. return;
  8060. }
  8061. // ArgValueKind != ParamValueKind
  8062. // The wrong type of absolute value function was used. Attempt to find the
  8063. // proper one.
  8064. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  8065. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  8066. if (NewAbsKind == 0)
  8067. return;
  8068. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  8069. << FDecl << ParamValueKind << ArgValueKind;
  8070. emitReplacement(*this, Call->getExprLoc(),
  8071. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8072. }
  8073. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  8074. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  8075. const FunctionDecl *FDecl) {
  8076. if (!Call || !FDecl) return;
  8077. // Ignore template specializations and macros.
  8078. if (inTemplateInstantiation()) return;
  8079. if (Call->getExprLoc().isMacroID()) return;
  8080. // Only care about the one template argument, two function parameter std::max
  8081. if (Call->getNumArgs() != 2) return;
  8082. if (!IsStdFunction(FDecl, "max")) return;
  8083. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  8084. if (!ArgList) return;
  8085. if (ArgList->size() != 1) return;
  8086. // Check that template type argument is unsigned integer.
  8087. const auto& TA = ArgList->get(0);
  8088. if (TA.getKind() != TemplateArgument::Type) return;
  8089. QualType ArgType = TA.getAsType();
  8090. if (!ArgType->isUnsignedIntegerType()) return;
  8091. // See if either argument is a literal zero.
  8092. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  8093. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  8094. if (!MTE) return false;
  8095. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  8096. if (!Num) return false;
  8097. if (Num->getValue() != 0) return false;
  8098. return true;
  8099. };
  8100. const Expr *FirstArg = Call->getArg(0);
  8101. const Expr *SecondArg = Call->getArg(1);
  8102. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  8103. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  8104. // Only warn when exactly one argument is zero.
  8105. if (IsFirstArgZero == IsSecondArgZero) return;
  8106. SourceRange FirstRange = FirstArg->getSourceRange();
  8107. SourceRange SecondRange = SecondArg->getSourceRange();
  8108. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  8109. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  8110. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  8111. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  8112. SourceRange RemovalRange;
  8113. if (IsFirstArgZero) {
  8114. RemovalRange = SourceRange(FirstRange.getBegin(),
  8115. SecondRange.getBegin().getLocWithOffset(-1));
  8116. } else {
  8117. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  8118. SecondRange.getEnd());
  8119. }
  8120. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  8121. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  8122. << FixItHint::CreateRemoval(RemovalRange);
  8123. }
  8124. //===--- CHECK: Standard memory functions ---------------------------------===//
  8125. /// Takes the expression passed to the size_t parameter of functions
  8126. /// such as memcmp, strncat, etc and warns if it's a comparison.
  8127. ///
  8128. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  8129. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  8130. IdentifierInfo *FnName,
  8131. SourceLocation FnLoc,
  8132. SourceLocation RParenLoc) {
  8133. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  8134. if (!Size)
  8135. return false;
  8136. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  8137. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  8138. return false;
  8139. SourceRange SizeRange = Size->getSourceRange();
  8140. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  8141. << SizeRange << FnName;
  8142. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  8143. << FnName
  8144. << FixItHint::CreateInsertion(
  8145. S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
  8146. << FixItHint::CreateRemoval(RParenLoc);
  8147. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  8148. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  8149. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  8150. ")");
  8151. return true;
  8152. }
  8153. /// Determine whether the given type is or contains a dynamic class type
  8154. /// (e.g., whether it has a vtable).
  8155. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  8156. bool &IsContained) {
  8157. // Look through array types while ignoring qualifiers.
  8158. const Type *Ty = T->getBaseElementTypeUnsafe();
  8159. IsContained = false;
  8160. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  8161. RD = RD ? RD->getDefinition() : nullptr;
  8162. if (!RD || RD->isInvalidDecl())
  8163. return nullptr;
  8164. if (RD->isDynamicClass())
  8165. return RD;
  8166. // Check all the fields. If any bases were dynamic, the class is dynamic.
  8167. // It's impossible for a class to transitively contain itself by value, so
  8168. // infinite recursion is impossible.
  8169. for (auto *FD : RD->fields()) {
  8170. bool SubContained;
  8171. if (const CXXRecordDecl *ContainedRD =
  8172. getContainedDynamicClass(FD->getType(), SubContained)) {
  8173. IsContained = true;
  8174. return ContainedRD;
  8175. }
  8176. }
  8177. return nullptr;
  8178. }
  8179. static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
  8180. if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  8181. if (Unary->getKind() == UETT_SizeOf)
  8182. return Unary;
  8183. return nullptr;
  8184. }
  8185. /// If E is a sizeof expression, returns its argument expression,
  8186. /// otherwise returns NULL.
  8187. static const Expr *getSizeOfExprArg(const Expr *E) {
  8188. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8189. if (!SizeOf->isArgumentType())
  8190. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  8191. return nullptr;
  8192. }
  8193. /// If E is a sizeof expression, returns its argument type.
  8194. static QualType getSizeOfArgType(const Expr *E) {
  8195. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8196. return SizeOf->getTypeOfArgument();
  8197. return QualType();
  8198. }
  8199. namespace {
  8200. struct SearchNonTrivialToInitializeField
  8201. : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
  8202. using Super =
  8203. DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
  8204. SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
  8205. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
  8206. SourceLocation SL) {
  8207. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8208. asDerived().visitArray(PDIK, AT, SL);
  8209. return;
  8210. }
  8211. Super::visitWithKind(PDIK, FT, SL);
  8212. }
  8213. void visitARCStrong(QualType FT, SourceLocation SL) {
  8214. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8215. }
  8216. void visitARCWeak(QualType FT, SourceLocation SL) {
  8217. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8218. }
  8219. void visitStruct(QualType FT, SourceLocation SL) {
  8220. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8221. visit(FD->getType(), FD->getLocation());
  8222. }
  8223. void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
  8224. const ArrayType *AT, SourceLocation SL) {
  8225. visit(getContext().getBaseElementType(AT), SL);
  8226. }
  8227. void visitTrivial(QualType FT, SourceLocation SL) {}
  8228. static void diag(QualType RT, const Expr *E, Sema &S) {
  8229. SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
  8230. }
  8231. ASTContext &getContext() { return S.getASTContext(); }
  8232. const Expr *E;
  8233. Sema &S;
  8234. };
  8235. struct SearchNonTrivialToCopyField
  8236. : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
  8237. using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
  8238. SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
  8239. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
  8240. SourceLocation SL) {
  8241. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8242. asDerived().visitArray(PCK, AT, SL);
  8243. return;
  8244. }
  8245. Super::visitWithKind(PCK, FT, SL);
  8246. }
  8247. void visitARCStrong(QualType FT, SourceLocation SL) {
  8248. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8249. }
  8250. void visitARCWeak(QualType FT, SourceLocation SL) {
  8251. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8252. }
  8253. void visitStruct(QualType FT, SourceLocation SL) {
  8254. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8255. visit(FD->getType(), FD->getLocation());
  8256. }
  8257. void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
  8258. SourceLocation SL) {
  8259. visit(getContext().getBaseElementType(AT), SL);
  8260. }
  8261. void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
  8262. SourceLocation SL) {}
  8263. void visitTrivial(QualType FT, SourceLocation SL) {}
  8264. void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
  8265. static void diag(QualType RT, const Expr *E, Sema &S) {
  8266. SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
  8267. }
  8268. ASTContext &getContext() { return S.getASTContext(); }
  8269. const Expr *E;
  8270. Sema &S;
  8271. };
  8272. }
  8273. /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
  8274. static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
  8275. SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
  8276. if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
  8277. if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
  8278. return false;
  8279. return doesExprLikelyComputeSize(BO->getLHS()) ||
  8280. doesExprLikelyComputeSize(BO->getRHS());
  8281. }
  8282. return getAsSizeOfExpr(SizeofExpr) != nullptr;
  8283. }
  8284. /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
  8285. ///
  8286. /// \code
  8287. /// #define MACRO 0
  8288. /// foo(MACRO);
  8289. /// foo(0);
  8290. /// \endcode
  8291. ///
  8292. /// This should return true for the first call to foo, but not for the second
  8293. /// (regardless of whether foo is a macro or function).
  8294. static bool isArgumentExpandedFromMacro(SourceManager &SM,
  8295. SourceLocation CallLoc,
  8296. SourceLocation ArgLoc) {
  8297. if (!CallLoc.isMacroID())
  8298. return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
  8299. return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
  8300. SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
  8301. }
  8302. /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
  8303. /// last two arguments transposed.
  8304. static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
  8305. if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
  8306. return;
  8307. const Expr *SizeArg =
  8308. Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
  8309. auto isLiteralZero = [](const Expr *E) {
  8310. return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
  8311. };
  8312. // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
  8313. SourceLocation CallLoc = Call->getRParenLoc();
  8314. SourceManager &SM = S.getSourceManager();
  8315. if (isLiteralZero(SizeArg) &&
  8316. !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
  8317. SourceLocation DiagLoc = SizeArg->getExprLoc();
  8318. // Some platforms #define bzero to __builtin_memset. See if this is the
  8319. // case, and if so, emit a better diagnostic.
  8320. if (BId == Builtin::BIbzero ||
  8321. (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
  8322. CallLoc, SM, S.getLangOpts()) == "bzero")) {
  8323. S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
  8324. S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
  8325. } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
  8326. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
  8327. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
  8328. }
  8329. return;
  8330. }
  8331. // If the second argument to a memset is a sizeof expression and the third
  8332. // isn't, this is also likely an error. This should catch
  8333. // 'memset(buf, sizeof(buf), 0xff)'.
  8334. if (BId == Builtin::BImemset &&
  8335. doesExprLikelyComputeSize(Call->getArg(1)) &&
  8336. !doesExprLikelyComputeSize(Call->getArg(2))) {
  8337. SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
  8338. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
  8339. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
  8340. return;
  8341. }
  8342. }
  8343. /// Check for dangerous or invalid arguments to memset().
  8344. ///
  8345. /// This issues warnings on known problematic, dangerous or unspecified
  8346. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  8347. /// function calls.
  8348. ///
  8349. /// \param Call The call expression to diagnose.
  8350. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  8351. unsigned BId,
  8352. IdentifierInfo *FnName) {
  8353. assert(BId != 0);
  8354. // It is possible to have a non-standard definition of memset. Validate
  8355. // we have enough arguments, and if not, abort further checking.
  8356. unsigned ExpectedNumArgs =
  8357. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  8358. if (Call->getNumArgs() < ExpectedNumArgs)
  8359. return;
  8360. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  8361. BId == Builtin::BIstrndup ? 1 : 2);
  8362. unsigned LenArg =
  8363. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  8364. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  8365. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  8366. Call->getBeginLoc(), Call->getRParenLoc()))
  8367. return;
  8368. // Catch cases like 'memset(buf, sizeof(buf), 0)'.
  8369. CheckMemaccessSize(*this, BId, Call);
  8370. // We have special checking when the length is a sizeof expression.
  8371. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  8372. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  8373. llvm::FoldingSetNodeID SizeOfArgID;
  8374. // Although widely used, 'bzero' is not a standard function. Be more strict
  8375. // with the argument types before allowing diagnostics and only allow the
  8376. // form bzero(ptr, sizeof(...)).
  8377. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8378. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  8379. return;
  8380. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  8381. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  8382. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  8383. QualType DestTy = Dest->getType();
  8384. QualType PointeeTy;
  8385. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  8386. PointeeTy = DestPtrTy->getPointeeType();
  8387. // Never warn about void type pointers. This can be used to suppress
  8388. // false positives.
  8389. if (PointeeTy->isVoidType())
  8390. continue;
  8391. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  8392. // actually comparing the expressions for equality. Because computing the
  8393. // expression IDs can be expensive, we only do this if the diagnostic is
  8394. // enabled.
  8395. if (SizeOfArg &&
  8396. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  8397. SizeOfArg->getExprLoc())) {
  8398. // We only compute IDs for expressions if the warning is enabled, and
  8399. // cache the sizeof arg's ID.
  8400. if (SizeOfArgID == llvm::FoldingSetNodeID())
  8401. SizeOfArg->Profile(SizeOfArgID, Context, true);
  8402. llvm::FoldingSetNodeID DestID;
  8403. Dest->Profile(DestID, Context, true);
  8404. if (DestID == SizeOfArgID) {
  8405. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  8406. // over sizeof(src) as well.
  8407. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  8408. StringRef ReadableName = FnName->getName();
  8409. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  8410. if (UnaryOp->getOpcode() == UO_AddrOf)
  8411. ActionIdx = 1; // If its an address-of operator, just remove it.
  8412. if (!PointeeTy->isIncompleteType() &&
  8413. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  8414. ActionIdx = 2; // If the pointee's size is sizeof(char),
  8415. // suggest an explicit length.
  8416. // If the function is defined as a builtin macro, do not show macro
  8417. // expansion.
  8418. SourceLocation SL = SizeOfArg->getExprLoc();
  8419. SourceRange DSR = Dest->getSourceRange();
  8420. SourceRange SSR = SizeOfArg->getSourceRange();
  8421. SourceManager &SM = getSourceManager();
  8422. if (SM.isMacroArgExpansion(SL)) {
  8423. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  8424. SL = SM.getSpellingLoc(SL);
  8425. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  8426. SM.getSpellingLoc(DSR.getEnd()));
  8427. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  8428. SM.getSpellingLoc(SSR.getEnd()));
  8429. }
  8430. DiagRuntimeBehavior(SL, SizeOfArg,
  8431. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  8432. << ReadableName
  8433. << PointeeTy
  8434. << DestTy
  8435. << DSR
  8436. << SSR);
  8437. DiagRuntimeBehavior(SL, SizeOfArg,
  8438. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  8439. << ActionIdx
  8440. << SSR);
  8441. break;
  8442. }
  8443. }
  8444. // Also check for cases where the sizeof argument is the exact same
  8445. // type as the memory argument, and where it points to a user-defined
  8446. // record type.
  8447. if (SizeOfArgTy != QualType()) {
  8448. if (PointeeTy->isRecordType() &&
  8449. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  8450. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  8451. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  8452. << FnName << SizeOfArgTy << ArgIdx
  8453. << PointeeTy << Dest->getSourceRange()
  8454. << LenExpr->getSourceRange());
  8455. break;
  8456. }
  8457. }
  8458. } else if (DestTy->isArrayType()) {
  8459. PointeeTy = DestTy;
  8460. }
  8461. if (PointeeTy == QualType())
  8462. continue;
  8463. // Always complain about dynamic classes.
  8464. bool IsContained;
  8465. if (const CXXRecordDecl *ContainedRD =
  8466. getContainedDynamicClass(PointeeTy, IsContained)) {
  8467. unsigned OperationType = 0;
  8468. const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
  8469. // "overwritten" if we're warning about the destination for any call
  8470. // but memcmp; otherwise a verb appropriate to the call.
  8471. if (ArgIdx != 0 || IsCmp) {
  8472. if (BId == Builtin::BImemcpy)
  8473. OperationType = 1;
  8474. else if(BId == Builtin::BImemmove)
  8475. OperationType = 2;
  8476. else if (IsCmp)
  8477. OperationType = 3;
  8478. }
  8479. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8480. PDiag(diag::warn_dyn_class_memaccess)
  8481. << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
  8482. << IsContained << ContainedRD << OperationType
  8483. << Call->getCallee()->getSourceRange());
  8484. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  8485. BId != Builtin::BImemset)
  8486. DiagRuntimeBehavior(
  8487. Dest->getExprLoc(), Dest,
  8488. PDiag(diag::warn_arc_object_memaccess)
  8489. << ArgIdx << FnName << PointeeTy
  8490. << Call->getCallee()->getSourceRange());
  8491. else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
  8492. if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
  8493. RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
  8494. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8495. PDiag(diag::warn_cstruct_memaccess)
  8496. << ArgIdx << FnName << PointeeTy << 0);
  8497. SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
  8498. } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  8499. RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
  8500. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8501. PDiag(diag::warn_cstruct_memaccess)
  8502. << ArgIdx << FnName << PointeeTy << 1);
  8503. SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
  8504. } else {
  8505. continue;
  8506. }
  8507. } else
  8508. continue;
  8509. DiagRuntimeBehavior(
  8510. Dest->getExprLoc(), Dest,
  8511. PDiag(diag::note_bad_memaccess_silence)
  8512. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  8513. break;
  8514. }
  8515. }
  8516. // A little helper routine: ignore addition and subtraction of integer literals.
  8517. // This intentionally does not ignore all integer constant expressions because
  8518. // we don't want to remove sizeof().
  8519. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  8520. Ex = Ex->IgnoreParenCasts();
  8521. while (true) {
  8522. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  8523. if (!BO || !BO->isAdditiveOp())
  8524. break;
  8525. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  8526. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  8527. if (isa<IntegerLiteral>(RHS))
  8528. Ex = LHS;
  8529. else if (isa<IntegerLiteral>(LHS))
  8530. Ex = RHS;
  8531. else
  8532. break;
  8533. }
  8534. return Ex;
  8535. }
  8536. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  8537. ASTContext &Context) {
  8538. // Only handle constant-sized or VLAs, but not flexible members.
  8539. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  8540. // Only issue the FIXIT for arrays of size > 1.
  8541. if (CAT->getSize().getSExtValue() <= 1)
  8542. return false;
  8543. } else if (!Ty->isVariableArrayType()) {
  8544. return false;
  8545. }
  8546. return true;
  8547. }
  8548. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  8549. // be the size of the source, instead of the destination.
  8550. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  8551. IdentifierInfo *FnName) {
  8552. // Don't crash if the user has the wrong number of arguments
  8553. unsigned NumArgs = Call->getNumArgs();
  8554. if ((NumArgs != 3) && (NumArgs != 4))
  8555. return;
  8556. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  8557. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  8558. const Expr *CompareWithSrc = nullptr;
  8559. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  8560. Call->getBeginLoc(), Call->getRParenLoc()))
  8561. return;
  8562. // Look for 'strlcpy(dst, x, sizeof(x))'
  8563. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  8564. CompareWithSrc = Ex;
  8565. else {
  8566. // Look for 'strlcpy(dst, x, strlen(x))'
  8567. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  8568. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  8569. SizeCall->getNumArgs() == 1)
  8570. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  8571. }
  8572. }
  8573. if (!CompareWithSrc)
  8574. return;
  8575. // Determine if the argument to sizeof/strlen is equal to the source
  8576. // argument. In principle there's all kinds of things you could do
  8577. // here, for instance creating an == expression and evaluating it with
  8578. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  8579. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  8580. if (!SrcArgDRE)
  8581. return;
  8582. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  8583. if (!CompareWithSrcDRE ||
  8584. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  8585. return;
  8586. const Expr *OriginalSizeArg = Call->getArg(2);
  8587. Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
  8588. << OriginalSizeArg->getSourceRange() << FnName;
  8589. // Output a FIXIT hint if the destination is an array (rather than a
  8590. // pointer to an array). This could be enhanced to handle some
  8591. // pointers if we know the actual size, like if DstArg is 'array+2'
  8592. // we could say 'sizeof(array)-2'.
  8593. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  8594. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  8595. return;
  8596. SmallString<128> sizeString;
  8597. llvm::raw_svector_ostream OS(sizeString);
  8598. OS << "sizeof(";
  8599. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8600. OS << ")";
  8601. Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
  8602. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  8603. OS.str());
  8604. }
  8605. /// Check if two expressions refer to the same declaration.
  8606. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  8607. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  8608. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  8609. return D1->getDecl() == D2->getDecl();
  8610. return false;
  8611. }
  8612. static const Expr *getStrlenExprArg(const Expr *E) {
  8613. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8614. const FunctionDecl *FD = CE->getDirectCallee();
  8615. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  8616. return nullptr;
  8617. return CE->getArg(0)->IgnoreParenCasts();
  8618. }
  8619. return nullptr;
  8620. }
  8621. // Warn on anti-patterns as the 'size' argument to strncat.
  8622. // The correct size argument should look like following:
  8623. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  8624. void Sema::CheckStrncatArguments(const CallExpr *CE,
  8625. IdentifierInfo *FnName) {
  8626. // Don't crash if the user has the wrong number of arguments.
  8627. if (CE->getNumArgs() < 3)
  8628. return;
  8629. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  8630. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  8631. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  8632. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
  8633. CE->getRParenLoc()))
  8634. return;
  8635. // Identify common expressions, which are wrongly used as the size argument
  8636. // to strncat and may lead to buffer overflows.
  8637. unsigned PatternType = 0;
  8638. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  8639. // - sizeof(dst)
  8640. if (referToTheSameDecl(SizeOfArg, DstArg))
  8641. PatternType = 1;
  8642. // - sizeof(src)
  8643. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  8644. PatternType = 2;
  8645. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  8646. if (BE->getOpcode() == BO_Sub) {
  8647. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  8648. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  8649. // - sizeof(dst) - strlen(dst)
  8650. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  8651. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  8652. PatternType = 1;
  8653. // - sizeof(src) - (anything)
  8654. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  8655. PatternType = 2;
  8656. }
  8657. }
  8658. if (PatternType == 0)
  8659. return;
  8660. // Generate the diagnostic.
  8661. SourceLocation SL = LenArg->getBeginLoc();
  8662. SourceRange SR = LenArg->getSourceRange();
  8663. SourceManager &SM = getSourceManager();
  8664. // If the function is defined as a builtin macro, do not show macro expansion.
  8665. if (SM.isMacroArgExpansion(SL)) {
  8666. SL = SM.getSpellingLoc(SL);
  8667. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  8668. SM.getSpellingLoc(SR.getEnd()));
  8669. }
  8670. // Check if the destination is an array (rather than a pointer to an array).
  8671. QualType DstTy = DstArg->getType();
  8672. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  8673. Context);
  8674. if (!isKnownSizeArray) {
  8675. if (PatternType == 1)
  8676. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  8677. else
  8678. Diag(SL, diag::warn_strncat_src_size) << SR;
  8679. return;
  8680. }
  8681. if (PatternType == 1)
  8682. Diag(SL, diag::warn_strncat_large_size) << SR;
  8683. else
  8684. Diag(SL, diag::warn_strncat_src_size) << SR;
  8685. SmallString<128> sizeString;
  8686. llvm::raw_svector_ostream OS(sizeString);
  8687. OS << "sizeof(";
  8688. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8689. OS << ") - ";
  8690. OS << "strlen(";
  8691. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8692. OS << ") - 1";
  8693. Diag(SL, diag::note_strncat_wrong_size)
  8694. << FixItHint::CreateReplacement(SR, OS.str());
  8695. }
  8696. void
  8697. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  8698. SourceLocation ReturnLoc,
  8699. bool isObjCMethod,
  8700. const AttrVec *Attrs,
  8701. const FunctionDecl *FD) {
  8702. // Check if the return value is null but should not be.
  8703. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  8704. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  8705. CheckNonNullExpr(*this, RetValExp))
  8706. Diag(ReturnLoc, diag::warn_null_ret)
  8707. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  8708. // C++11 [basic.stc.dynamic.allocation]p4:
  8709. // If an allocation function declared with a non-throwing
  8710. // exception-specification fails to allocate storage, it shall return
  8711. // a null pointer. Any other allocation function that fails to allocate
  8712. // storage shall indicate failure only by throwing an exception [...]
  8713. if (FD) {
  8714. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  8715. if (Op == OO_New || Op == OO_Array_New) {
  8716. const FunctionProtoType *Proto
  8717. = FD->getType()->castAs<FunctionProtoType>();
  8718. if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
  8719. CheckNonNullExpr(*this, RetValExp))
  8720. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  8721. << FD << getLangOpts().CPlusPlus11;
  8722. }
  8723. }
  8724. }
  8725. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  8726. /// Check for comparisons of floating point operands using != and ==.
  8727. /// Issue a warning if these are no self-comparisons, as they are not likely
  8728. /// to do what the programmer intended.
  8729. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  8730. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  8731. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  8732. // Special case: check for x == x (which is OK).
  8733. // Do not emit warnings for such cases.
  8734. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  8735. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  8736. if (DRL->getDecl() == DRR->getDecl())
  8737. return;
  8738. // Special case: check for comparisons against literals that can be exactly
  8739. // represented by APFloat. In such cases, do not emit a warning. This
  8740. // is a heuristic: often comparison against such literals are used to
  8741. // detect if a value in a variable has not changed. This clearly can
  8742. // lead to false negatives.
  8743. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  8744. if (FLL->isExact())
  8745. return;
  8746. } else
  8747. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  8748. if (FLR->isExact())
  8749. return;
  8750. // Check for comparisons with builtin types.
  8751. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  8752. if (CL->getBuiltinCallee())
  8753. return;
  8754. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  8755. if (CR->getBuiltinCallee())
  8756. return;
  8757. // Emit the diagnostic.
  8758. Diag(Loc, diag::warn_floatingpoint_eq)
  8759. << LHS->getSourceRange() << RHS->getSourceRange();
  8760. }
  8761. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  8762. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  8763. namespace {
  8764. /// Structure recording the 'active' range of an integer-valued
  8765. /// expression.
  8766. struct IntRange {
  8767. /// The number of bits active in the int.
  8768. unsigned Width;
  8769. /// True if the int is known not to have negative values.
  8770. bool NonNegative;
  8771. IntRange(unsigned Width, bool NonNegative)
  8772. : Width(Width), NonNegative(NonNegative) {}
  8773. /// Returns the range of the bool type.
  8774. static IntRange forBoolType() {
  8775. return IntRange(1, true);
  8776. }
  8777. /// Returns the range of an opaque value of the given integral type.
  8778. static IntRange forValueOfType(ASTContext &C, QualType T) {
  8779. return forValueOfCanonicalType(C,
  8780. T->getCanonicalTypeInternal().getTypePtr());
  8781. }
  8782. /// Returns the range of an opaque value of a canonical integral type.
  8783. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  8784. assert(T->isCanonicalUnqualified());
  8785. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8786. T = VT->getElementType().getTypePtr();
  8787. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8788. T = CT->getElementType().getTypePtr();
  8789. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8790. T = AT->getValueType().getTypePtr();
  8791. if (!C.getLangOpts().CPlusPlus) {
  8792. // For enum types in C code, use the underlying datatype.
  8793. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8794. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  8795. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  8796. // For enum types in C++, use the known bit width of the enumerators.
  8797. EnumDecl *Enum = ET->getDecl();
  8798. // In C++11, enums can have a fixed underlying type. Use this type to
  8799. // compute the range.
  8800. if (Enum->isFixed()) {
  8801. return IntRange(C.getIntWidth(QualType(T, 0)),
  8802. !ET->isSignedIntegerOrEnumerationType());
  8803. }
  8804. unsigned NumPositive = Enum->getNumPositiveBits();
  8805. unsigned NumNegative = Enum->getNumNegativeBits();
  8806. if (NumNegative == 0)
  8807. return IntRange(NumPositive, true/*NonNegative*/);
  8808. else
  8809. return IntRange(std::max(NumPositive + 1, NumNegative),
  8810. false/*NonNegative*/);
  8811. }
  8812. const BuiltinType *BT = cast<BuiltinType>(T);
  8813. assert(BT->isInteger());
  8814. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8815. }
  8816. /// Returns the "target" range of a canonical integral type, i.e.
  8817. /// the range of values expressible in the type.
  8818. ///
  8819. /// This matches forValueOfCanonicalType except that enums have the
  8820. /// full range of their type, not the range of their enumerators.
  8821. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  8822. assert(T->isCanonicalUnqualified());
  8823. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8824. T = VT->getElementType().getTypePtr();
  8825. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8826. T = CT->getElementType().getTypePtr();
  8827. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8828. T = AT->getValueType().getTypePtr();
  8829. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8830. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  8831. const BuiltinType *BT = cast<BuiltinType>(T);
  8832. assert(BT->isInteger());
  8833. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8834. }
  8835. /// Returns the supremum of two ranges: i.e. their conservative merge.
  8836. static IntRange join(IntRange L, IntRange R) {
  8837. return IntRange(std::max(L.Width, R.Width),
  8838. L.NonNegative && R.NonNegative);
  8839. }
  8840. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  8841. static IntRange meet(IntRange L, IntRange R) {
  8842. return IntRange(std::min(L.Width, R.Width),
  8843. L.NonNegative || R.NonNegative);
  8844. }
  8845. };
  8846. } // namespace
  8847. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  8848. unsigned MaxWidth) {
  8849. if (value.isSigned() && value.isNegative())
  8850. return IntRange(value.getMinSignedBits(), false);
  8851. if (value.getBitWidth() > MaxWidth)
  8852. value = value.trunc(MaxWidth);
  8853. // isNonNegative() just checks the sign bit without considering
  8854. // signedness.
  8855. return IntRange(value.getActiveBits(), true);
  8856. }
  8857. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  8858. unsigned MaxWidth) {
  8859. if (result.isInt())
  8860. return GetValueRange(C, result.getInt(), MaxWidth);
  8861. if (result.isVector()) {
  8862. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  8863. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  8864. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  8865. R = IntRange::join(R, El);
  8866. }
  8867. return R;
  8868. }
  8869. if (result.isComplexInt()) {
  8870. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  8871. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  8872. return IntRange::join(R, I);
  8873. }
  8874. // This can happen with lossless casts to intptr_t of "based" lvalues.
  8875. // Assume it might use arbitrary bits.
  8876. // FIXME: The only reason we need to pass the type in here is to get
  8877. // the sign right on this one case. It would be nice if APValue
  8878. // preserved this.
  8879. assert(result.isLValue() || result.isAddrLabelDiff());
  8880. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  8881. }
  8882. static QualType GetExprType(const Expr *E) {
  8883. QualType Ty = E->getType();
  8884. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  8885. Ty = AtomicRHS->getValueType();
  8886. return Ty;
  8887. }
  8888. /// Pseudo-evaluate the given integer expression, estimating the
  8889. /// range of values it might take.
  8890. ///
  8891. /// \param MaxWidth - the width to which the value will be truncated
  8892. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
  8893. E = E->IgnoreParens();
  8894. // Try a full evaluation first.
  8895. Expr::EvalResult result;
  8896. if (E->EvaluateAsRValue(result, C))
  8897. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  8898. // I think we only want to look through implicit casts here; if the
  8899. // user has an explicit widening cast, we should treat the value as
  8900. // being of the new, wider type.
  8901. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  8902. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  8903. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  8904. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  8905. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  8906. CE->getCastKind() == CK_BooleanToSignedIntegral;
  8907. // Assume that non-integer casts can span the full range of the type.
  8908. if (!isIntegerCast)
  8909. return OutputTypeRange;
  8910. IntRange SubRange
  8911. = GetExprRange(C, CE->getSubExpr(),
  8912. std::min(MaxWidth, OutputTypeRange.Width));
  8913. // Bail out if the subexpr's range is as wide as the cast type.
  8914. if (SubRange.Width >= OutputTypeRange.Width)
  8915. return OutputTypeRange;
  8916. // Otherwise, we take the smaller width, and we're non-negative if
  8917. // either the output type or the subexpr is.
  8918. return IntRange(SubRange.Width,
  8919. SubRange.NonNegative || OutputTypeRange.NonNegative);
  8920. }
  8921. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  8922. // If we can fold the condition, just take that operand.
  8923. bool CondResult;
  8924. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  8925. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  8926. : CO->getFalseExpr(),
  8927. MaxWidth);
  8928. // Otherwise, conservatively merge.
  8929. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  8930. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  8931. return IntRange::join(L, R);
  8932. }
  8933. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  8934. switch (BO->getOpcode()) {
  8935. case BO_Cmp:
  8936. llvm_unreachable("builtin <=> should have class type");
  8937. // Boolean-valued operations are single-bit and positive.
  8938. case BO_LAnd:
  8939. case BO_LOr:
  8940. case BO_LT:
  8941. case BO_GT:
  8942. case BO_LE:
  8943. case BO_GE:
  8944. case BO_EQ:
  8945. case BO_NE:
  8946. return IntRange::forBoolType();
  8947. // The type of the assignments is the type of the LHS, so the RHS
  8948. // is not necessarily the same type.
  8949. case BO_MulAssign:
  8950. case BO_DivAssign:
  8951. case BO_RemAssign:
  8952. case BO_AddAssign:
  8953. case BO_SubAssign:
  8954. case BO_XorAssign:
  8955. case BO_OrAssign:
  8956. // TODO: bitfields?
  8957. return IntRange::forValueOfType(C, GetExprType(E));
  8958. // Simple assignments just pass through the RHS, which will have
  8959. // been coerced to the LHS type.
  8960. case BO_Assign:
  8961. // TODO: bitfields?
  8962. return GetExprRange(C, BO->getRHS(), MaxWidth);
  8963. // Operations with opaque sources are black-listed.
  8964. case BO_PtrMemD:
  8965. case BO_PtrMemI:
  8966. return IntRange::forValueOfType(C, GetExprType(E));
  8967. // Bitwise-and uses the *infinum* of the two source ranges.
  8968. case BO_And:
  8969. case BO_AndAssign:
  8970. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  8971. GetExprRange(C, BO->getRHS(), MaxWidth));
  8972. // Left shift gets black-listed based on a judgement call.
  8973. case BO_Shl:
  8974. // ...except that we want to treat '1 << (blah)' as logically
  8975. // positive. It's an important idiom.
  8976. if (IntegerLiteral *I
  8977. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  8978. if (I->getValue() == 1) {
  8979. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  8980. return IntRange(R.Width, /*NonNegative*/ true);
  8981. }
  8982. }
  8983. LLVM_FALLTHROUGH;
  8984. case BO_ShlAssign:
  8985. return IntRange::forValueOfType(C, GetExprType(E));
  8986. // Right shift by a constant can narrow its left argument.
  8987. case BO_Shr:
  8988. case BO_ShrAssign: {
  8989. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  8990. // If the shift amount is a positive constant, drop the width by
  8991. // that much.
  8992. llvm::APSInt shift;
  8993. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  8994. shift.isNonNegative()) {
  8995. unsigned zext = shift.getZExtValue();
  8996. if (zext >= L.Width)
  8997. L.Width = (L.NonNegative ? 0 : 1);
  8998. else
  8999. L.Width -= zext;
  9000. }
  9001. return L;
  9002. }
  9003. // Comma acts as its right operand.
  9004. case BO_Comma:
  9005. return GetExprRange(C, BO->getRHS(), MaxWidth);
  9006. // Black-list pointer subtractions.
  9007. case BO_Sub:
  9008. if (BO->getLHS()->getType()->isPointerType())
  9009. return IntRange::forValueOfType(C, GetExprType(E));
  9010. break;
  9011. // The width of a division result is mostly determined by the size
  9012. // of the LHS.
  9013. case BO_Div: {
  9014. // Don't 'pre-truncate' the operands.
  9015. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9016. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  9017. // If the divisor is constant, use that.
  9018. llvm::APSInt divisor;
  9019. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  9020. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  9021. if (log2 >= L.Width)
  9022. L.Width = (L.NonNegative ? 0 : 1);
  9023. else
  9024. L.Width = std::min(L.Width - log2, MaxWidth);
  9025. return L;
  9026. }
  9027. // Otherwise, just use the LHS's width.
  9028. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  9029. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  9030. }
  9031. // The result of a remainder can't be larger than the result of
  9032. // either side.
  9033. case BO_Rem: {
  9034. // Don't 'pre-truncate' the operands.
  9035. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9036. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  9037. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  9038. IntRange meet = IntRange::meet(L, R);
  9039. meet.Width = std::min(meet.Width, MaxWidth);
  9040. return meet;
  9041. }
  9042. // The default behavior is okay for these.
  9043. case BO_Mul:
  9044. case BO_Add:
  9045. case BO_Xor:
  9046. case BO_Or:
  9047. break;
  9048. }
  9049. // The default case is to treat the operation as if it were closed
  9050. // on the narrowest type that encompasses both operands.
  9051. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  9052. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  9053. return IntRange::join(L, R);
  9054. }
  9055. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  9056. switch (UO->getOpcode()) {
  9057. // Boolean-valued operations are white-listed.
  9058. case UO_LNot:
  9059. return IntRange::forBoolType();
  9060. // Operations with opaque sources are black-listed.
  9061. case UO_Deref:
  9062. case UO_AddrOf: // should be impossible
  9063. return IntRange::forValueOfType(C, GetExprType(E));
  9064. default:
  9065. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  9066. }
  9067. }
  9068. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  9069. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
  9070. if (const auto *BitField = E->getSourceBitField())
  9071. return IntRange(BitField->getBitWidthValue(C),
  9072. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  9073. return IntRange::forValueOfType(C, GetExprType(E));
  9074. }
  9075. static IntRange GetExprRange(ASTContext &C, const Expr *E) {
  9076. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
  9077. }
  9078. /// Checks whether the given value, which currently has the given
  9079. /// source semantics, has the same value when coerced through the
  9080. /// target semantics.
  9081. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  9082. const llvm::fltSemantics &Src,
  9083. const llvm::fltSemantics &Tgt) {
  9084. llvm::APFloat truncated = value;
  9085. bool ignored;
  9086. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9087. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9088. return truncated.bitwiseIsEqual(value);
  9089. }
  9090. /// Checks whether the given value, which currently has the given
  9091. /// source semantics, has the same value when coerced through the
  9092. /// target semantics.
  9093. ///
  9094. /// The value might be a vector of floats (or a complex number).
  9095. static bool IsSameFloatAfterCast(const APValue &value,
  9096. const llvm::fltSemantics &Src,
  9097. const llvm::fltSemantics &Tgt) {
  9098. if (value.isFloat())
  9099. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  9100. if (value.isVector()) {
  9101. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  9102. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  9103. return false;
  9104. return true;
  9105. }
  9106. assert(value.isComplexFloat());
  9107. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  9108. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  9109. }
  9110. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  9111. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  9112. // Suppress cases where we are comparing against an enum constant.
  9113. if (const DeclRefExpr *DR =
  9114. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  9115. if (isa<EnumConstantDecl>(DR->getDecl()))
  9116. return true;
  9117. // Suppress cases where the '0' value is expanded from a macro.
  9118. if (E->getBeginLoc().isMacroID())
  9119. return true;
  9120. return false;
  9121. }
  9122. static bool isKnownToHaveUnsignedValue(Expr *E) {
  9123. return E->getType()->isIntegerType() &&
  9124. (!E->getType()->isSignedIntegerType() ||
  9125. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  9126. }
  9127. namespace {
  9128. /// The promoted range of values of a type. In general this has the
  9129. /// following structure:
  9130. ///
  9131. /// |-----------| . . . |-----------|
  9132. /// ^ ^ ^ ^
  9133. /// Min HoleMin HoleMax Max
  9134. ///
  9135. /// ... where there is only a hole if a signed type is promoted to unsigned
  9136. /// (in which case Min and Max are the smallest and largest representable
  9137. /// values).
  9138. struct PromotedRange {
  9139. // Min, or HoleMax if there is a hole.
  9140. llvm::APSInt PromotedMin;
  9141. // Max, or HoleMin if there is a hole.
  9142. llvm::APSInt PromotedMax;
  9143. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  9144. if (R.Width == 0)
  9145. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  9146. else if (R.Width >= BitWidth && !Unsigned) {
  9147. // Promotion made the type *narrower*. This happens when promoting
  9148. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  9149. // Treat all values of 'signed int' as being in range for now.
  9150. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  9151. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  9152. } else {
  9153. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  9154. .extOrTrunc(BitWidth);
  9155. PromotedMin.setIsUnsigned(Unsigned);
  9156. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  9157. .extOrTrunc(BitWidth);
  9158. PromotedMax.setIsUnsigned(Unsigned);
  9159. }
  9160. }
  9161. // Determine whether this range is contiguous (has no hole).
  9162. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  9163. // Where a constant value is within the range.
  9164. enum ComparisonResult {
  9165. LT = 0x1,
  9166. LE = 0x2,
  9167. GT = 0x4,
  9168. GE = 0x8,
  9169. EQ = 0x10,
  9170. NE = 0x20,
  9171. InRangeFlag = 0x40,
  9172. Less = LE | LT | NE,
  9173. Min = LE | InRangeFlag,
  9174. InRange = InRangeFlag,
  9175. Max = GE | InRangeFlag,
  9176. Greater = GE | GT | NE,
  9177. OnlyValue = LE | GE | EQ | InRangeFlag,
  9178. InHole = NE
  9179. };
  9180. ComparisonResult compare(const llvm::APSInt &Value) const {
  9181. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  9182. Value.isUnsigned() == PromotedMin.isUnsigned());
  9183. if (!isContiguous()) {
  9184. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  9185. if (Value.isMinValue()) return Min;
  9186. if (Value.isMaxValue()) return Max;
  9187. if (Value >= PromotedMin) return InRange;
  9188. if (Value <= PromotedMax) return InRange;
  9189. return InHole;
  9190. }
  9191. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  9192. case -1: return Less;
  9193. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  9194. case 1:
  9195. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  9196. case -1: return InRange;
  9197. case 0: return Max;
  9198. case 1: return Greater;
  9199. }
  9200. }
  9201. llvm_unreachable("impossible compare result");
  9202. }
  9203. static llvm::Optional<StringRef>
  9204. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  9205. if (Op == BO_Cmp) {
  9206. ComparisonResult LTFlag = LT, GTFlag = GT;
  9207. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  9208. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  9209. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  9210. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  9211. return llvm::None;
  9212. }
  9213. ComparisonResult TrueFlag, FalseFlag;
  9214. if (Op == BO_EQ) {
  9215. TrueFlag = EQ;
  9216. FalseFlag = NE;
  9217. } else if (Op == BO_NE) {
  9218. TrueFlag = NE;
  9219. FalseFlag = EQ;
  9220. } else {
  9221. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  9222. TrueFlag = LT;
  9223. FalseFlag = GE;
  9224. } else {
  9225. TrueFlag = GT;
  9226. FalseFlag = LE;
  9227. }
  9228. if (Op == BO_GE || Op == BO_LE)
  9229. std::swap(TrueFlag, FalseFlag);
  9230. }
  9231. if (R & TrueFlag)
  9232. return StringRef("true");
  9233. if (R & FalseFlag)
  9234. return StringRef("false");
  9235. return llvm::None;
  9236. }
  9237. };
  9238. }
  9239. static bool HasEnumType(Expr *E) {
  9240. // Strip off implicit integral promotions.
  9241. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  9242. if (ICE->getCastKind() != CK_IntegralCast &&
  9243. ICE->getCastKind() != CK_NoOp)
  9244. break;
  9245. E = ICE->getSubExpr();
  9246. }
  9247. return E->getType()->isEnumeralType();
  9248. }
  9249. static int classifyConstantValue(Expr *Constant) {
  9250. // The values of this enumeration are used in the diagnostics
  9251. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  9252. enum ConstantValueKind {
  9253. Miscellaneous = 0,
  9254. LiteralTrue,
  9255. LiteralFalse
  9256. };
  9257. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  9258. return BL->getValue() ? ConstantValueKind::LiteralTrue
  9259. : ConstantValueKind::LiteralFalse;
  9260. return ConstantValueKind::Miscellaneous;
  9261. }
  9262. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  9263. Expr *Constant, Expr *Other,
  9264. const llvm::APSInt &Value,
  9265. bool RhsConstant) {
  9266. if (S.inTemplateInstantiation())
  9267. return false;
  9268. Expr *OriginalOther = Other;
  9269. Constant = Constant->IgnoreParenImpCasts();
  9270. Other = Other->IgnoreParenImpCasts();
  9271. // Suppress warnings on tautological comparisons between values of the same
  9272. // enumeration type. There are only two ways we could warn on this:
  9273. // - If the constant is outside the range of representable values of
  9274. // the enumeration. In such a case, we should warn about the cast
  9275. // to enumeration type, not about the comparison.
  9276. // - If the constant is the maximum / minimum in-range value. For an
  9277. // enumeratin type, such comparisons can be meaningful and useful.
  9278. if (Constant->getType()->isEnumeralType() &&
  9279. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  9280. return false;
  9281. // TODO: Investigate using GetExprRange() to get tighter bounds
  9282. // on the bit ranges.
  9283. QualType OtherT = Other->getType();
  9284. if (const auto *AT = OtherT->getAs<AtomicType>())
  9285. OtherT = AT->getValueType();
  9286. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  9287. // Whether we're treating Other as being a bool because of the form of
  9288. // expression despite it having another type (typically 'int' in C).
  9289. bool OtherIsBooleanDespiteType =
  9290. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  9291. if (OtherIsBooleanDespiteType)
  9292. OtherRange = IntRange::forBoolType();
  9293. // Determine the promoted range of the other type and see if a comparison of
  9294. // the constant against that range is tautological.
  9295. PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
  9296. Value.isUnsigned());
  9297. auto Cmp = OtherPromotedRange.compare(Value);
  9298. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  9299. if (!Result)
  9300. return false;
  9301. // Suppress the diagnostic for an in-range comparison if the constant comes
  9302. // from a macro or enumerator. We don't want to diagnose
  9303. //
  9304. // some_long_value <= INT_MAX
  9305. //
  9306. // when sizeof(int) == sizeof(long).
  9307. bool InRange = Cmp & PromotedRange::InRangeFlag;
  9308. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  9309. return false;
  9310. // If this is a comparison to an enum constant, include that
  9311. // constant in the diagnostic.
  9312. const EnumConstantDecl *ED = nullptr;
  9313. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  9314. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  9315. // Should be enough for uint128 (39 decimal digits)
  9316. SmallString<64> PrettySourceValue;
  9317. llvm::raw_svector_ostream OS(PrettySourceValue);
  9318. if (ED)
  9319. OS << '\'' << *ED << "' (" << Value << ")";
  9320. else
  9321. OS << Value;
  9322. // FIXME: We use a somewhat different formatting for the in-range cases and
  9323. // cases involving boolean values for historical reasons. We should pick a
  9324. // consistent way of presenting these diagnostics.
  9325. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  9326. S.DiagRuntimeBehavior(
  9327. E->getOperatorLoc(), E,
  9328. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  9329. : diag::warn_tautological_bool_compare)
  9330. << OS.str() << classifyConstantValue(Constant)
  9331. << OtherT << OtherIsBooleanDespiteType << *Result
  9332. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  9333. } else {
  9334. unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  9335. ? (HasEnumType(OriginalOther)
  9336. ? diag::warn_unsigned_enum_always_true_comparison
  9337. : diag::warn_unsigned_always_true_comparison)
  9338. : diag::warn_tautological_constant_compare;
  9339. S.Diag(E->getOperatorLoc(), Diag)
  9340. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  9341. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  9342. }
  9343. return true;
  9344. }
  9345. /// Analyze the operands of the given comparison. Implements the
  9346. /// fallback case from AnalyzeComparison.
  9347. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  9348. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9349. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9350. }
  9351. /// Implements -Wsign-compare.
  9352. ///
  9353. /// \param E the binary operator to check for warnings
  9354. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  9355. // The type the comparison is being performed in.
  9356. QualType T = E->getLHS()->getType();
  9357. // Only analyze comparison operators where both sides have been converted to
  9358. // the same type.
  9359. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  9360. return AnalyzeImpConvsInComparison(S, E);
  9361. // Don't analyze value-dependent comparisons directly.
  9362. if (E->isValueDependent())
  9363. return AnalyzeImpConvsInComparison(S, E);
  9364. Expr *LHS = E->getLHS();
  9365. Expr *RHS = E->getRHS();
  9366. if (T->isIntegralType(S.Context)) {
  9367. llvm::APSInt RHSValue;
  9368. llvm::APSInt LHSValue;
  9369. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  9370. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  9371. // We don't care about expressions whose result is a constant.
  9372. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  9373. return AnalyzeImpConvsInComparison(S, E);
  9374. // We only care about expressions where just one side is literal
  9375. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  9376. // Is the constant on the RHS or LHS?
  9377. const bool RhsConstant = IsRHSIntegralLiteral;
  9378. Expr *Const = RhsConstant ? RHS : LHS;
  9379. Expr *Other = RhsConstant ? LHS : RHS;
  9380. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  9381. // Check whether an integer constant comparison results in a value
  9382. // of 'true' or 'false'.
  9383. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  9384. return AnalyzeImpConvsInComparison(S, E);
  9385. }
  9386. }
  9387. if (!T->hasUnsignedIntegerRepresentation()) {
  9388. // We don't do anything special if this isn't an unsigned integral
  9389. // comparison: we're only interested in integral comparisons, and
  9390. // signed comparisons only happen in cases we don't care to warn about.
  9391. return AnalyzeImpConvsInComparison(S, E);
  9392. }
  9393. LHS = LHS->IgnoreParenImpCasts();
  9394. RHS = RHS->IgnoreParenImpCasts();
  9395. if (!S.getLangOpts().CPlusPlus) {
  9396. // Avoid warning about comparison of integers with different signs when
  9397. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  9398. // the type of `E`.
  9399. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  9400. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9401. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  9402. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9403. }
  9404. // Check to see if one of the (unmodified) operands is of different
  9405. // signedness.
  9406. Expr *signedOperand, *unsignedOperand;
  9407. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  9408. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  9409. "unsigned comparison between two signed integer expressions?");
  9410. signedOperand = LHS;
  9411. unsignedOperand = RHS;
  9412. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  9413. signedOperand = RHS;
  9414. unsignedOperand = LHS;
  9415. } else {
  9416. return AnalyzeImpConvsInComparison(S, E);
  9417. }
  9418. // Otherwise, calculate the effective range of the signed operand.
  9419. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  9420. // Go ahead and analyze implicit conversions in the operands. Note
  9421. // that we skip the implicit conversions on both sides.
  9422. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  9423. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  9424. // If the signed range is non-negative, -Wsign-compare won't fire.
  9425. if (signedRange.NonNegative)
  9426. return;
  9427. // For (in)equality comparisons, if the unsigned operand is a
  9428. // constant which cannot collide with a overflowed signed operand,
  9429. // then reinterpreting the signed operand as unsigned will not
  9430. // change the result of the comparison.
  9431. if (E->isEqualityOp()) {
  9432. unsigned comparisonWidth = S.Context.getIntWidth(T);
  9433. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  9434. // We should never be unable to prove that the unsigned operand is
  9435. // non-negative.
  9436. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  9437. if (unsignedRange.Width < comparisonWidth)
  9438. return;
  9439. }
  9440. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9441. S.PDiag(diag::warn_mixed_sign_comparison)
  9442. << LHS->getType() << RHS->getType()
  9443. << LHS->getSourceRange() << RHS->getSourceRange());
  9444. }
  9445. /// Analyzes an attempt to assign the given value to a bitfield.
  9446. ///
  9447. /// Returns true if there was something fishy about the attempt.
  9448. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  9449. SourceLocation InitLoc) {
  9450. assert(Bitfield->isBitField());
  9451. if (Bitfield->isInvalidDecl())
  9452. return false;
  9453. // White-list bool bitfields.
  9454. QualType BitfieldType = Bitfield->getType();
  9455. if (BitfieldType->isBooleanType())
  9456. return false;
  9457. if (BitfieldType->isEnumeralType()) {
  9458. EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
  9459. // If the underlying enum type was not explicitly specified as an unsigned
  9460. // type and the enum contain only positive values, MSVC++ will cause an
  9461. // inconsistency by storing this as a signed type.
  9462. if (S.getLangOpts().CPlusPlus11 &&
  9463. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  9464. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  9465. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  9466. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  9467. << BitfieldEnumDecl->getNameAsString();
  9468. }
  9469. }
  9470. if (Bitfield->getType()->isBooleanType())
  9471. return false;
  9472. // Ignore value- or type-dependent expressions.
  9473. if (Bitfield->getBitWidth()->isValueDependent() ||
  9474. Bitfield->getBitWidth()->isTypeDependent() ||
  9475. Init->isValueDependent() ||
  9476. Init->isTypeDependent())
  9477. return false;
  9478. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  9479. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  9480. Expr::EvalResult Result;
  9481. if (!OriginalInit->EvaluateAsInt(Result, S.Context,
  9482. Expr::SE_AllowSideEffects)) {
  9483. // The RHS is not constant. If the RHS has an enum type, make sure the
  9484. // bitfield is wide enough to hold all the values of the enum without
  9485. // truncation.
  9486. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  9487. EnumDecl *ED = EnumTy->getDecl();
  9488. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  9489. // Enum types are implicitly signed on Windows, so check if there are any
  9490. // negative enumerators to see if the enum was intended to be signed or
  9491. // not.
  9492. bool SignedEnum = ED->getNumNegativeBits() > 0;
  9493. // Check for surprising sign changes when assigning enum values to a
  9494. // bitfield of different signedness. If the bitfield is signed and we
  9495. // have exactly the right number of bits to store this unsigned enum,
  9496. // suggest changing the enum to an unsigned type. This typically happens
  9497. // on Windows where unfixed enums always use an underlying type of 'int'.
  9498. unsigned DiagID = 0;
  9499. if (SignedEnum && !SignedBitfield) {
  9500. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  9501. } else if (SignedBitfield && !SignedEnum &&
  9502. ED->getNumPositiveBits() == FieldWidth) {
  9503. DiagID = diag::warn_signed_bitfield_enum_conversion;
  9504. }
  9505. if (DiagID) {
  9506. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  9507. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  9508. SourceRange TypeRange =
  9509. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  9510. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  9511. << SignedEnum << TypeRange;
  9512. }
  9513. // Compute the required bitwidth. If the enum has negative values, we need
  9514. // one more bit than the normal number of positive bits to represent the
  9515. // sign bit.
  9516. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  9517. ED->getNumNegativeBits())
  9518. : ED->getNumPositiveBits();
  9519. // Check the bitwidth.
  9520. if (BitsNeeded > FieldWidth) {
  9521. Expr *WidthExpr = Bitfield->getBitWidth();
  9522. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  9523. << Bitfield << ED;
  9524. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  9525. << BitsNeeded << ED << WidthExpr->getSourceRange();
  9526. }
  9527. }
  9528. return false;
  9529. }
  9530. llvm::APSInt Value = Result.Val.getInt();
  9531. unsigned OriginalWidth = Value.getBitWidth();
  9532. if (!Value.isSigned() || Value.isNegative())
  9533. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  9534. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  9535. OriginalWidth = Value.getMinSignedBits();
  9536. if (OriginalWidth <= FieldWidth)
  9537. return false;
  9538. // Compute the value which the bitfield will contain.
  9539. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  9540. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  9541. // Check whether the stored value is equal to the original value.
  9542. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  9543. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  9544. return false;
  9545. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  9546. // therefore don't strictly fit into a signed bitfield of width 1.
  9547. if (FieldWidth == 1 && Value == 1)
  9548. return false;
  9549. std::string PrettyValue = Value.toString(10);
  9550. std::string PrettyTrunc = TruncatedValue.toString(10);
  9551. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  9552. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  9553. << Init->getSourceRange();
  9554. return true;
  9555. }
  9556. /// Analyze the given simple or compound assignment for warning-worthy
  9557. /// operations.
  9558. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  9559. // Just recurse on the LHS.
  9560. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9561. // We want to recurse on the RHS as normal unless we're assigning to
  9562. // a bitfield.
  9563. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  9564. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  9565. E->getOperatorLoc())) {
  9566. // Recurse, ignoring any implicit conversions on the RHS.
  9567. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  9568. E->getOperatorLoc());
  9569. }
  9570. }
  9571. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9572. // Diagnose implicitly sequentially-consistent atomic assignment.
  9573. if (E->getLHS()->getType()->isAtomicType())
  9574. S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  9575. }
  9576. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9577. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  9578. SourceLocation CContext, unsigned diag,
  9579. bool pruneControlFlow = false) {
  9580. if (pruneControlFlow) {
  9581. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9582. S.PDiag(diag)
  9583. << SourceType << T << E->getSourceRange()
  9584. << SourceRange(CContext));
  9585. return;
  9586. }
  9587. S.Diag(E->getExprLoc(), diag)
  9588. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  9589. }
  9590. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9591. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  9592. SourceLocation CContext,
  9593. unsigned diag, bool pruneControlFlow = false) {
  9594. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  9595. }
  9596. /// Diagnose an implicit cast from a floating point value to an integer value.
  9597. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  9598. SourceLocation CContext) {
  9599. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  9600. const bool PruneWarnings = S.inTemplateInstantiation();
  9601. Expr *InnerE = E->IgnoreParenImpCasts();
  9602. // We also want to warn on, e.g., "int i = -1.234"
  9603. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  9604. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  9605. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  9606. const bool IsLiteral =
  9607. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  9608. llvm::APFloat Value(0.0);
  9609. bool IsConstant =
  9610. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  9611. if (!IsConstant) {
  9612. return DiagnoseImpCast(S, E, T, CContext,
  9613. diag::warn_impcast_float_integer, PruneWarnings);
  9614. }
  9615. bool isExact = false;
  9616. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  9617. T->hasUnsignedIntegerRepresentation());
  9618. llvm::APFloat::opStatus Result = Value.convertToInteger(
  9619. IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
  9620. if (Result == llvm::APFloat::opOK && isExact) {
  9621. if (IsLiteral) return;
  9622. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  9623. PruneWarnings);
  9624. }
  9625. // Conversion of a floating-point value to a non-bool integer where the
  9626. // integral part cannot be represented by the integer type is undefined.
  9627. if (!IsBool && Result == llvm::APFloat::opInvalidOp)
  9628. return DiagnoseImpCast(
  9629. S, E, T, CContext,
  9630. IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
  9631. : diag::warn_impcast_float_to_integer_out_of_range,
  9632. PruneWarnings);
  9633. unsigned DiagID = 0;
  9634. if (IsLiteral) {
  9635. // Warn on floating point literal to integer.
  9636. DiagID = diag::warn_impcast_literal_float_to_integer;
  9637. } else if (IntegerValue == 0) {
  9638. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  9639. return DiagnoseImpCast(S, E, T, CContext,
  9640. diag::warn_impcast_float_integer, PruneWarnings);
  9641. }
  9642. // Warn on non-zero to zero conversion.
  9643. DiagID = diag::warn_impcast_float_to_integer_zero;
  9644. } else {
  9645. if (IntegerValue.isUnsigned()) {
  9646. if (!IntegerValue.isMaxValue()) {
  9647. return DiagnoseImpCast(S, E, T, CContext,
  9648. diag::warn_impcast_float_integer, PruneWarnings);
  9649. }
  9650. } else { // IntegerValue.isSigned()
  9651. if (!IntegerValue.isMaxSignedValue() &&
  9652. !IntegerValue.isMinSignedValue()) {
  9653. return DiagnoseImpCast(S, E, T, CContext,
  9654. diag::warn_impcast_float_integer, PruneWarnings);
  9655. }
  9656. }
  9657. // Warn on evaluatable floating point expression to integer conversion.
  9658. DiagID = diag::warn_impcast_float_to_integer;
  9659. }
  9660. // FIXME: Force the precision of the source value down so we don't print
  9661. // digits which are usually useless (we don't really care here if we
  9662. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  9663. // would automatically print the shortest representation, but it's a bit
  9664. // tricky to implement.
  9665. SmallString<16> PrettySourceValue;
  9666. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  9667. precision = (precision * 59 + 195) / 196;
  9668. Value.toString(PrettySourceValue, precision);
  9669. SmallString<16> PrettyTargetValue;
  9670. if (IsBool)
  9671. PrettyTargetValue = Value.isZero() ? "false" : "true";
  9672. else
  9673. IntegerValue.toString(PrettyTargetValue);
  9674. if (PruneWarnings) {
  9675. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9676. S.PDiag(DiagID)
  9677. << E->getType() << T.getUnqualifiedType()
  9678. << PrettySourceValue << PrettyTargetValue
  9679. << E->getSourceRange() << SourceRange(CContext));
  9680. } else {
  9681. S.Diag(E->getExprLoc(), DiagID)
  9682. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  9683. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  9684. }
  9685. }
  9686. /// Analyze the given compound assignment for the possible losing of
  9687. /// floating-point precision.
  9688. static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
  9689. assert(isa<CompoundAssignOperator>(E) &&
  9690. "Must be compound assignment operation");
  9691. // Recurse on the LHS and RHS in here
  9692. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9693. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9694. if (E->getLHS()->getType()->isAtomicType())
  9695. S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
  9696. // Now check the outermost expression
  9697. const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
  9698. const auto *RBT = cast<CompoundAssignOperator>(E)
  9699. ->getComputationResultType()
  9700. ->getAs<BuiltinType>();
  9701. // The below checks assume source is floating point.
  9702. if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
  9703. // If source is floating point but target is an integer.
  9704. if (ResultBT->isInteger())
  9705. return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
  9706. E->getExprLoc(), diag::warn_impcast_float_integer);
  9707. if (!ResultBT->isFloatingPoint())
  9708. return;
  9709. // If both source and target are floating points, warn about losing precision.
  9710. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  9711. QualType(ResultBT, 0), QualType(RBT, 0));
  9712. if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
  9713. // warn about dropping FP rank.
  9714. DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
  9715. diag::warn_impcast_float_result_precision);
  9716. }
  9717. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  9718. IntRange Range) {
  9719. if (!Range.Width) return "0";
  9720. llvm::APSInt ValueInRange = Value;
  9721. ValueInRange.setIsSigned(!Range.NonNegative);
  9722. ValueInRange = ValueInRange.trunc(Range.Width);
  9723. return ValueInRange.toString(10);
  9724. }
  9725. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  9726. if (!isa<ImplicitCastExpr>(Ex))
  9727. return false;
  9728. Expr *InnerE = Ex->IgnoreParenImpCasts();
  9729. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  9730. const Type *Source =
  9731. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  9732. if (Target->isDependentType())
  9733. return false;
  9734. const BuiltinType *FloatCandidateBT =
  9735. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  9736. const Type *BoolCandidateType = ToBool ? Target : Source;
  9737. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  9738. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  9739. }
  9740. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  9741. SourceLocation CC) {
  9742. unsigned NumArgs = TheCall->getNumArgs();
  9743. for (unsigned i = 0; i < NumArgs; ++i) {
  9744. Expr *CurrA = TheCall->getArg(i);
  9745. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  9746. continue;
  9747. bool IsSwapped = ((i > 0) &&
  9748. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  9749. IsSwapped |= ((i < (NumArgs - 1)) &&
  9750. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  9751. if (IsSwapped) {
  9752. // Warn on this floating-point to bool conversion.
  9753. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  9754. CurrA->getType(), CC,
  9755. diag::warn_impcast_floating_point_to_bool);
  9756. }
  9757. }
  9758. }
  9759. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  9760. SourceLocation CC) {
  9761. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  9762. E->getExprLoc()))
  9763. return;
  9764. // Don't warn on functions which have return type nullptr_t.
  9765. if (isa<CallExpr>(E))
  9766. return;
  9767. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  9768. const Expr::NullPointerConstantKind NullKind =
  9769. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  9770. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  9771. return;
  9772. // Return if target type is a safe conversion.
  9773. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  9774. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  9775. return;
  9776. SourceLocation Loc = E->getSourceRange().getBegin();
  9777. // Venture through the macro stacks to get to the source of macro arguments.
  9778. // The new location is a better location than the complete location that was
  9779. // passed in.
  9780. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  9781. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  9782. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  9783. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  9784. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  9785. Loc, S.SourceMgr, S.getLangOpts());
  9786. if (MacroName == "NULL")
  9787. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
  9788. }
  9789. // Only warn if the null and context location are in the same macro expansion.
  9790. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  9791. return;
  9792. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  9793. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  9794. << FixItHint::CreateReplacement(Loc,
  9795. S.getFixItZeroLiteralForType(T, Loc));
  9796. }
  9797. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9798. ObjCArrayLiteral *ArrayLiteral);
  9799. static void
  9800. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9801. ObjCDictionaryLiteral *DictionaryLiteral);
  9802. /// Check a single element within a collection literal against the
  9803. /// target element type.
  9804. static void checkObjCCollectionLiteralElement(Sema &S,
  9805. QualType TargetElementType,
  9806. Expr *Element,
  9807. unsigned ElementKind) {
  9808. // Skip a bitcast to 'id' or qualified 'id'.
  9809. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  9810. if (ICE->getCastKind() == CK_BitCast &&
  9811. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  9812. Element = ICE->getSubExpr();
  9813. }
  9814. QualType ElementType = Element->getType();
  9815. ExprResult ElementResult(Element);
  9816. if (ElementType->getAs<ObjCObjectPointerType>() &&
  9817. S.CheckSingleAssignmentConstraints(TargetElementType,
  9818. ElementResult,
  9819. false, false)
  9820. != Sema::Compatible) {
  9821. S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
  9822. << ElementType << ElementKind << TargetElementType
  9823. << Element->getSourceRange();
  9824. }
  9825. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  9826. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  9827. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  9828. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  9829. }
  9830. /// Check an Objective-C array literal being converted to the given
  9831. /// target type.
  9832. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9833. ObjCArrayLiteral *ArrayLiteral) {
  9834. if (!S.NSArrayDecl)
  9835. return;
  9836. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9837. if (!TargetObjCPtr)
  9838. return;
  9839. if (TargetObjCPtr->isUnspecialized() ||
  9840. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9841. != S.NSArrayDecl->getCanonicalDecl())
  9842. return;
  9843. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9844. if (TypeArgs.size() != 1)
  9845. return;
  9846. QualType TargetElementType = TypeArgs[0];
  9847. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  9848. checkObjCCollectionLiteralElement(S, TargetElementType,
  9849. ArrayLiteral->getElement(I),
  9850. 0);
  9851. }
  9852. }
  9853. /// Check an Objective-C dictionary literal being converted to the given
  9854. /// target type.
  9855. static void
  9856. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9857. ObjCDictionaryLiteral *DictionaryLiteral) {
  9858. if (!S.NSDictionaryDecl)
  9859. return;
  9860. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9861. if (!TargetObjCPtr)
  9862. return;
  9863. if (TargetObjCPtr->isUnspecialized() ||
  9864. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9865. != S.NSDictionaryDecl->getCanonicalDecl())
  9866. return;
  9867. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9868. if (TypeArgs.size() != 2)
  9869. return;
  9870. QualType TargetKeyType = TypeArgs[0];
  9871. QualType TargetObjectType = TypeArgs[1];
  9872. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  9873. auto Element = DictionaryLiteral->getKeyValueElement(I);
  9874. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  9875. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  9876. }
  9877. }
  9878. // Helper function to filter out cases for constant width constant conversion.
  9879. // Don't warn on char array initialization or for non-decimal values.
  9880. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  9881. SourceLocation CC) {
  9882. // If initializing from a constant, and the constant starts with '0',
  9883. // then it is a binary, octal, or hexadecimal. Allow these constants
  9884. // to fill all the bits, even if there is a sign change.
  9885. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  9886. const char FirstLiteralCharacter =
  9887. S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
  9888. if (FirstLiteralCharacter == '0')
  9889. return false;
  9890. }
  9891. // If the CC location points to a '{', and the type is char, then assume
  9892. // assume it is an array initialization.
  9893. if (CC.isValid() && T->isCharType()) {
  9894. const char FirstContextCharacter =
  9895. S.getSourceManager().getCharacterData(CC)[0];
  9896. if (FirstContextCharacter == '{')
  9897. return false;
  9898. }
  9899. return true;
  9900. }
  9901. static void
  9902. CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
  9903. bool *ICContext = nullptr) {
  9904. if (E->isTypeDependent() || E->isValueDependent()) return;
  9905. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  9906. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  9907. if (Source == Target) return;
  9908. if (Target->isDependentType()) return;
  9909. // If the conversion context location is invalid don't complain. We also
  9910. // don't want to emit a warning if the issue occurs from the expansion of
  9911. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  9912. // delay this check as long as possible. Once we detect we are in that
  9913. // scenario, we just return.
  9914. if (CC.isInvalid())
  9915. return;
  9916. if (Source->isAtomicType())
  9917. S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
  9918. // Diagnose implicit casts to bool.
  9919. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  9920. if (isa<StringLiteral>(E))
  9921. // Warn on string literal to bool. Checks for string literals in logical
  9922. // and expressions, for instance, assert(0 && "error here"), are
  9923. // prevented by a check in AnalyzeImplicitConversions().
  9924. return DiagnoseImpCast(S, E, T, CC,
  9925. diag::warn_impcast_string_literal_to_bool);
  9926. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  9927. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  9928. // This covers the literal expressions that evaluate to Objective-C
  9929. // objects.
  9930. return DiagnoseImpCast(S, E, T, CC,
  9931. diag::warn_impcast_objective_c_literal_to_bool);
  9932. }
  9933. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  9934. // Warn on pointer to bool conversion that is always true.
  9935. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  9936. SourceRange(CC));
  9937. }
  9938. }
  9939. // Check implicit casts from Objective-C collection literals to specialized
  9940. // collection types, e.g., NSArray<NSString *> *.
  9941. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  9942. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  9943. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  9944. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  9945. // Strip vector types.
  9946. if (isa<VectorType>(Source)) {
  9947. if (!isa<VectorType>(Target)) {
  9948. if (S.SourceMgr.isInSystemMacro(CC))
  9949. return;
  9950. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  9951. }
  9952. // If the vector cast is cast between two vectors of the same size, it is
  9953. // a bitcast, not a conversion.
  9954. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  9955. return;
  9956. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  9957. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  9958. }
  9959. if (auto VecTy = dyn_cast<VectorType>(Target))
  9960. Target = VecTy->getElementType().getTypePtr();
  9961. // Strip complex types.
  9962. if (isa<ComplexType>(Source)) {
  9963. if (!isa<ComplexType>(Target)) {
  9964. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  9965. return;
  9966. return DiagnoseImpCast(S, E, T, CC,
  9967. S.getLangOpts().CPlusPlus
  9968. ? diag::err_impcast_complex_scalar
  9969. : diag::warn_impcast_complex_scalar);
  9970. }
  9971. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  9972. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  9973. }
  9974. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  9975. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  9976. // If the source is floating point...
  9977. if (SourceBT && SourceBT->isFloatingPoint()) {
  9978. // ...and the target is floating point...
  9979. if (TargetBT && TargetBT->isFloatingPoint()) {
  9980. // ...then warn if we're dropping FP rank.
  9981. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  9982. QualType(SourceBT, 0), QualType(TargetBT, 0));
  9983. if (Order > 0) {
  9984. // Don't warn about float constants that are precisely
  9985. // representable in the target type.
  9986. Expr::EvalResult result;
  9987. if (E->EvaluateAsRValue(result, S.Context)) {
  9988. // Value might be a float, a float vector, or a float complex.
  9989. if (IsSameFloatAfterCast(result.Val,
  9990. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  9991. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  9992. return;
  9993. }
  9994. if (S.SourceMgr.isInSystemMacro(CC))
  9995. return;
  9996. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  9997. }
  9998. // ... or possibly if we're increasing rank, too
  9999. else if (Order < 0) {
  10000. if (S.SourceMgr.isInSystemMacro(CC))
  10001. return;
  10002. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  10003. }
  10004. return;
  10005. }
  10006. // If the target is integral, always warn.
  10007. if (TargetBT && TargetBT->isInteger()) {
  10008. if (S.SourceMgr.isInSystemMacro(CC))
  10009. return;
  10010. DiagnoseFloatingImpCast(S, E, T, CC);
  10011. }
  10012. // Detect the case where a call result is converted from floating-point to
  10013. // to bool, and the final argument to the call is converted from bool, to
  10014. // discover this typo:
  10015. //
  10016. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  10017. //
  10018. // FIXME: This is an incredibly special case; is there some more general
  10019. // way to detect this class of misplaced-parentheses bug?
  10020. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  10021. // Check last argument of function call to see if it is an
  10022. // implicit cast from a type matching the type the result
  10023. // is being cast to.
  10024. CallExpr *CEx = cast<CallExpr>(E);
  10025. if (unsigned NumArgs = CEx->getNumArgs()) {
  10026. Expr *LastA = CEx->getArg(NumArgs - 1);
  10027. Expr *InnerE = LastA->IgnoreParenImpCasts();
  10028. if (isa<ImplicitCastExpr>(LastA) &&
  10029. InnerE->getType()->isBooleanType()) {
  10030. // Warn on this floating-point to bool conversion
  10031. DiagnoseImpCast(S, E, T, CC,
  10032. diag::warn_impcast_floating_point_to_bool);
  10033. }
  10034. }
  10035. }
  10036. return;
  10037. }
  10038. // Valid casts involving fixed point types should be accounted for here.
  10039. if (Source->isFixedPointType()) {
  10040. if (Target->isUnsaturatedFixedPointType()) {
  10041. Expr::EvalResult Result;
  10042. if (E->EvaluateAsFixedPoint(Result, S.Context,
  10043. Expr::SE_AllowSideEffects)) {
  10044. APFixedPoint Value = Result.Val.getFixedPoint();
  10045. APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
  10046. APFixedPoint MinVal = S.Context.getFixedPointMin(T);
  10047. if (Value > MaxVal || Value < MinVal) {
  10048. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10049. S.PDiag(diag::warn_impcast_fixed_point_range)
  10050. << Value.toString() << T
  10051. << E->getSourceRange()
  10052. << clang::SourceRange(CC));
  10053. return;
  10054. }
  10055. }
  10056. } else if (Target->isIntegerType()) {
  10057. Expr::EvalResult Result;
  10058. if (E->EvaluateAsFixedPoint(Result, S.Context,
  10059. Expr::SE_AllowSideEffects)) {
  10060. APFixedPoint FXResult = Result.Val.getFixedPoint();
  10061. bool Overflowed;
  10062. llvm::APSInt IntResult = FXResult.convertToInt(
  10063. S.Context.getIntWidth(T),
  10064. Target->isSignedIntegerOrEnumerationType(), &Overflowed);
  10065. if (Overflowed) {
  10066. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10067. S.PDiag(diag::warn_impcast_fixed_point_range)
  10068. << FXResult.toString() << T
  10069. << E->getSourceRange()
  10070. << clang::SourceRange(CC));
  10071. return;
  10072. }
  10073. }
  10074. }
  10075. } else if (Target->isUnsaturatedFixedPointType()) {
  10076. if (Source->isIntegerType()) {
  10077. Expr::EvalResult Result;
  10078. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
  10079. llvm::APSInt Value = Result.Val.getInt();
  10080. bool Overflowed;
  10081. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  10082. Value, S.Context.getFixedPointSemantics(T), &Overflowed);
  10083. if (Overflowed) {
  10084. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10085. S.PDiag(diag::warn_impcast_fixed_point_range)
  10086. << Value.toString(/*radix=*/10) << T
  10087. << E->getSourceRange()
  10088. << clang::SourceRange(CC));
  10089. return;
  10090. }
  10091. }
  10092. }
  10093. }
  10094. DiagnoseNullConversion(S, E, T, CC);
  10095. S.DiscardMisalignedMemberAddress(Target, E);
  10096. if (!Source->isIntegerType() || !Target->isIntegerType())
  10097. return;
  10098. // TODO: remove this early return once the false positives for constant->bool
  10099. // in templates, macros, etc, are reduced or removed.
  10100. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  10101. return;
  10102. IntRange SourceRange = GetExprRange(S.Context, E);
  10103. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  10104. if (SourceRange.Width > TargetRange.Width) {
  10105. // If the source is a constant, use a default-on diagnostic.
  10106. // TODO: this should happen for bitfield stores, too.
  10107. Expr::EvalResult Result;
  10108. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
  10109. llvm::APSInt Value(32);
  10110. Value = Result.Val.getInt();
  10111. if (S.SourceMgr.isInSystemMacro(CC))
  10112. return;
  10113. std::string PrettySourceValue = Value.toString(10);
  10114. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10115. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10116. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10117. << PrettySourceValue << PrettyTargetValue
  10118. << E->getType() << T << E->getSourceRange()
  10119. << clang::SourceRange(CC));
  10120. return;
  10121. }
  10122. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  10123. if (S.SourceMgr.isInSystemMacro(CC))
  10124. return;
  10125. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  10126. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  10127. /* pruneControlFlow */ true);
  10128. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  10129. }
  10130. if (TargetRange.Width > SourceRange.Width) {
  10131. if (auto *UO = dyn_cast<UnaryOperator>(E))
  10132. if (UO->getOpcode() == UO_Minus)
  10133. if (Source->isUnsignedIntegerType()) {
  10134. if (Target->isUnsignedIntegerType())
  10135. return DiagnoseImpCast(S, E, T, CC,
  10136. diag::warn_impcast_high_order_zero_bits);
  10137. if (Target->isSignedIntegerType())
  10138. return DiagnoseImpCast(S, E, T, CC,
  10139. diag::warn_impcast_nonnegative_result);
  10140. }
  10141. }
  10142. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  10143. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  10144. // Warn when doing a signed to signed conversion, warn if the positive
  10145. // source value is exactly the width of the target type, which will
  10146. // cause a negative value to be stored.
  10147. Expr::EvalResult Result;
  10148. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
  10149. !S.SourceMgr.isInSystemMacro(CC)) {
  10150. llvm::APSInt Value = Result.Val.getInt();
  10151. if (isSameWidthConstantConversion(S, E, T, CC)) {
  10152. std::string PrettySourceValue = Value.toString(10);
  10153. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10154. S.DiagRuntimeBehavior(
  10155. E->getExprLoc(), E,
  10156. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10157. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10158. << E->getSourceRange() << clang::SourceRange(CC));
  10159. return;
  10160. }
  10161. }
  10162. // Fall through for non-constants to give a sign conversion warning.
  10163. }
  10164. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  10165. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  10166. SourceRange.Width == TargetRange.Width)) {
  10167. if (S.SourceMgr.isInSystemMacro(CC))
  10168. return;
  10169. unsigned DiagID = diag::warn_impcast_integer_sign;
  10170. // Traditionally, gcc has warned about this under -Wsign-compare.
  10171. // We also want to warn about it in -Wconversion.
  10172. // So if -Wconversion is off, use a completely identical diagnostic
  10173. // in the sign-compare group.
  10174. // The conditional-checking code will
  10175. if (ICContext) {
  10176. DiagID = diag::warn_impcast_integer_sign_conditional;
  10177. *ICContext = true;
  10178. }
  10179. return DiagnoseImpCast(S, E, T, CC, DiagID);
  10180. }
  10181. // Diagnose conversions between different enumeration types.
  10182. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  10183. // type, to give us better diagnostics.
  10184. QualType SourceType = E->getType();
  10185. if (!S.getLangOpts().CPlusPlus) {
  10186. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10187. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  10188. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  10189. SourceType = S.Context.getTypeDeclType(Enum);
  10190. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  10191. }
  10192. }
  10193. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  10194. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  10195. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  10196. TargetEnum->getDecl()->hasNameForLinkage() &&
  10197. SourceEnum != TargetEnum) {
  10198. if (S.SourceMgr.isInSystemMacro(CC))
  10199. return;
  10200. return DiagnoseImpCast(S, E, SourceType, T, CC,
  10201. diag::warn_impcast_different_enum_types);
  10202. }
  10203. }
  10204. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10205. SourceLocation CC, QualType T);
  10206. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  10207. SourceLocation CC, bool &ICContext) {
  10208. E = E->IgnoreParenImpCasts();
  10209. if (isa<ConditionalOperator>(E))
  10210. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  10211. AnalyzeImplicitConversions(S, E, CC);
  10212. if (E->getType() != T)
  10213. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  10214. }
  10215. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10216. SourceLocation CC, QualType T) {
  10217. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  10218. bool Suspicious = false;
  10219. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  10220. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  10221. // If -Wconversion would have warned about either of the candidates
  10222. // for a signedness conversion to the context type...
  10223. if (!Suspicious) return;
  10224. // ...but it's currently ignored...
  10225. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  10226. return;
  10227. // ...then check whether it would have warned about either of the
  10228. // candidates for a signedness conversion to the condition type.
  10229. if (E->getType() == T) return;
  10230. Suspicious = false;
  10231. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  10232. E->getType(), CC, &Suspicious);
  10233. if (!Suspicious)
  10234. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  10235. E->getType(), CC, &Suspicious);
  10236. }
  10237. /// Check conversion of given expression to boolean.
  10238. /// Input argument E is a logical expression.
  10239. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  10240. if (S.getLangOpts().Bool)
  10241. return;
  10242. if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
  10243. return;
  10244. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  10245. }
  10246. /// AnalyzeImplicitConversions - Find and report any interesting
  10247. /// implicit conversions in the given expression. There are a couple
  10248. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  10249. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
  10250. SourceLocation CC) {
  10251. QualType T = OrigE->getType();
  10252. Expr *E = OrigE->IgnoreParenImpCasts();
  10253. if (E->isTypeDependent() || E->isValueDependent())
  10254. return;
  10255. // For conditional operators, we analyze the arguments as if they
  10256. // were being fed directly into the output.
  10257. if (isa<ConditionalOperator>(E)) {
  10258. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  10259. CheckConditionalOperator(S, CO, CC, T);
  10260. return;
  10261. }
  10262. // Check implicit argument conversions for function calls.
  10263. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  10264. CheckImplicitArgumentConversions(S, Call, CC);
  10265. // Go ahead and check any implicit conversions we might have skipped.
  10266. // The non-canonical typecheck is just an optimization;
  10267. // CheckImplicitConversion will filter out dead implicit conversions.
  10268. if (E->getType() != T)
  10269. CheckImplicitConversion(S, E, T, CC);
  10270. // Now continue drilling into this expression.
  10271. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  10272. // The bound subexpressions in a PseudoObjectExpr are not reachable
  10273. // as transitive children.
  10274. // FIXME: Use a more uniform representation for this.
  10275. for (auto *SE : POE->semantics())
  10276. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  10277. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  10278. }
  10279. // Skip past explicit casts.
  10280. if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
  10281. E = CE->getSubExpr()->IgnoreParenImpCasts();
  10282. if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
  10283. S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  10284. return AnalyzeImplicitConversions(S, E, CC);
  10285. }
  10286. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10287. // Do a somewhat different check with comparison operators.
  10288. if (BO->isComparisonOp())
  10289. return AnalyzeComparison(S, BO);
  10290. // And with simple assignments.
  10291. if (BO->getOpcode() == BO_Assign)
  10292. return AnalyzeAssignment(S, BO);
  10293. // And with compound assignments.
  10294. if (BO->isAssignmentOp())
  10295. return AnalyzeCompoundAssignment(S, BO);
  10296. }
  10297. // These break the otherwise-useful invariant below. Fortunately,
  10298. // we don't really need to recurse into them, because any internal
  10299. // expressions should have been analyzed already when they were
  10300. // built into statements.
  10301. if (isa<StmtExpr>(E)) return;
  10302. // Don't descend into unevaluated contexts.
  10303. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  10304. // Now just recurse over the expression's children.
  10305. CC = E->getExprLoc();
  10306. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  10307. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  10308. for (Stmt *SubStmt : E->children()) {
  10309. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  10310. if (!ChildExpr)
  10311. continue;
  10312. if (IsLogicalAndOperator &&
  10313. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  10314. // Ignore checking string literals that are in logical and operators.
  10315. // This is a common pattern for asserts.
  10316. continue;
  10317. AnalyzeImplicitConversions(S, ChildExpr, CC);
  10318. }
  10319. if (BO && BO->isLogicalOp()) {
  10320. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  10321. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10322. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10323. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  10324. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10325. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10326. }
  10327. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  10328. if (U->getOpcode() == UO_LNot) {
  10329. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  10330. } else if (U->getOpcode() != UO_AddrOf) {
  10331. if (U->getSubExpr()->getType()->isAtomicType())
  10332. S.Diag(U->getSubExpr()->getBeginLoc(),
  10333. diag::warn_atomic_implicit_seq_cst);
  10334. }
  10335. }
  10336. }
  10337. /// Diagnose integer type and any valid implicit conversion to it.
  10338. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  10339. // Taking into account implicit conversions,
  10340. // allow any integer.
  10341. if (!E->getType()->isIntegerType()) {
  10342. S.Diag(E->getBeginLoc(),
  10343. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  10344. return true;
  10345. }
  10346. // Potentially emit standard warnings for implicit conversions if enabled
  10347. // using -Wconversion.
  10348. CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
  10349. return false;
  10350. }
  10351. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  10352. // Returns true when emitting a warning about taking the address of a reference.
  10353. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  10354. const PartialDiagnostic &PD) {
  10355. E = E->IgnoreParenImpCasts();
  10356. const FunctionDecl *FD = nullptr;
  10357. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  10358. if (!DRE->getDecl()->getType()->isReferenceType())
  10359. return false;
  10360. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10361. if (!M->getMemberDecl()->getType()->isReferenceType())
  10362. return false;
  10363. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  10364. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  10365. return false;
  10366. FD = Call->getDirectCallee();
  10367. } else {
  10368. return false;
  10369. }
  10370. SemaRef.Diag(E->getExprLoc(), PD);
  10371. // If possible, point to location of function.
  10372. if (FD) {
  10373. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  10374. }
  10375. return true;
  10376. }
  10377. // Returns true if the SourceLocation is expanded from any macro body.
  10378. // Returns false if the SourceLocation is invalid, is from not in a macro
  10379. // expansion, or is from expanded from a top-level macro argument.
  10380. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  10381. if (Loc.isInvalid())
  10382. return false;
  10383. while (Loc.isMacroID()) {
  10384. if (SM.isMacroBodyExpansion(Loc))
  10385. return true;
  10386. Loc = SM.getImmediateMacroCallerLoc(Loc);
  10387. }
  10388. return false;
  10389. }
  10390. /// Diagnose pointers that are always non-null.
  10391. /// \param E the expression containing the pointer
  10392. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  10393. /// compared to a null pointer
  10394. /// \param IsEqual True when the comparison is equal to a null pointer
  10395. /// \param Range Extra SourceRange to highlight in the diagnostic
  10396. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  10397. Expr::NullPointerConstantKind NullKind,
  10398. bool IsEqual, SourceRange Range) {
  10399. if (!E)
  10400. return;
  10401. // Don't warn inside macros.
  10402. if (E->getExprLoc().isMacroID()) {
  10403. const SourceManager &SM = getSourceManager();
  10404. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  10405. IsInAnyMacroBody(SM, Range.getBegin()))
  10406. return;
  10407. }
  10408. E = E->IgnoreImpCasts();
  10409. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  10410. if (isa<CXXThisExpr>(E)) {
  10411. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  10412. : diag::warn_this_bool_conversion;
  10413. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  10414. return;
  10415. }
  10416. bool IsAddressOf = false;
  10417. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10418. if (UO->getOpcode() != UO_AddrOf)
  10419. return;
  10420. IsAddressOf = true;
  10421. E = UO->getSubExpr();
  10422. }
  10423. if (IsAddressOf) {
  10424. unsigned DiagID = IsCompare
  10425. ? diag::warn_address_of_reference_null_compare
  10426. : diag::warn_address_of_reference_bool_conversion;
  10427. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  10428. << IsEqual;
  10429. if (CheckForReference(*this, E, PD)) {
  10430. return;
  10431. }
  10432. }
  10433. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  10434. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  10435. std::string Str;
  10436. llvm::raw_string_ostream S(Str);
  10437. E->printPretty(S, nullptr, getPrintingPolicy());
  10438. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  10439. : diag::warn_cast_nonnull_to_bool;
  10440. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  10441. << E->getSourceRange() << Range << IsEqual;
  10442. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  10443. };
  10444. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  10445. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  10446. if (auto *Callee = Call->getDirectCallee()) {
  10447. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  10448. ComplainAboutNonnullParamOrCall(A);
  10449. return;
  10450. }
  10451. }
  10452. }
  10453. // Expect to find a single Decl. Skip anything more complicated.
  10454. ValueDecl *D = nullptr;
  10455. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  10456. D = R->getDecl();
  10457. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10458. D = M->getMemberDecl();
  10459. }
  10460. // Weak Decls can be null.
  10461. if (!D || D->isWeak())
  10462. return;
  10463. // Check for parameter decl with nonnull attribute
  10464. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  10465. if (getCurFunction() &&
  10466. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  10467. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  10468. ComplainAboutNonnullParamOrCall(A);
  10469. return;
  10470. }
  10471. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  10472. // Skip function template not specialized yet.
  10473. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  10474. return;
  10475. auto ParamIter = llvm::find(FD->parameters(), PV);
  10476. assert(ParamIter != FD->param_end());
  10477. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  10478. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  10479. if (!NonNull->args_size()) {
  10480. ComplainAboutNonnullParamOrCall(NonNull);
  10481. return;
  10482. }
  10483. for (const ParamIdx &ArgNo : NonNull->args()) {
  10484. if (ArgNo.getASTIndex() == ParamNo) {
  10485. ComplainAboutNonnullParamOrCall(NonNull);
  10486. return;
  10487. }
  10488. }
  10489. }
  10490. }
  10491. }
  10492. }
  10493. QualType T = D->getType();
  10494. const bool IsArray = T->isArrayType();
  10495. const bool IsFunction = T->isFunctionType();
  10496. // Address of function is used to silence the function warning.
  10497. if (IsAddressOf && IsFunction) {
  10498. return;
  10499. }
  10500. // Found nothing.
  10501. if (!IsAddressOf && !IsFunction && !IsArray)
  10502. return;
  10503. // Pretty print the expression for the diagnostic.
  10504. std::string Str;
  10505. llvm::raw_string_ostream S(Str);
  10506. E->printPretty(S, nullptr, getPrintingPolicy());
  10507. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  10508. : diag::warn_impcast_pointer_to_bool;
  10509. enum {
  10510. AddressOf,
  10511. FunctionPointer,
  10512. ArrayPointer
  10513. } DiagType;
  10514. if (IsAddressOf)
  10515. DiagType = AddressOf;
  10516. else if (IsFunction)
  10517. DiagType = FunctionPointer;
  10518. else if (IsArray)
  10519. DiagType = ArrayPointer;
  10520. else
  10521. llvm_unreachable("Could not determine diagnostic.");
  10522. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  10523. << Range << IsEqual;
  10524. if (!IsFunction)
  10525. return;
  10526. // Suggest '&' to silence the function warning.
  10527. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  10528. << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
  10529. // Check to see if '()' fixit should be emitted.
  10530. QualType ReturnType;
  10531. UnresolvedSet<4> NonTemplateOverloads;
  10532. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  10533. if (ReturnType.isNull())
  10534. return;
  10535. if (IsCompare) {
  10536. // There are two cases here. If there is null constant, the only suggest
  10537. // for a pointer return type. If the null is 0, then suggest if the return
  10538. // type is a pointer or an integer type.
  10539. if (!ReturnType->isPointerType()) {
  10540. if (NullKind == Expr::NPCK_ZeroExpression ||
  10541. NullKind == Expr::NPCK_ZeroLiteral) {
  10542. if (!ReturnType->isIntegerType())
  10543. return;
  10544. } else {
  10545. return;
  10546. }
  10547. }
  10548. } else { // !IsCompare
  10549. // For function to bool, only suggest if the function pointer has bool
  10550. // return type.
  10551. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  10552. return;
  10553. }
  10554. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  10555. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
  10556. }
  10557. /// Diagnoses "dangerous" implicit conversions within the given
  10558. /// expression (which is a full expression). Implements -Wconversion
  10559. /// and -Wsign-compare.
  10560. ///
  10561. /// \param CC the "context" location of the implicit conversion, i.e.
  10562. /// the most location of the syntactic entity requiring the implicit
  10563. /// conversion
  10564. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  10565. // Don't diagnose in unevaluated contexts.
  10566. if (isUnevaluatedContext())
  10567. return;
  10568. // Don't diagnose for value- or type-dependent expressions.
  10569. if (E->isTypeDependent() || E->isValueDependent())
  10570. return;
  10571. // Check for array bounds violations in cases where the check isn't triggered
  10572. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  10573. // ArraySubscriptExpr is on the RHS of a variable initialization.
  10574. CheckArrayAccess(E);
  10575. // This is not the right CC for (e.g.) a variable initialization.
  10576. AnalyzeImplicitConversions(*this, E, CC);
  10577. }
  10578. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  10579. /// Input argument E is a logical expression.
  10580. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  10581. ::CheckBoolLikeConversion(*this, E, CC);
  10582. }
  10583. /// Diagnose when expression is an integer constant expression and its evaluation
  10584. /// results in integer overflow
  10585. void Sema::CheckForIntOverflow (Expr *E) {
  10586. // Use a work list to deal with nested struct initializers.
  10587. SmallVector<Expr *, 2> Exprs(1, E);
  10588. do {
  10589. Expr *OriginalE = Exprs.pop_back_val();
  10590. Expr *E = OriginalE->IgnoreParenCasts();
  10591. if (isa<BinaryOperator>(E)) {
  10592. E->EvaluateForOverflow(Context);
  10593. continue;
  10594. }
  10595. if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
  10596. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  10597. else if (isa<ObjCBoxedExpr>(OriginalE))
  10598. E->EvaluateForOverflow(Context);
  10599. else if (auto Call = dyn_cast<CallExpr>(E))
  10600. Exprs.append(Call->arg_begin(), Call->arg_end());
  10601. else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
  10602. Exprs.append(Message->arg_begin(), Message->arg_end());
  10603. } while (!Exprs.empty());
  10604. }
  10605. namespace {
  10606. /// Visitor for expressions which looks for unsequenced operations on the
  10607. /// same object.
  10608. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  10609. using Base = EvaluatedExprVisitor<SequenceChecker>;
  10610. /// A tree of sequenced regions within an expression. Two regions are
  10611. /// unsequenced if one is an ancestor or a descendent of the other. When we
  10612. /// finish processing an expression with sequencing, such as a comma
  10613. /// expression, we fold its tree nodes into its parent, since they are
  10614. /// unsequenced with respect to nodes we will visit later.
  10615. class SequenceTree {
  10616. struct Value {
  10617. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  10618. unsigned Parent : 31;
  10619. unsigned Merged : 1;
  10620. };
  10621. SmallVector<Value, 8> Values;
  10622. public:
  10623. /// A region within an expression which may be sequenced with respect
  10624. /// to some other region.
  10625. class Seq {
  10626. friend class SequenceTree;
  10627. unsigned Index;
  10628. explicit Seq(unsigned N) : Index(N) {}
  10629. public:
  10630. Seq() : Index(0) {}
  10631. };
  10632. SequenceTree() { Values.push_back(Value(0)); }
  10633. Seq root() const { return Seq(0); }
  10634. /// Create a new sequence of operations, which is an unsequenced
  10635. /// subset of \p Parent. This sequence of operations is sequenced with
  10636. /// respect to other children of \p Parent.
  10637. Seq allocate(Seq Parent) {
  10638. Values.push_back(Value(Parent.Index));
  10639. return Seq(Values.size() - 1);
  10640. }
  10641. /// Merge a sequence of operations into its parent.
  10642. void merge(Seq S) {
  10643. Values[S.Index].Merged = true;
  10644. }
  10645. /// Determine whether two operations are unsequenced. This operation
  10646. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  10647. /// should have been merged into its parent as appropriate.
  10648. bool isUnsequenced(Seq Cur, Seq Old) {
  10649. unsigned C = representative(Cur.Index);
  10650. unsigned Target = representative(Old.Index);
  10651. while (C >= Target) {
  10652. if (C == Target)
  10653. return true;
  10654. C = Values[C].Parent;
  10655. }
  10656. return false;
  10657. }
  10658. private:
  10659. /// Pick a representative for a sequence.
  10660. unsigned representative(unsigned K) {
  10661. if (Values[K].Merged)
  10662. // Perform path compression as we go.
  10663. return Values[K].Parent = representative(Values[K].Parent);
  10664. return K;
  10665. }
  10666. };
  10667. /// An object for which we can track unsequenced uses.
  10668. using Object = NamedDecl *;
  10669. /// Different flavors of object usage which we track. We only track the
  10670. /// least-sequenced usage of each kind.
  10671. enum UsageKind {
  10672. /// A read of an object. Multiple unsequenced reads are OK.
  10673. UK_Use,
  10674. /// A modification of an object which is sequenced before the value
  10675. /// computation of the expression, such as ++n in C++.
  10676. UK_ModAsValue,
  10677. /// A modification of an object which is not sequenced before the value
  10678. /// computation of the expression, such as n++.
  10679. UK_ModAsSideEffect,
  10680. UK_Count = UK_ModAsSideEffect + 1
  10681. };
  10682. struct Usage {
  10683. Expr *Use;
  10684. SequenceTree::Seq Seq;
  10685. Usage() : Use(nullptr), Seq() {}
  10686. };
  10687. struct UsageInfo {
  10688. Usage Uses[UK_Count];
  10689. /// Have we issued a diagnostic for this variable already?
  10690. bool Diagnosed;
  10691. UsageInfo() : Uses(), Diagnosed(false) {}
  10692. };
  10693. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  10694. Sema &SemaRef;
  10695. /// Sequenced regions within the expression.
  10696. SequenceTree Tree;
  10697. /// Declaration modifications and references which we have seen.
  10698. UsageInfoMap UsageMap;
  10699. /// The region we are currently within.
  10700. SequenceTree::Seq Region;
  10701. /// Filled in with declarations which were modified as a side-effect
  10702. /// (that is, post-increment operations).
  10703. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  10704. /// Expressions to check later. We defer checking these to reduce
  10705. /// stack usage.
  10706. SmallVectorImpl<Expr *> &WorkList;
  10707. /// RAII object wrapping the visitation of a sequenced subexpression of an
  10708. /// expression. At the end of this process, the side-effects of the evaluation
  10709. /// become sequenced with respect to the value computation of the result, so
  10710. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  10711. /// UK_ModAsValue.
  10712. struct SequencedSubexpression {
  10713. SequencedSubexpression(SequenceChecker &Self)
  10714. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  10715. Self.ModAsSideEffect = &ModAsSideEffect;
  10716. }
  10717. ~SequencedSubexpression() {
  10718. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  10719. UsageInfo &U = Self.UsageMap[M.first];
  10720. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  10721. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  10722. SideEffectUsage = M.second;
  10723. }
  10724. Self.ModAsSideEffect = OldModAsSideEffect;
  10725. }
  10726. SequenceChecker &Self;
  10727. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  10728. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  10729. };
  10730. /// RAII object wrapping the visitation of a subexpression which we might
  10731. /// choose to evaluate as a constant. If any subexpression is evaluated and
  10732. /// found to be non-constant, this allows us to suppress the evaluation of
  10733. /// the outer expression.
  10734. class EvaluationTracker {
  10735. public:
  10736. EvaluationTracker(SequenceChecker &Self)
  10737. : Self(Self), Prev(Self.EvalTracker) {
  10738. Self.EvalTracker = this;
  10739. }
  10740. ~EvaluationTracker() {
  10741. Self.EvalTracker = Prev;
  10742. if (Prev)
  10743. Prev->EvalOK &= EvalOK;
  10744. }
  10745. bool evaluate(const Expr *E, bool &Result) {
  10746. if (!EvalOK || E->isValueDependent())
  10747. return false;
  10748. EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
  10749. return EvalOK;
  10750. }
  10751. private:
  10752. SequenceChecker &Self;
  10753. EvaluationTracker *Prev;
  10754. bool EvalOK = true;
  10755. } *EvalTracker = nullptr;
  10756. /// Find the object which is produced by the specified expression,
  10757. /// if any.
  10758. Object getObject(Expr *E, bool Mod) const {
  10759. E = E->IgnoreParenCasts();
  10760. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10761. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  10762. return getObject(UO->getSubExpr(), Mod);
  10763. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10764. if (BO->getOpcode() == BO_Comma)
  10765. return getObject(BO->getRHS(), Mod);
  10766. if (Mod && BO->isAssignmentOp())
  10767. return getObject(BO->getLHS(), Mod);
  10768. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  10769. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  10770. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  10771. return ME->getMemberDecl();
  10772. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10773. // FIXME: If this is a reference, map through to its value.
  10774. return DRE->getDecl();
  10775. return nullptr;
  10776. }
  10777. /// Note that an object was modified or used by an expression.
  10778. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  10779. Usage &U = UI.Uses[UK];
  10780. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  10781. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  10782. ModAsSideEffect->push_back(std::make_pair(O, U));
  10783. U.Use = Ref;
  10784. U.Seq = Region;
  10785. }
  10786. }
  10787. /// Check whether a modification or use conflicts with a prior usage.
  10788. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  10789. bool IsModMod) {
  10790. if (UI.Diagnosed)
  10791. return;
  10792. const Usage &U = UI.Uses[OtherKind];
  10793. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  10794. return;
  10795. Expr *Mod = U.Use;
  10796. Expr *ModOrUse = Ref;
  10797. if (OtherKind == UK_Use)
  10798. std::swap(Mod, ModOrUse);
  10799. SemaRef.DiagRuntimeBehavior(
  10800. Mod->getExprLoc(), {Mod, ModOrUse},
  10801. SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
  10802. : diag::warn_unsequenced_mod_use)
  10803. << O << SourceRange(ModOrUse->getExprLoc()));
  10804. UI.Diagnosed = true;
  10805. }
  10806. void notePreUse(Object O, Expr *Use) {
  10807. UsageInfo &U = UsageMap[O];
  10808. // Uses conflict with other modifications.
  10809. checkUsage(O, U, Use, UK_ModAsValue, false);
  10810. }
  10811. void notePostUse(Object O, Expr *Use) {
  10812. UsageInfo &U = UsageMap[O];
  10813. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  10814. addUsage(U, O, Use, UK_Use);
  10815. }
  10816. void notePreMod(Object O, Expr *Mod) {
  10817. UsageInfo &U = UsageMap[O];
  10818. // Modifications conflict with other modifications and with uses.
  10819. checkUsage(O, U, Mod, UK_ModAsValue, true);
  10820. checkUsage(O, U, Mod, UK_Use, false);
  10821. }
  10822. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  10823. UsageInfo &U = UsageMap[O];
  10824. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  10825. addUsage(U, O, Use, UK);
  10826. }
  10827. public:
  10828. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  10829. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  10830. Visit(E);
  10831. }
  10832. void VisitStmt(Stmt *S) {
  10833. // Skip all statements which aren't expressions for now.
  10834. }
  10835. void VisitExpr(Expr *E) {
  10836. // By default, just recurse to evaluated subexpressions.
  10837. Base::VisitStmt(E);
  10838. }
  10839. void VisitCastExpr(CastExpr *E) {
  10840. Object O = Object();
  10841. if (E->getCastKind() == CK_LValueToRValue)
  10842. O = getObject(E->getSubExpr(), false);
  10843. if (O)
  10844. notePreUse(O, E);
  10845. VisitExpr(E);
  10846. if (O)
  10847. notePostUse(O, E);
  10848. }
  10849. void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
  10850. SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
  10851. SequenceTree::Seq AfterRegion = Tree.allocate(Region);
  10852. SequenceTree::Seq OldRegion = Region;
  10853. {
  10854. SequencedSubexpression SeqBefore(*this);
  10855. Region = BeforeRegion;
  10856. Visit(SequencedBefore);
  10857. }
  10858. Region = AfterRegion;
  10859. Visit(SequencedAfter);
  10860. Region = OldRegion;
  10861. Tree.merge(BeforeRegion);
  10862. Tree.merge(AfterRegion);
  10863. }
  10864. void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
  10865. // C++17 [expr.sub]p1:
  10866. // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
  10867. // expression E1 is sequenced before the expression E2.
  10868. if (SemaRef.getLangOpts().CPlusPlus17)
  10869. VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
  10870. else
  10871. Base::VisitStmt(ASE);
  10872. }
  10873. void VisitBinComma(BinaryOperator *BO) {
  10874. // C++11 [expr.comma]p1:
  10875. // Every value computation and side effect associated with the left
  10876. // expression is sequenced before every value computation and side
  10877. // effect associated with the right expression.
  10878. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  10879. }
  10880. void VisitBinAssign(BinaryOperator *BO) {
  10881. // The modification is sequenced after the value computation of the LHS
  10882. // and RHS, so check it before inspecting the operands and update the
  10883. // map afterwards.
  10884. Object O = getObject(BO->getLHS(), true);
  10885. if (!O)
  10886. return VisitExpr(BO);
  10887. notePreMod(O, BO);
  10888. // C++11 [expr.ass]p7:
  10889. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  10890. // only once.
  10891. //
  10892. // Therefore, for a compound assignment operator, O is considered used
  10893. // everywhere except within the evaluation of E1 itself.
  10894. if (isa<CompoundAssignOperator>(BO))
  10895. notePreUse(O, BO);
  10896. Visit(BO->getLHS());
  10897. if (isa<CompoundAssignOperator>(BO))
  10898. notePostUse(O, BO);
  10899. Visit(BO->getRHS());
  10900. // C++11 [expr.ass]p1:
  10901. // the assignment is sequenced [...] before the value computation of the
  10902. // assignment expression.
  10903. // C11 6.5.16/3 has no such rule.
  10904. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  10905. : UK_ModAsSideEffect);
  10906. }
  10907. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  10908. VisitBinAssign(CAO);
  10909. }
  10910. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10911. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10912. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  10913. Object O = getObject(UO->getSubExpr(), true);
  10914. if (!O)
  10915. return VisitExpr(UO);
  10916. notePreMod(O, UO);
  10917. Visit(UO->getSubExpr());
  10918. // C++11 [expr.pre.incr]p1:
  10919. // the expression ++x is equivalent to x+=1
  10920. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  10921. : UK_ModAsSideEffect);
  10922. }
  10923. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  10924. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  10925. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  10926. Object O = getObject(UO->getSubExpr(), true);
  10927. if (!O)
  10928. return VisitExpr(UO);
  10929. notePreMod(O, UO);
  10930. Visit(UO->getSubExpr());
  10931. notePostMod(O, UO, UK_ModAsSideEffect);
  10932. }
  10933. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  10934. void VisitBinLOr(BinaryOperator *BO) {
  10935. // The side-effects of the LHS of an '&&' are sequenced before the
  10936. // value computation of the RHS, and hence before the value computation
  10937. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  10938. // as if they were unconditionally sequenced.
  10939. EvaluationTracker Eval(*this);
  10940. {
  10941. SequencedSubexpression Sequenced(*this);
  10942. Visit(BO->getLHS());
  10943. }
  10944. bool Result;
  10945. if (Eval.evaluate(BO->getLHS(), Result)) {
  10946. if (!Result)
  10947. Visit(BO->getRHS());
  10948. } else {
  10949. // Check for unsequenced operations in the RHS, treating it as an
  10950. // entirely separate evaluation.
  10951. //
  10952. // FIXME: If there are operations in the RHS which are unsequenced
  10953. // with respect to operations outside the RHS, and those operations
  10954. // are unconditionally evaluated, diagnose them.
  10955. WorkList.push_back(BO->getRHS());
  10956. }
  10957. }
  10958. void VisitBinLAnd(BinaryOperator *BO) {
  10959. EvaluationTracker Eval(*this);
  10960. {
  10961. SequencedSubexpression Sequenced(*this);
  10962. Visit(BO->getLHS());
  10963. }
  10964. bool Result;
  10965. if (Eval.evaluate(BO->getLHS(), Result)) {
  10966. if (Result)
  10967. Visit(BO->getRHS());
  10968. } else {
  10969. WorkList.push_back(BO->getRHS());
  10970. }
  10971. }
  10972. // Only visit the condition, unless we can be sure which subexpression will
  10973. // be chosen.
  10974. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  10975. EvaluationTracker Eval(*this);
  10976. {
  10977. SequencedSubexpression Sequenced(*this);
  10978. Visit(CO->getCond());
  10979. }
  10980. bool Result;
  10981. if (Eval.evaluate(CO->getCond(), Result))
  10982. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  10983. else {
  10984. WorkList.push_back(CO->getTrueExpr());
  10985. WorkList.push_back(CO->getFalseExpr());
  10986. }
  10987. }
  10988. void VisitCallExpr(CallExpr *CE) {
  10989. // C++11 [intro.execution]p15:
  10990. // When calling a function [...], every value computation and side effect
  10991. // associated with any argument expression, or with the postfix expression
  10992. // designating the called function, is sequenced before execution of every
  10993. // expression or statement in the body of the function [and thus before
  10994. // the value computation of its result].
  10995. SequencedSubexpression Sequenced(*this);
  10996. Base::VisitCallExpr(CE);
  10997. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  10998. }
  10999. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  11000. // This is a call, so all subexpressions are sequenced before the result.
  11001. SequencedSubexpression Sequenced(*this);
  11002. if (!CCE->isListInitialization())
  11003. return VisitExpr(CCE);
  11004. // In C++11, list initializations are sequenced.
  11005. SmallVector<SequenceTree::Seq, 32> Elts;
  11006. SequenceTree::Seq Parent = Region;
  11007. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  11008. E = CCE->arg_end();
  11009. I != E; ++I) {
  11010. Region = Tree.allocate(Parent);
  11011. Elts.push_back(Region);
  11012. Visit(*I);
  11013. }
  11014. // Forget that the initializers are sequenced.
  11015. Region = Parent;
  11016. for (unsigned I = 0; I < Elts.size(); ++I)
  11017. Tree.merge(Elts[I]);
  11018. }
  11019. void VisitInitListExpr(InitListExpr *ILE) {
  11020. if (!SemaRef.getLangOpts().CPlusPlus11)
  11021. return VisitExpr(ILE);
  11022. // In C++11, list initializations are sequenced.
  11023. SmallVector<SequenceTree::Seq, 32> Elts;
  11024. SequenceTree::Seq Parent = Region;
  11025. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  11026. Expr *E = ILE->getInit(I);
  11027. if (!E) continue;
  11028. Region = Tree.allocate(Parent);
  11029. Elts.push_back(Region);
  11030. Visit(E);
  11031. }
  11032. // Forget that the initializers are sequenced.
  11033. Region = Parent;
  11034. for (unsigned I = 0; I < Elts.size(); ++I)
  11035. Tree.merge(Elts[I]);
  11036. }
  11037. };
  11038. } // namespace
  11039. void Sema::CheckUnsequencedOperations(Expr *E) {
  11040. SmallVector<Expr *, 8> WorkList;
  11041. WorkList.push_back(E);
  11042. while (!WorkList.empty()) {
  11043. Expr *Item = WorkList.pop_back_val();
  11044. SequenceChecker(*this, Item, WorkList);
  11045. }
  11046. }
  11047. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  11048. bool IsConstexpr) {
  11049. CheckImplicitConversions(E, CheckLoc);
  11050. if (!E->isInstantiationDependent())
  11051. CheckUnsequencedOperations(E);
  11052. if (!IsConstexpr && !E->isValueDependent())
  11053. CheckForIntOverflow(E);
  11054. DiagnoseMisalignedMembers();
  11055. }
  11056. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  11057. FieldDecl *BitField,
  11058. Expr *Init) {
  11059. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  11060. }
  11061. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  11062. SourceLocation Loc) {
  11063. if (!PType->isVariablyModifiedType())
  11064. return;
  11065. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  11066. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  11067. return;
  11068. }
  11069. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  11070. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  11071. return;
  11072. }
  11073. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  11074. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  11075. return;
  11076. }
  11077. const ArrayType *AT = S.Context.getAsArrayType(PType);
  11078. if (!AT)
  11079. return;
  11080. if (AT->getSizeModifier() != ArrayType::Star) {
  11081. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  11082. return;
  11083. }
  11084. S.Diag(Loc, diag::err_array_star_in_function_definition);
  11085. }
  11086. /// CheckParmsForFunctionDef - Check that the parameters of the given
  11087. /// function are appropriate for the definition of a function. This
  11088. /// takes care of any checks that cannot be performed on the
  11089. /// declaration itself, e.g., that the types of each of the function
  11090. /// parameters are complete.
  11091. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  11092. bool CheckParameterNames) {
  11093. bool HasInvalidParm = false;
  11094. for (ParmVarDecl *Param : Parameters) {
  11095. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  11096. // function declarator that is part of a function definition of
  11097. // that function shall not have incomplete type.
  11098. //
  11099. // This is also C++ [dcl.fct]p6.
  11100. if (!Param->isInvalidDecl() &&
  11101. RequireCompleteType(Param->getLocation(), Param->getType(),
  11102. diag::err_typecheck_decl_incomplete_type)) {
  11103. Param->setInvalidDecl();
  11104. HasInvalidParm = true;
  11105. }
  11106. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  11107. // declaration of each parameter shall include an identifier.
  11108. if (CheckParameterNames &&
  11109. Param->getIdentifier() == nullptr &&
  11110. !Param->isImplicit() &&
  11111. !getLangOpts().CPlusPlus)
  11112. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  11113. // C99 6.7.5.3p12:
  11114. // If the function declarator is not part of a definition of that
  11115. // function, parameters may have incomplete type and may use the [*]
  11116. // notation in their sequences of declarator specifiers to specify
  11117. // variable length array types.
  11118. QualType PType = Param->getOriginalType();
  11119. // FIXME: This diagnostic should point the '[*]' if source-location
  11120. // information is added for it.
  11121. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  11122. // If the parameter is a c++ class type and it has to be destructed in the
  11123. // callee function, declare the destructor so that it can be called by the
  11124. // callee function. Do not perform any direct access check on the dtor here.
  11125. if (!Param->isInvalidDecl()) {
  11126. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  11127. if (!ClassDecl->isInvalidDecl() &&
  11128. !ClassDecl->hasIrrelevantDestructor() &&
  11129. !ClassDecl->isDependentContext() &&
  11130. ClassDecl->isParamDestroyedInCallee()) {
  11131. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  11132. MarkFunctionReferenced(Param->getLocation(), Destructor);
  11133. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  11134. }
  11135. }
  11136. }
  11137. // Parameters with the pass_object_size attribute only need to be marked
  11138. // constant at function definitions. Because we lack information about
  11139. // whether we're on a declaration or definition when we're instantiating the
  11140. // attribute, we need to check for constness here.
  11141. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  11142. if (!Param->getType().isConstQualified())
  11143. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  11144. << Attr->getSpelling() << 1;
  11145. // Check for parameter names shadowing fields from the class.
  11146. if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
  11147. // The owning context for the parameter should be the function, but we
  11148. // want to see if this function's declaration context is a record.
  11149. DeclContext *DC = Param->getDeclContext();
  11150. if (DC && DC->isFunctionOrMethod()) {
  11151. if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
  11152. CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
  11153. RD, /*DeclIsField*/ false);
  11154. }
  11155. }
  11156. }
  11157. return HasInvalidParm;
  11158. }
  11159. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  11160. /// or MemberExpr.
  11161. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  11162. ASTContext &Context) {
  11163. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  11164. return Context.getDeclAlign(DRE->getDecl());
  11165. if (const auto *ME = dyn_cast<MemberExpr>(E))
  11166. return Context.getDeclAlign(ME->getMemberDecl());
  11167. return TypeAlign;
  11168. }
  11169. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  11170. /// pointer cast increases the alignment requirements.
  11171. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  11172. // This is actually a lot of work to potentially be doing on every
  11173. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  11174. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  11175. return;
  11176. // Ignore dependent types.
  11177. if (T->isDependentType() || Op->getType()->isDependentType())
  11178. return;
  11179. // Require that the destination be a pointer type.
  11180. const PointerType *DestPtr = T->getAs<PointerType>();
  11181. if (!DestPtr) return;
  11182. // If the destination has alignment 1, we're done.
  11183. QualType DestPointee = DestPtr->getPointeeType();
  11184. if (DestPointee->isIncompleteType()) return;
  11185. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  11186. if (DestAlign.isOne()) return;
  11187. // Require that the source be a pointer type.
  11188. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  11189. if (!SrcPtr) return;
  11190. QualType SrcPointee = SrcPtr->getPointeeType();
  11191. // Whitelist casts from cv void*. We already implicitly
  11192. // whitelisted casts to cv void*, since they have alignment 1.
  11193. // Also whitelist casts involving incomplete types, which implicitly
  11194. // includes 'void'.
  11195. if (SrcPointee->isIncompleteType()) return;
  11196. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  11197. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  11198. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  11199. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  11200. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  11201. if (UO->getOpcode() == UO_AddrOf)
  11202. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  11203. }
  11204. if (SrcAlign >= DestAlign) return;
  11205. Diag(TRange.getBegin(), diag::warn_cast_align)
  11206. << Op->getType() << T
  11207. << static_cast<unsigned>(SrcAlign.getQuantity())
  11208. << static_cast<unsigned>(DestAlign.getQuantity())
  11209. << TRange << Op->getSourceRange();
  11210. }
  11211. /// Check whether this array fits the idiom of a size-one tail padded
  11212. /// array member of a struct.
  11213. ///
  11214. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  11215. /// commonly used to emulate flexible arrays in C89 code.
  11216. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  11217. const NamedDecl *ND) {
  11218. if (Size != 1 || !ND) return false;
  11219. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  11220. if (!FD) return false;
  11221. // Don't consider sizes resulting from macro expansions or template argument
  11222. // substitution to form C89 tail-padded arrays.
  11223. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  11224. while (TInfo) {
  11225. TypeLoc TL = TInfo->getTypeLoc();
  11226. // Look through typedefs.
  11227. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  11228. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  11229. TInfo = TDL->getTypeSourceInfo();
  11230. continue;
  11231. }
  11232. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  11233. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  11234. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  11235. return false;
  11236. }
  11237. break;
  11238. }
  11239. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  11240. if (!RD) return false;
  11241. if (RD->isUnion()) return false;
  11242. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  11243. if (!CRD->isStandardLayout()) return false;
  11244. }
  11245. // See if this is the last field decl in the record.
  11246. const Decl *D = FD;
  11247. while ((D = D->getNextDeclInContext()))
  11248. if (isa<FieldDecl>(D))
  11249. return false;
  11250. return true;
  11251. }
  11252. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  11253. const ArraySubscriptExpr *ASE,
  11254. bool AllowOnePastEnd, bool IndexNegated) {
  11255. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  11256. if (IndexExpr->isValueDependent())
  11257. return;
  11258. const Type *EffectiveType =
  11259. BaseExpr->getType()->getPointeeOrArrayElementType();
  11260. BaseExpr = BaseExpr->IgnoreParenCasts();
  11261. const ConstantArrayType *ArrayTy =
  11262. Context.getAsConstantArrayType(BaseExpr->getType());
  11263. if (!ArrayTy)
  11264. return;
  11265. const Type *BaseType = ArrayTy->getElementType().getTypePtr();
  11266. if (EffectiveType->isDependentType() || BaseType->isDependentType())
  11267. return;
  11268. Expr::EvalResult Result;
  11269. if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
  11270. return;
  11271. llvm::APSInt index = Result.Val.getInt();
  11272. if (IndexNegated)
  11273. index = -index;
  11274. const NamedDecl *ND = nullptr;
  11275. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11276. ND = DRE->getDecl();
  11277. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11278. ND = ME->getMemberDecl();
  11279. if (index.isUnsigned() || !index.isNegative()) {
  11280. // It is possible that the type of the base expression after
  11281. // IgnoreParenCasts is incomplete, even though the type of the base
  11282. // expression before IgnoreParenCasts is complete (see PR39746 for an
  11283. // example). In this case we have no information about whether the array
  11284. // access exceeds the array bounds. However we can still diagnose an array
  11285. // access which precedes the array bounds.
  11286. if (BaseType->isIncompleteType())
  11287. return;
  11288. llvm::APInt size = ArrayTy->getSize();
  11289. if (!size.isStrictlyPositive())
  11290. return;
  11291. if (BaseType != EffectiveType) {
  11292. // Make sure we're comparing apples to apples when comparing index to size
  11293. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  11294. uint64_t array_typesize = Context.getTypeSize(BaseType);
  11295. // Handle ptrarith_typesize being zero, such as when casting to void*
  11296. if (!ptrarith_typesize) ptrarith_typesize = 1;
  11297. if (ptrarith_typesize != array_typesize) {
  11298. // There's a cast to a different size type involved
  11299. uint64_t ratio = array_typesize / ptrarith_typesize;
  11300. // TODO: Be smarter about handling cases where array_typesize is not a
  11301. // multiple of ptrarith_typesize
  11302. if (ptrarith_typesize * ratio == array_typesize)
  11303. size *= llvm::APInt(size.getBitWidth(), ratio);
  11304. }
  11305. }
  11306. if (size.getBitWidth() > index.getBitWidth())
  11307. index = index.zext(size.getBitWidth());
  11308. else if (size.getBitWidth() < index.getBitWidth())
  11309. size = size.zext(index.getBitWidth());
  11310. // For array subscripting the index must be less than size, but for pointer
  11311. // arithmetic also allow the index (offset) to be equal to size since
  11312. // computing the next address after the end of the array is legal and
  11313. // commonly done e.g. in C++ iterators and range-based for loops.
  11314. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  11315. return;
  11316. // Also don't warn for arrays of size 1 which are members of some
  11317. // structure. These are often used to approximate flexible arrays in C89
  11318. // code.
  11319. if (IsTailPaddedMemberArray(*this, size, ND))
  11320. return;
  11321. // Suppress the warning if the subscript expression (as identified by the
  11322. // ']' location) and the index expression are both from macro expansions
  11323. // within a system header.
  11324. if (ASE) {
  11325. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  11326. ASE->getRBracketLoc());
  11327. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  11328. SourceLocation IndexLoc =
  11329. SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
  11330. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  11331. return;
  11332. }
  11333. }
  11334. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  11335. if (ASE)
  11336. DiagID = diag::warn_array_index_exceeds_bounds;
  11337. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11338. PDiag(DiagID) << index.toString(10, true)
  11339. << size.toString(10, true)
  11340. << (unsigned)size.getLimitedValue(~0U)
  11341. << IndexExpr->getSourceRange());
  11342. } else {
  11343. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  11344. if (!ASE) {
  11345. DiagID = diag::warn_ptr_arith_precedes_bounds;
  11346. if (index.isNegative()) index = -index;
  11347. }
  11348. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11349. PDiag(DiagID) << index.toString(10, true)
  11350. << IndexExpr->getSourceRange());
  11351. }
  11352. if (!ND) {
  11353. // Try harder to find a NamedDecl to point at in the note.
  11354. while (const ArraySubscriptExpr *ASE =
  11355. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  11356. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  11357. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11358. ND = DRE->getDecl();
  11359. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11360. ND = ME->getMemberDecl();
  11361. }
  11362. if (ND)
  11363. DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
  11364. PDiag(diag::note_array_index_out_of_bounds)
  11365. << ND->getDeclName());
  11366. }
  11367. void Sema::CheckArrayAccess(const Expr *expr) {
  11368. int AllowOnePastEnd = 0;
  11369. while (expr) {
  11370. expr = expr->IgnoreParenImpCasts();
  11371. switch (expr->getStmtClass()) {
  11372. case Stmt::ArraySubscriptExprClass: {
  11373. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  11374. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  11375. AllowOnePastEnd > 0);
  11376. expr = ASE->getBase();
  11377. break;
  11378. }
  11379. case Stmt::MemberExprClass: {
  11380. expr = cast<MemberExpr>(expr)->getBase();
  11381. break;
  11382. }
  11383. case Stmt::OMPArraySectionExprClass: {
  11384. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  11385. if (ASE->getLowerBound())
  11386. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  11387. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  11388. return;
  11389. }
  11390. case Stmt::UnaryOperatorClass: {
  11391. // Only unwrap the * and & unary operators
  11392. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  11393. expr = UO->getSubExpr();
  11394. switch (UO->getOpcode()) {
  11395. case UO_AddrOf:
  11396. AllowOnePastEnd++;
  11397. break;
  11398. case UO_Deref:
  11399. AllowOnePastEnd--;
  11400. break;
  11401. default:
  11402. return;
  11403. }
  11404. break;
  11405. }
  11406. case Stmt::ConditionalOperatorClass: {
  11407. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  11408. if (const Expr *lhs = cond->getLHS())
  11409. CheckArrayAccess(lhs);
  11410. if (const Expr *rhs = cond->getRHS())
  11411. CheckArrayAccess(rhs);
  11412. return;
  11413. }
  11414. case Stmt::CXXOperatorCallExprClass: {
  11415. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  11416. for (const auto *Arg : OCE->arguments())
  11417. CheckArrayAccess(Arg);
  11418. return;
  11419. }
  11420. default:
  11421. return;
  11422. }
  11423. }
  11424. }
  11425. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  11426. namespace {
  11427. struct RetainCycleOwner {
  11428. VarDecl *Variable = nullptr;
  11429. SourceRange Range;
  11430. SourceLocation Loc;
  11431. bool Indirect = false;
  11432. RetainCycleOwner() = default;
  11433. void setLocsFrom(Expr *e) {
  11434. Loc = e->getExprLoc();
  11435. Range = e->getSourceRange();
  11436. }
  11437. };
  11438. } // namespace
  11439. /// Consider whether capturing the given variable can possibly lead to
  11440. /// a retain cycle.
  11441. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  11442. // In ARC, it's captured strongly iff the variable has __strong
  11443. // lifetime. In MRR, it's captured strongly if the variable is
  11444. // __block and has an appropriate type.
  11445. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11446. return false;
  11447. owner.Variable = var;
  11448. if (ref)
  11449. owner.setLocsFrom(ref);
  11450. return true;
  11451. }
  11452. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11453. while (true) {
  11454. e = e->IgnoreParens();
  11455. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  11456. switch (cast->getCastKind()) {
  11457. case CK_BitCast:
  11458. case CK_LValueBitCast:
  11459. case CK_LValueToRValue:
  11460. case CK_ARCReclaimReturnedObject:
  11461. e = cast->getSubExpr();
  11462. continue;
  11463. default:
  11464. return false;
  11465. }
  11466. }
  11467. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  11468. ObjCIvarDecl *ivar = ref->getDecl();
  11469. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11470. return false;
  11471. // Try to find a retain cycle in the base.
  11472. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  11473. return false;
  11474. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  11475. owner.Indirect = true;
  11476. return true;
  11477. }
  11478. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  11479. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  11480. if (!var) return false;
  11481. return considerVariable(var, ref, owner);
  11482. }
  11483. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  11484. if (member->isArrow()) return false;
  11485. // Don't count this as an indirect ownership.
  11486. e = member->getBase();
  11487. continue;
  11488. }
  11489. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  11490. // Only pay attention to pseudo-objects on property references.
  11491. ObjCPropertyRefExpr *pre
  11492. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  11493. ->IgnoreParens());
  11494. if (!pre) return false;
  11495. if (pre->isImplicitProperty()) return false;
  11496. ObjCPropertyDecl *property = pre->getExplicitProperty();
  11497. if (!property->isRetaining() &&
  11498. !(property->getPropertyIvarDecl() &&
  11499. property->getPropertyIvarDecl()->getType()
  11500. .getObjCLifetime() == Qualifiers::OCL_Strong))
  11501. return false;
  11502. owner.Indirect = true;
  11503. if (pre->isSuperReceiver()) {
  11504. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  11505. if (!owner.Variable)
  11506. return false;
  11507. owner.Loc = pre->getLocation();
  11508. owner.Range = pre->getSourceRange();
  11509. return true;
  11510. }
  11511. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  11512. ->getSourceExpr());
  11513. continue;
  11514. }
  11515. // Array ivars?
  11516. return false;
  11517. }
  11518. }
  11519. namespace {
  11520. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  11521. ASTContext &Context;
  11522. VarDecl *Variable;
  11523. Expr *Capturer = nullptr;
  11524. bool VarWillBeReased = false;
  11525. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  11526. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  11527. Context(Context), Variable(variable) {}
  11528. void VisitDeclRefExpr(DeclRefExpr *ref) {
  11529. if (ref->getDecl() == Variable && !Capturer)
  11530. Capturer = ref;
  11531. }
  11532. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  11533. if (Capturer) return;
  11534. Visit(ref->getBase());
  11535. if (Capturer && ref->isFreeIvar())
  11536. Capturer = ref;
  11537. }
  11538. void VisitBlockExpr(BlockExpr *block) {
  11539. // Look inside nested blocks
  11540. if (block->getBlockDecl()->capturesVariable(Variable))
  11541. Visit(block->getBlockDecl()->getBody());
  11542. }
  11543. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  11544. if (Capturer) return;
  11545. if (OVE->getSourceExpr())
  11546. Visit(OVE->getSourceExpr());
  11547. }
  11548. void VisitBinaryOperator(BinaryOperator *BinOp) {
  11549. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  11550. return;
  11551. Expr *LHS = BinOp->getLHS();
  11552. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  11553. if (DRE->getDecl() != Variable)
  11554. return;
  11555. if (Expr *RHS = BinOp->getRHS()) {
  11556. RHS = RHS->IgnoreParenCasts();
  11557. llvm::APSInt Value;
  11558. VarWillBeReased =
  11559. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  11560. }
  11561. }
  11562. }
  11563. };
  11564. } // namespace
  11565. /// Check whether the given argument is a block which captures a
  11566. /// variable.
  11567. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11568. assert(owner.Variable && owner.Loc.isValid());
  11569. e = e->IgnoreParenCasts();
  11570. // Look through [^{...} copy] and Block_copy(^{...}).
  11571. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  11572. Selector Cmd = ME->getSelector();
  11573. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  11574. e = ME->getInstanceReceiver();
  11575. if (!e)
  11576. return nullptr;
  11577. e = e->IgnoreParenCasts();
  11578. }
  11579. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  11580. if (CE->getNumArgs() == 1) {
  11581. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  11582. if (Fn) {
  11583. const IdentifierInfo *FnI = Fn->getIdentifier();
  11584. if (FnI && FnI->isStr("_Block_copy")) {
  11585. e = CE->getArg(0)->IgnoreParenCasts();
  11586. }
  11587. }
  11588. }
  11589. }
  11590. BlockExpr *block = dyn_cast<BlockExpr>(e);
  11591. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  11592. return nullptr;
  11593. FindCaptureVisitor visitor(S.Context, owner.Variable);
  11594. visitor.Visit(block->getBlockDecl()->getBody());
  11595. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  11596. }
  11597. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  11598. RetainCycleOwner &owner) {
  11599. assert(capturer);
  11600. assert(owner.Variable && owner.Loc.isValid());
  11601. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  11602. << owner.Variable << capturer->getSourceRange();
  11603. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  11604. << owner.Indirect << owner.Range;
  11605. }
  11606. /// Check for a keyword selector that starts with the word 'add' or
  11607. /// 'set'.
  11608. static bool isSetterLikeSelector(Selector sel) {
  11609. if (sel.isUnarySelector()) return false;
  11610. StringRef str = sel.getNameForSlot(0);
  11611. while (!str.empty() && str.front() == '_') str = str.substr(1);
  11612. if (str.startswith("set"))
  11613. str = str.substr(3);
  11614. else if (str.startswith("add")) {
  11615. // Specially whitelist 'addOperationWithBlock:'.
  11616. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  11617. return false;
  11618. str = str.substr(3);
  11619. }
  11620. else
  11621. return false;
  11622. if (str.empty()) return true;
  11623. return !isLowercase(str.front());
  11624. }
  11625. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  11626. ObjCMessageExpr *Message) {
  11627. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  11628. Message->getReceiverInterface(),
  11629. NSAPI::ClassId_NSMutableArray);
  11630. if (!IsMutableArray) {
  11631. return None;
  11632. }
  11633. Selector Sel = Message->getSelector();
  11634. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  11635. S.NSAPIObj->getNSArrayMethodKind(Sel);
  11636. if (!MKOpt) {
  11637. return None;
  11638. }
  11639. NSAPI::NSArrayMethodKind MK = *MKOpt;
  11640. switch (MK) {
  11641. case NSAPI::NSMutableArr_addObject:
  11642. case NSAPI::NSMutableArr_insertObjectAtIndex:
  11643. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  11644. return 0;
  11645. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  11646. return 1;
  11647. default:
  11648. return None;
  11649. }
  11650. return None;
  11651. }
  11652. static
  11653. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  11654. ObjCMessageExpr *Message) {
  11655. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  11656. Message->getReceiverInterface(),
  11657. NSAPI::ClassId_NSMutableDictionary);
  11658. if (!IsMutableDictionary) {
  11659. return None;
  11660. }
  11661. Selector Sel = Message->getSelector();
  11662. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  11663. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  11664. if (!MKOpt) {
  11665. return None;
  11666. }
  11667. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  11668. switch (MK) {
  11669. case NSAPI::NSMutableDict_setObjectForKey:
  11670. case NSAPI::NSMutableDict_setValueForKey:
  11671. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  11672. return 0;
  11673. default:
  11674. return None;
  11675. }
  11676. return None;
  11677. }
  11678. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  11679. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  11680. Message->getReceiverInterface(),
  11681. NSAPI::ClassId_NSMutableSet);
  11682. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  11683. Message->getReceiverInterface(),
  11684. NSAPI::ClassId_NSMutableOrderedSet);
  11685. if (!IsMutableSet && !IsMutableOrderedSet) {
  11686. return None;
  11687. }
  11688. Selector Sel = Message->getSelector();
  11689. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  11690. if (!MKOpt) {
  11691. return None;
  11692. }
  11693. NSAPI::NSSetMethodKind MK = *MKOpt;
  11694. switch (MK) {
  11695. case NSAPI::NSMutableSet_addObject:
  11696. case NSAPI::NSOrderedSet_setObjectAtIndex:
  11697. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  11698. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  11699. return 0;
  11700. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  11701. return 1;
  11702. }
  11703. return None;
  11704. }
  11705. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  11706. if (!Message->isInstanceMessage()) {
  11707. return;
  11708. }
  11709. Optional<int> ArgOpt;
  11710. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  11711. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  11712. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  11713. return;
  11714. }
  11715. int ArgIndex = *ArgOpt;
  11716. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  11717. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  11718. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  11719. }
  11720. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  11721. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11722. if (ArgRE->isObjCSelfExpr()) {
  11723. Diag(Message->getSourceRange().getBegin(),
  11724. diag::warn_objc_circular_container)
  11725. << ArgRE->getDecl() << StringRef("'super'");
  11726. }
  11727. }
  11728. } else {
  11729. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  11730. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  11731. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  11732. }
  11733. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  11734. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11735. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  11736. ValueDecl *Decl = ReceiverRE->getDecl();
  11737. Diag(Message->getSourceRange().getBegin(),
  11738. diag::warn_objc_circular_container)
  11739. << Decl << Decl;
  11740. if (!ArgRE->isObjCSelfExpr()) {
  11741. Diag(Decl->getLocation(),
  11742. diag::note_objc_circular_container_declared_here)
  11743. << Decl;
  11744. }
  11745. }
  11746. }
  11747. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  11748. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  11749. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  11750. ObjCIvarDecl *Decl = IvarRE->getDecl();
  11751. Diag(Message->getSourceRange().getBegin(),
  11752. diag::warn_objc_circular_container)
  11753. << Decl << Decl;
  11754. Diag(Decl->getLocation(),
  11755. diag::note_objc_circular_container_declared_here)
  11756. << Decl;
  11757. }
  11758. }
  11759. }
  11760. }
  11761. }
  11762. /// Check a message send to see if it's likely to cause a retain cycle.
  11763. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  11764. // Only check instance methods whose selector looks like a setter.
  11765. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  11766. return;
  11767. // Try to find a variable that the receiver is strongly owned by.
  11768. RetainCycleOwner owner;
  11769. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  11770. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  11771. return;
  11772. } else {
  11773. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  11774. owner.Variable = getCurMethodDecl()->getSelfDecl();
  11775. owner.Loc = msg->getSuperLoc();
  11776. owner.Range = msg->getSuperLoc();
  11777. }
  11778. // Check whether the receiver is captured by any of the arguments.
  11779. const ObjCMethodDecl *MD = msg->getMethodDecl();
  11780. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  11781. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  11782. // noescape blocks should not be retained by the method.
  11783. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  11784. continue;
  11785. return diagnoseRetainCycle(*this, capturer, owner);
  11786. }
  11787. }
  11788. }
  11789. /// Check a property assign to see if it's likely to cause a retain cycle.
  11790. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  11791. RetainCycleOwner owner;
  11792. if (!findRetainCycleOwner(*this, receiver, owner))
  11793. return;
  11794. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  11795. diagnoseRetainCycle(*this, capturer, owner);
  11796. }
  11797. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  11798. RetainCycleOwner Owner;
  11799. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  11800. return;
  11801. // Because we don't have an expression for the variable, we have to set the
  11802. // location explicitly here.
  11803. Owner.Loc = Var->getLocation();
  11804. Owner.Range = Var->getSourceRange();
  11805. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  11806. diagnoseRetainCycle(*this, Capturer, Owner);
  11807. }
  11808. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  11809. Expr *RHS, bool isProperty) {
  11810. // Check if RHS is an Objective-C object literal, which also can get
  11811. // immediately zapped in a weak reference. Note that we explicitly
  11812. // allow ObjCStringLiterals, since those are designed to never really die.
  11813. RHS = RHS->IgnoreParenImpCasts();
  11814. // This enum needs to match with the 'select' in
  11815. // warn_objc_arc_literal_assign (off-by-1).
  11816. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  11817. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  11818. return false;
  11819. S.Diag(Loc, diag::warn_arc_literal_assign)
  11820. << (unsigned) Kind
  11821. << (isProperty ? 0 : 1)
  11822. << RHS->getSourceRange();
  11823. return true;
  11824. }
  11825. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  11826. Qualifiers::ObjCLifetime LT,
  11827. Expr *RHS, bool isProperty) {
  11828. // Strip off any implicit cast added to get to the one ARC-specific.
  11829. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11830. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11831. S.Diag(Loc, diag::warn_arc_retained_assign)
  11832. << (LT == Qualifiers::OCL_ExplicitNone)
  11833. << (isProperty ? 0 : 1)
  11834. << RHS->getSourceRange();
  11835. return true;
  11836. }
  11837. RHS = cast->getSubExpr();
  11838. }
  11839. if (LT == Qualifiers::OCL_Weak &&
  11840. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  11841. return true;
  11842. return false;
  11843. }
  11844. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  11845. QualType LHS, Expr *RHS) {
  11846. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  11847. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  11848. return false;
  11849. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  11850. return true;
  11851. return false;
  11852. }
  11853. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  11854. Expr *LHS, Expr *RHS) {
  11855. QualType LHSType;
  11856. // PropertyRef on LHS type need be directly obtained from
  11857. // its declaration as it has a PseudoType.
  11858. ObjCPropertyRefExpr *PRE
  11859. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  11860. if (PRE && !PRE->isImplicitProperty()) {
  11861. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11862. if (PD)
  11863. LHSType = PD->getType();
  11864. }
  11865. if (LHSType.isNull())
  11866. LHSType = LHS->getType();
  11867. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  11868. if (LT == Qualifiers::OCL_Weak) {
  11869. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  11870. getCurFunction()->markSafeWeakUse(LHS);
  11871. }
  11872. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  11873. return;
  11874. // FIXME. Check for other life times.
  11875. if (LT != Qualifiers::OCL_None)
  11876. return;
  11877. if (PRE) {
  11878. if (PRE->isImplicitProperty())
  11879. return;
  11880. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11881. if (!PD)
  11882. return;
  11883. unsigned Attributes = PD->getPropertyAttributes();
  11884. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  11885. // when 'assign' attribute was not explicitly specified
  11886. // by user, ignore it and rely on property type itself
  11887. // for lifetime info.
  11888. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  11889. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  11890. LHSType->isObjCRetainableType())
  11891. return;
  11892. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11893. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11894. Diag(Loc, diag::warn_arc_retained_property_assign)
  11895. << RHS->getSourceRange();
  11896. return;
  11897. }
  11898. RHS = cast->getSubExpr();
  11899. }
  11900. }
  11901. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  11902. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  11903. return;
  11904. }
  11905. }
  11906. }
  11907. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  11908. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  11909. SourceLocation StmtLoc,
  11910. const NullStmt *Body) {
  11911. // Do not warn if the body is a macro that expands to nothing, e.g:
  11912. //
  11913. // #define CALL(x)
  11914. // if (condition)
  11915. // CALL(0);
  11916. if (Body->hasLeadingEmptyMacro())
  11917. return false;
  11918. // Get line numbers of statement and body.
  11919. bool StmtLineInvalid;
  11920. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  11921. &StmtLineInvalid);
  11922. if (StmtLineInvalid)
  11923. return false;
  11924. bool BodyLineInvalid;
  11925. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  11926. &BodyLineInvalid);
  11927. if (BodyLineInvalid)
  11928. return false;
  11929. // Warn if null statement and body are on the same line.
  11930. if (StmtLine != BodyLine)
  11931. return false;
  11932. return true;
  11933. }
  11934. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  11935. const Stmt *Body,
  11936. unsigned DiagID) {
  11937. // Since this is a syntactic check, don't emit diagnostic for template
  11938. // instantiations, this just adds noise.
  11939. if (CurrentInstantiationScope)
  11940. return;
  11941. // The body should be a null statement.
  11942. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  11943. if (!NBody)
  11944. return;
  11945. // Do the usual checks.
  11946. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  11947. return;
  11948. Diag(NBody->getSemiLoc(), DiagID);
  11949. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  11950. }
  11951. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  11952. const Stmt *PossibleBody) {
  11953. assert(!CurrentInstantiationScope); // Ensured by caller
  11954. SourceLocation StmtLoc;
  11955. const Stmt *Body;
  11956. unsigned DiagID;
  11957. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  11958. StmtLoc = FS->getRParenLoc();
  11959. Body = FS->getBody();
  11960. DiagID = diag::warn_empty_for_body;
  11961. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  11962. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  11963. Body = WS->getBody();
  11964. DiagID = diag::warn_empty_while_body;
  11965. } else
  11966. return; // Neither `for' nor `while'.
  11967. // The body should be a null statement.
  11968. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  11969. if (!NBody)
  11970. return;
  11971. // Skip expensive checks if diagnostic is disabled.
  11972. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  11973. return;
  11974. // Do the usual checks.
  11975. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  11976. return;
  11977. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  11978. // noise level low, emit diagnostics only if for/while is followed by a
  11979. // CompoundStmt, e.g.:
  11980. // for (int i = 0; i < n; i++);
  11981. // {
  11982. // a(i);
  11983. // }
  11984. // or if for/while is followed by a statement with more indentation
  11985. // than for/while itself:
  11986. // for (int i = 0; i < n; i++);
  11987. // a(i);
  11988. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  11989. if (!ProbableTypo) {
  11990. bool BodyColInvalid;
  11991. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  11992. PossibleBody->getBeginLoc(), &BodyColInvalid);
  11993. if (BodyColInvalid)
  11994. return;
  11995. bool StmtColInvalid;
  11996. unsigned StmtCol =
  11997. SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
  11998. if (StmtColInvalid)
  11999. return;
  12000. if (BodyCol > StmtCol)
  12001. ProbableTypo = true;
  12002. }
  12003. if (ProbableTypo) {
  12004. Diag(NBody->getSemiLoc(), DiagID);
  12005. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  12006. }
  12007. }
  12008. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  12009. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  12010. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  12011. SourceLocation OpLoc) {
  12012. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  12013. return;
  12014. if (inTemplateInstantiation())
  12015. return;
  12016. // Strip parens and casts away.
  12017. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  12018. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  12019. // Check for a call expression
  12020. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  12021. if (!CE || CE->getNumArgs() != 1)
  12022. return;
  12023. // Check for a call to std::move
  12024. if (!CE->isCallToStdMove())
  12025. return;
  12026. // Get argument from std::move
  12027. RHSExpr = CE->getArg(0);
  12028. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  12029. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  12030. // Two DeclRefExpr's, check that the decls are the same.
  12031. if (LHSDeclRef && RHSDeclRef) {
  12032. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12033. return;
  12034. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12035. RHSDeclRef->getDecl()->getCanonicalDecl())
  12036. return;
  12037. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12038. << LHSExpr->getSourceRange()
  12039. << RHSExpr->getSourceRange();
  12040. return;
  12041. }
  12042. // Member variables require a different approach to check for self moves.
  12043. // MemberExpr's are the same if every nested MemberExpr refers to the same
  12044. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  12045. // the base Expr's are CXXThisExpr's.
  12046. const Expr *LHSBase = LHSExpr;
  12047. const Expr *RHSBase = RHSExpr;
  12048. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  12049. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  12050. if (!LHSME || !RHSME)
  12051. return;
  12052. while (LHSME && RHSME) {
  12053. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  12054. RHSME->getMemberDecl()->getCanonicalDecl())
  12055. return;
  12056. LHSBase = LHSME->getBase();
  12057. RHSBase = RHSME->getBase();
  12058. LHSME = dyn_cast<MemberExpr>(LHSBase);
  12059. RHSME = dyn_cast<MemberExpr>(RHSBase);
  12060. }
  12061. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  12062. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  12063. if (LHSDeclRef && RHSDeclRef) {
  12064. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12065. return;
  12066. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12067. RHSDeclRef->getDecl()->getCanonicalDecl())
  12068. return;
  12069. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12070. << LHSExpr->getSourceRange()
  12071. << RHSExpr->getSourceRange();
  12072. return;
  12073. }
  12074. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  12075. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12076. << LHSExpr->getSourceRange()
  12077. << RHSExpr->getSourceRange();
  12078. }
  12079. //===--- Layout compatibility ----------------------------------------------//
  12080. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  12081. /// Check if two enumeration types are layout-compatible.
  12082. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  12083. // C++11 [dcl.enum] p8:
  12084. // Two enumeration types are layout-compatible if they have the same
  12085. // underlying type.
  12086. return ED1->isComplete() && ED2->isComplete() &&
  12087. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  12088. }
  12089. /// Check if two fields are layout-compatible.
  12090. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  12091. FieldDecl *Field2) {
  12092. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  12093. return false;
  12094. if (Field1->isBitField() != Field2->isBitField())
  12095. return false;
  12096. if (Field1->isBitField()) {
  12097. // Make sure that the bit-fields are the same length.
  12098. unsigned Bits1 = Field1->getBitWidthValue(C);
  12099. unsigned Bits2 = Field2->getBitWidthValue(C);
  12100. if (Bits1 != Bits2)
  12101. return false;
  12102. }
  12103. return true;
  12104. }
  12105. /// Check if two standard-layout structs are layout-compatible.
  12106. /// (C++11 [class.mem] p17)
  12107. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  12108. RecordDecl *RD2) {
  12109. // If both records are C++ classes, check that base classes match.
  12110. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  12111. // If one of records is a CXXRecordDecl we are in C++ mode,
  12112. // thus the other one is a CXXRecordDecl, too.
  12113. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  12114. // Check number of base classes.
  12115. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  12116. return false;
  12117. // Check the base classes.
  12118. for (CXXRecordDecl::base_class_const_iterator
  12119. Base1 = D1CXX->bases_begin(),
  12120. BaseEnd1 = D1CXX->bases_end(),
  12121. Base2 = D2CXX->bases_begin();
  12122. Base1 != BaseEnd1;
  12123. ++Base1, ++Base2) {
  12124. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  12125. return false;
  12126. }
  12127. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  12128. // If only RD2 is a C++ class, it should have zero base classes.
  12129. if (D2CXX->getNumBases() > 0)
  12130. return false;
  12131. }
  12132. // Check the fields.
  12133. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  12134. Field2End = RD2->field_end(),
  12135. Field1 = RD1->field_begin(),
  12136. Field1End = RD1->field_end();
  12137. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  12138. if (!isLayoutCompatible(C, *Field1, *Field2))
  12139. return false;
  12140. }
  12141. if (Field1 != Field1End || Field2 != Field2End)
  12142. return false;
  12143. return true;
  12144. }
  12145. /// Check if two standard-layout unions are layout-compatible.
  12146. /// (C++11 [class.mem] p18)
  12147. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  12148. RecordDecl *RD2) {
  12149. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  12150. for (auto *Field2 : RD2->fields())
  12151. UnmatchedFields.insert(Field2);
  12152. for (auto *Field1 : RD1->fields()) {
  12153. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  12154. I = UnmatchedFields.begin(),
  12155. E = UnmatchedFields.end();
  12156. for ( ; I != E; ++I) {
  12157. if (isLayoutCompatible(C, Field1, *I)) {
  12158. bool Result = UnmatchedFields.erase(*I);
  12159. (void) Result;
  12160. assert(Result);
  12161. break;
  12162. }
  12163. }
  12164. if (I == E)
  12165. return false;
  12166. }
  12167. return UnmatchedFields.empty();
  12168. }
  12169. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  12170. RecordDecl *RD2) {
  12171. if (RD1->isUnion() != RD2->isUnion())
  12172. return false;
  12173. if (RD1->isUnion())
  12174. return isLayoutCompatibleUnion(C, RD1, RD2);
  12175. else
  12176. return isLayoutCompatibleStruct(C, RD1, RD2);
  12177. }
  12178. /// Check if two types are layout-compatible in C++11 sense.
  12179. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  12180. if (T1.isNull() || T2.isNull())
  12181. return false;
  12182. // C++11 [basic.types] p11:
  12183. // If two types T1 and T2 are the same type, then T1 and T2 are
  12184. // layout-compatible types.
  12185. if (C.hasSameType(T1, T2))
  12186. return true;
  12187. T1 = T1.getCanonicalType().getUnqualifiedType();
  12188. T2 = T2.getCanonicalType().getUnqualifiedType();
  12189. const Type::TypeClass TC1 = T1->getTypeClass();
  12190. const Type::TypeClass TC2 = T2->getTypeClass();
  12191. if (TC1 != TC2)
  12192. return false;
  12193. if (TC1 == Type::Enum) {
  12194. return isLayoutCompatible(C,
  12195. cast<EnumType>(T1)->getDecl(),
  12196. cast<EnumType>(T2)->getDecl());
  12197. } else if (TC1 == Type::Record) {
  12198. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  12199. return false;
  12200. return isLayoutCompatible(C,
  12201. cast<RecordType>(T1)->getDecl(),
  12202. cast<RecordType>(T2)->getDecl());
  12203. }
  12204. return false;
  12205. }
  12206. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  12207. /// Given a type tag expression find the type tag itself.
  12208. ///
  12209. /// \param TypeExpr Type tag expression, as it appears in user's code.
  12210. ///
  12211. /// \param VD Declaration of an identifier that appears in a type tag.
  12212. ///
  12213. /// \param MagicValue Type tag magic value.
  12214. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  12215. const ValueDecl **VD, uint64_t *MagicValue) {
  12216. while(true) {
  12217. if (!TypeExpr)
  12218. return false;
  12219. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  12220. switch (TypeExpr->getStmtClass()) {
  12221. case Stmt::UnaryOperatorClass: {
  12222. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  12223. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  12224. TypeExpr = UO->getSubExpr();
  12225. continue;
  12226. }
  12227. return false;
  12228. }
  12229. case Stmt::DeclRefExprClass: {
  12230. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  12231. *VD = DRE->getDecl();
  12232. return true;
  12233. }
  12234. case Stmt::IntegerLiteralClass: {
  12235. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  12236. llvm::APInt MagicValueAPInt = IL->getValue();
  12237. if (MagicValueAPInt.getActiveBits() <= 64) {
  12238. *MagicValue = MagicValueAPInt.getZExtValue();
  12239. return true;
  12240. } else
  12241. return false;
  12242. }
  12243. case Stmt::BinaryConditionalOperatorClass:
  12244. case Stmt::ConditionalOperatorClass: {
  12245. const AbstractConditionalOperator *ACO =
  12246. cast<AbstractConditionalOperator>(TypeExpr);
  12247. bool Result;
  12248. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  12249. if (Result)
  12250. TypeExpr = ACO->getTrueExpr();
  12251. else
  12252. TypeExpr = ACO->getFalseExpr();
  12253. continue;
  12254. }
  12255. return false;
  12256. }
  12257. case Stmt::BinaryOperatorClass: {
  12258. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  12259. if (BO->getOpcode() == BO_Comma) {
  12260. TypeExpr = BO->getRHS();
  12261. continue;
  12262. }
  12263. return false;
  12264. }
  12265. default:
  12266. return false;
  12267. }
  12268. }
  12269. }
  12270. /// Retrieve the C type corresponding to type tag TypeExpr.
  12271. ///
  12272. /// \param TypeExpr Expression that specifies a type tag.
  12273. ///
  12274. /// \param MagicValues Registered magic values.
  12275. ///
  12276. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  12277. /// kind.
  12278. ///
  12279. /// \param TypeInfo Information about the corresponding C type.
  12280. ///
  12281. /// \returns true if the corresponding C type was found.
  12282. static bool GetMatchingCType(
  12283. const IdentifierInfo *ArgumentKind,
  12284. const Expr *TypeExpr, const ASTContext &Ctx,
  12285. const llvm::DenseMap<Sema::TypeTagMagicValue,
  12286. Sema::TypeTagData> *MagicValues,
  12287. bool &FoundWrongKind,
  12288. Sema::TypeTagData &TypeInfo) {
  12289. FoundWrongKind = false;
  12290. // Variable declaration that has type_tag_for_datatype attribute.
  12291. const ValueDecl *VD = nullptr;
  12292. uint64_t MagicValue;
  12293. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  12294. return false;
  12295. if (VD) {
  12296. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  12297. if (I->getArgumentKind() != ArgumentKind) {
  12298. FoundWrongKind = true;
  12299. return false;
  12300. }
  12301. TypeInfo.Type = I->getMatchingCType();
  12302. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  12303. TypeInfo.MustBeNull = I->getMustBeNull();
  12304. return true;
  12305. }
  12306. return false;
  12307. }
  12308. if (!MagicValues)
  12309. return false;
  12310. llvm::DenseMap<Sema::TypeTagMagicValue,
  12311. Sema::TypeTagData>::const_iterator I =
  12312. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  12313. if (I == MagicValues->end())
  12314. return false;
  12315. TypeInfo = I->second;
  12316. return true;
  12317. }
  12318. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  12319. uint64_t MagicValue, QualType Type,
  12320. bool LayoutCompatible,
  12321. bool MustBeNull) {
  12322. if (!TypeTagForDatatypeMagicValues)
  12323. TypeTagForDatatypeMagicValues.reset(
  12324. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  12325. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  12326. (*TypeTagForDatatypeMagicValues)[Magic] =
  12327. TypeTagData(Type, LayoutCompatible, MustBeNull);
  12328. }
  12329. static bool IsSameCharType(QualType T1, QualType T2) {
  12330. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  12331. if (!BT1)
  12332. return false;
  12333. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  12334. if (!BT2)
  12335. return false;
  12336. BuiltinType::Kind T1Kind = BT1->getKind();
  12337. BuiltinType::Kind T2Kind = BT2->getKind();
  12338. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  12339. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  12340. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  12341. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  12342. }
  12343. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  12344. const ArrayRef<const Expr *> ExprArgs,
  12345. SourceLocation CallSiteLoc) {
  12346. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  12347. bool IsPointerAttr = Attr->getIsPointer();
  12348. // Retrieve the argument representing the 'type_tag'.
  12349. unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
  12350. if (TypeTagIdxAST >= ExprArgs.size()) {
  12351. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12352. << 0 << Attr->getTypeTagIdx().getSourceIndex();
  12353. return;
  12354. }
  12355. const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
  12356. bool FoundWrongKind;
  12357. TypeTagData TypeInfo;
  12358. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  12359. TypeTagForDatatypeMagicValues.get(),
  12360. FoundWrongKind, TypeInfo)) {
  12361. if (FoundWrongKind)
  12362. Diag(TypeTagExpr->getExprLoc(),
  12363. diag::warn_type_tag_for_datatype_wrong_kind)
  12364. << TypeTagExpr->getSourceRange();
  12365. return;
  12366. }
  12367. // Retrieve the argument representing the 'arg_idx'.
  12368. unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
  12369. if (ArgumentIdxAST >= ExprArgs.size()) {
  12370. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12371. << 1 << Attr->getArgumentIdx().getSourceIndex();
  12372. return;
  12373. }
  12374. const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
  12375. if (IsPointerAttr) {
  12376. // Skip implicit cast of pointer to `void *' (as a function argument).
  12377. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  12378. if (ICE->getType()->isVoidPointerType() &&
  12379. ICE->getCastKind() == CK_BitCast)
  12380. ArgumentExpr = ICE->getSubExpr();
  12381. }
  12382. QualType ArgumentType = ArgumentExpr->getType();
  12383. // Passing a `void*' pointer shouldn't trigger a warning.
  12384. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  12385. return;
  12386. if (TypeInfo.MustBeNull) {
  12387. // Type tag with matching void type requires a null pointer.
  12388. if (!ArgumentExpr->isNullPointerConstant(Context,
  12389. Expr::NPC_ValueDependentIsNotNull)) {
  12390. Diag(ArgumentExpr->getExprLoc(),
  12391. diag::warn_type_safety_null_pointer_required)
  12392. << ArgumentKind->getName()
  12393. << ArgumentExpr->getSourceRange()
  12394. << TypeTagExpr->getSourceRange();
  12395. }
  12396. return;
  12397. }
  12398. QualType RequiredType = TypeInfo.Type;
  12399. if (IsPointerAttr)
  12400. RequiredType = Context.getPointerType(RequiredType);
  12401. bool mismatch = false;
  12402. if (!TypeInfo.LayoutCompatible) {
  12403. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  12404. // C++11 [basic.fundamental] p1:
  12405. // Plain char, signed char, and unsigned char are three distinct types.
  12406. //
  12407. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  12408. // char' depending on the current char signedness mode.
  12409. if (mismatch)
  12410. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  12411. RequiredType->getPointeeType())) ||
  12412. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  12413. mismatch = false;
  12414. } else
  12415. if (IsPointerAttr)
  12416. mismatch = !isLayoutCompatible(Context,
  12417. ArgumentType->getPointeeType(),
  12418. RequiredType->getPointeeType());
  12419. else
  12420. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  12421. if (mismatch)
  12422. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  12423. << ArgumentType << ArgumentKind
  12424. << TypeInfo.LayoutCompatible << RequiredType
  12425. << ArgumentExpr->getSourceRange()
  12426. << TypeTagExpr->getSourceRange();
  12427. }
  12428. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  12429. CharUnits Alignment) {
  12430. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  12431. }
  12432. void Sema::DiagnoseMisalignedMembers() {
  12433. for (MisalignedMember &m : MisalignedMembers) {
  12434. const NamedDecl *ND = m.RD;
  12435. if (ND->getName().empty()) {
  12436. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  12437. ND = TD;
  12438. }
  12439. Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
  12440. << m.MD << ND << m.E->getSourceRange();
  12441. }
  12442. MisalignedMembers.clear();
  12443. }
  12444. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  12445. E = E->IgnoreParens();
  12446. if (!T->isPointerType() && !T->isIntegerType())
  12447. return;
  12448. if (isa<UnaryOperator>(E) &&
  12449. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  12450. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  12451. if (isa<MemberExpr>(Op)) {
  12452. auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
  12453. if (MA != MisalignedMembers.end() &&
  12454. (T->isIntegerType() ||
  12455. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  12456. Context.getTypeAlignInChars(
  12457. T->getPointeeType()) <= MA->Alignment))))
  12458. MisalignedMembers.erase(MA);
  12459. }
  12460. }
  12461. }
  12462. void Sema::RefersToMemberWithReducedAlignment(
  12463. Expr *E,
  12464. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  12465. Action) {
  12466. const auto *ME = dyn_cast<MemberExpr>(E);
  12467. if (!ME)
  12468. return;
  12469. // No need to check expressions with an __unaligned-qualified type.
  12470. if (E->getType().getQualifiers().hasUnaligned())
  12471. return;
  12472. // For a chain of MemberExpr like "a.b.c.d" this list
  12473. // will keep FieldDecl's like [d, c, b].
  12474. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  12475. const MemberExpr *TopME = nullptr;
  12476. bool AnyIsPacked = false;
  12477. do {
  12478. QualType BaseType = ME->getBase()->getType();
  12479. if (ME->isArrow())
  12480. BaseType = BaseType->getPointeeType();
  12481. RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
  12482. if (RD->isInvalidDecl())
  12483. return;
  12484. ValueDecl *MD = ME->getMemberDecl();
  12485. auto *FD = dyn_cast<FieldDecl>(MD);
  12486. // We do not care about non-data members.
  12487. if (!FD || FD->isInvalidDecl())
  12488. return;
  12489. AnyIsPacked =
  12490. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  12491. ReverseMemberChain.push_back(FD);
  12492. TopME = ME;
  12493. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  12494. } while (ME);
  12495. assert(TopME && "We did not compute a topmost MemberExpr!");
  12496. // Not the scope of this diagnostic.
  12497. if (!AnyIsPacked)
  12498. return;
  12499. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  12500. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  12501. // TODO: The innermost base of the member expression may be too complicated.
  12502. // For now, just disregard these cases. This is left for future
  12503. // improvement.
  12504. if (!DRE && !isa<CXXThisExpr>(TopBase))
  12505. return;
  12506. // Alignment expected by the whole expression.
  12507. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  12508. // No need to do anything else with this case.
  12509. if (ExpectedAlignment.isOne())
  12510. return;
  12511. // Synthesize offset of the whole access.
  12512. CharUnits Offset;
  12513. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  12514. I++) {
  12515. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  12516. }
  12517. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  12518. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  12519. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  12520. // The base expression of the innermost MemberExpr may give
  12521. // stronger guarantees than the class containing the member.
  12522. if (DRE && !TopME->isArrow()) {
  12523. const ValueDecl *VD = DRE->getDecl();
  12524. if (!VD->getType()->isReferenceType())
  12525. CompleteObjectAlignment =
  12526. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  12527. }
  12528. // Check if the synthesized offset fulfills the alignment.
  12529. if (Offset % ExpectedAlignment != 0 ||
  12530. // It may fulfill the offset it but the effective alignment may still be
  12531. // lower than the expected expression alignment.
  12532. CompleteObjectAlignment < ExpectedAlignment) {
  12533. // If this happens, we want to determine a sensible culprit of this.
  12534. // Intuitively, watching the chain of member expressions from right to
  12535. // left, we start with the required alignment (as required by the field
  12536. // type) but some packed attribute in that chain has reduced the alignment.
  12537. // It may happen that another packed structure increases it again. But if
  12538. // we are here such increase has not been enough. So pointing the first
  12539. // FieldDecl that either is packed or else its RecordDecl is,
  12540. // seems reasonable.
  12541. FieldDecl *FD = nullptr;
  12542. CharUnits Alignment;
  12543. for (FieldDecl *FDI : ReverseMemberChain) {
  12544. if (FDI->hasAttr<PackedAttr>() ||
  12545. FDI->getParent()->hasAttr<PackedAttr>()) {
  12546. FD = FDI;
  12547. Alignment = std::min(
  12548. Context.getTypeAlignInChars(FD->getType()),
  12549. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  12550. break;
  12551. }
  12552. }
  12553. assert(FD && "We did not find a packed FieldDecl!");
  12554. Action(E, FD->getParent(), FD, Alignment);
  12555. }
  12556. }
  12557. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  12558. using namespace std::placeholders;
  12559. RefersToMemberWithReducedAlignment(
  12560. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  12561. _2, _3, _4));
  12562. }