SemaChecking.cpp 554 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219
  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_cfcmsa:
  2849. case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
  2850. case Mips::BI__builtin_msa_clei_u_b:
  2851. case Mips::BI__builtin_msa_clei_u_h:
  2852. case Mips::BI__builtin_msa_clei_u_w:
  2853. case Mips::BI__builtin_msa_clei_u_d:
  2854. case Mips::BI__builtin_msa_clti_u_b:
  2855. case Mips::BI__builtin_msa_clti_u_h:
  2856. case Mips::BI__builtin_msa_clti_u_w:
  2857. case Mips::BI__builtin_msa_clti_u_d:
  2858. case Mips::BI__builtin_msa_maxi_u_b:
  2859. case Mips::BI__builtin_msa_maxi_u_h:
  2860. case Mips::BI__builtin_msa_maxi_u_w:
  2861. case Mips::BI__builtin_msa_maxi_u_d:
  2862. case Mips::BI__builtin_msa_mini_u_b:
  2863. case Mips::BI__builtin_msa_mini_u_h:
  2864. case Mips::BI__builtin_msa_mini_u_w:
  2865. case Mips::BI__builtin_msa_mini_u_d:
  2866. case Mips::BI__builtin_msa_addvi_b:
  2867. case Mips::BI__builtin_msa_addvi_h:
  2868. case Mips::BI__builtin_msa_addvi_w:
  2869. case Mips::BI__builtin_msa_addvi_d:
  2870. case Mips::BI__builtin_msa_bclri_w:
  2871. case Mips::BI__builtin_msa_bnegi_w:
  2872. case Mips::BI__builtin_msa_bseti_w:
  2873. case Mips::BI__builtin_msa_sat_s_w:
  2874. case Mips::BI__builtin_msa_sat_u_w:
  2875. case Mips::BI__builtin_msa_slli_w:
  2876. case Mips::BI__builtin_msa_srai_w:
  2877. case Mips::BI__builtin_msa_srari_w:
  2878. case Mips::BI__builtin_msa_srli_w:
  2879. case Mips::BI__builtin_msa_srlri_w:
  2880. case Mips::BI__builtin_msa_subvi_b:
  2881. case Mips::BI__builtin_msa_subvi_h:
  2882. case Mips::BI__builtin_msa_subvi_w:
  2883. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  2884. case Mips::BI__builtin_msa_binsli_w:
  2885. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  2886. // These intrinsics take an unsigned 6 bit immediate.
  2887. case Mips::BI__builtin_msa_bclri_d:
  2888. case Mips::BI__builtin_msa_bnegi_d:
  2889. case Mips::BI__builtin_msa_bseti_d:
  2890. case Mips::BI__builtin_msa_sat_s_d:
  2891. case Mips::BI__builtin_msa_sat_u_d:
  2892. case Mips::BI__builtin_msa_slli_d:
  2893. case Mips::BI__builtin_msa_srai_d:
  2894. case Mips::BI__builtin_msa_srari_d:
  2895. case Mips::BI__builtin_msa_srli_d:
  2896. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  2897. case Mips::BI__builtin_msa_binsli_d:
  2898. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  2899. // These intrinsics take a signed 5 bit immediate.
  2900. case Mips::BI__builtin_msa_ceqi_b:
  2901. case Mips::BI__builtin_msa_ceqi_h:
  2902. case Mips::BI__builtin_msa_ceqi_w:
  2903. case Mips::BI__builtin_msa_ceqi_d:
  2904. case Mips::BI__builtin_msa_clti_s_b:
  2905. case Mips::BI__builtin_msa_clti_s_h:
  2906. case Mips::BI__builtin_msa_clti_s_w:
  2907. case Mips::BI__builtin_msa_clti_s_d:
  2908. case Mips::BI__builtin_msa_clei_s_b:
  2909. case Mips::BI__builtin_msa_clei_s_h:
  2910. case Mips::BI__builtin_msa_clei_s_w:
  2911. case Mips::BI__builtin_msa_clei_s_d:
  2912. case Mips::BI__builtin_msa_maxi_s_b:
  2913. case Mips::BI__builtin_msa_maxi_s_h:
  2914. case Mips::BI__builtin_msa_maxi_s_w:
  2915. case Mips::BI__builtin_msa_maxi_s_d:
  2916. case Mips::BI__builtin_msa_mini_s_b:
  2917. case Mips::BI__builtin_msa_mini_s_h:
  2918. case Mips::BI__builtin_msa_mini_s_w:
  2919. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  2920. // These intrinsics take an unsigned 8 bit immediate.
  2921. case Mips::BI__builtin_msa_andi_b:
  2922. case Mips::BI__builtin_msa_nori_b:
  2923. case Mips::BI__builtin_msa_ori_b:
  2924. case Mips::BI__builtin_msa_shf_b:
  2925. case Mips::BI__builtin_msa_shf_h:
  2926. case Mips::BI__builtin_msa_shf_w:
  2927. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  2928. case Mips::BI__builtin_msa_bseli_b:
  2929. case Mips::BI__builtin_msa_bmnzi_b:
  2930. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  2931. // df/n format
  2932. // These intrinsics take an unsigned 4 bit immediate.
  2933. case Mips::BI__builtin_msa_copy_s_b:
  2934. case Mips::BI__builtin_msa_copy_u_b:
  2935. case Mips::BI__builtin_msa_insve_b:
  2936. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  2937. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  2938. // These intrinsics take an unsigned 3 bit immediate.
  2939. case Mips::BI__builtin_msa_copy_s_h:
  2940. case Mips::BI__builtin_msa_copy_u_h:
  2941. case Mips::BI__builtin_msa_insve_h:
  2942. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  2943. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  2944. // These intrinsics take an unsigned 2 bit immediate.
  2945. case Mips::BI__builtin_msa_copy_s_w:
  2946. case Mips::BI__builtin_msa_copy_u_w:
  2947. case Mips::BI__builtin_msa_insve_w:
  2948. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  2949. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  2950. // These intrinsics take an unsigned 1 bit immediate.
  2951. case Mips::BI__builtin_msa_copy_s_d:
  2952. case Mips::BI__builtin_msa_copy_u_d:
  2953. case Mips::BI__builtin_msa_insve_d:
  2954. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  2955. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  2956. // Memory offsets and immediate loads.
  2957. // These intrinsics take a signed 10 bit immediate.
  2958. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  2959. case Mips::BI__builtin_msa_ldi_h:
  2960. case Mips::BI__builtin_msa_ldi_w:
  2961. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  2962. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
  2963. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
  2964. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
  2965. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
  2966. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
  2967. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
  2968. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
  2969. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
  2970. }
  2971. if (!m)
  2972. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2973. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  2974. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  2975. }
  2976. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2977. unsigned i = 0, l = 0, u = 0;
  2978. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  2979. BuiltinID == PPC::BI__builtin_divdeu ||
  2980. BuiltinID == PPC::BI__builtin_bpermd;
  2981. bool IsTarget64Bit = Context.getTargetInfo()
  2982. .getTypeWidth(Context
  2983. .getTargetInfo()
  2984. .getIntPtrType()) == 64;
  2985. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  2986. BuiltinID == PPC::BI__builtin_divweu ||
  2987. BuiltinID == PPC::BI__builtin_divde ||
  2988. BuiltinID == PPC::BI__builtin_divdeu;
  2989. if (Is64BitBltin && !IsTarget64Bit)
  2990. return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
  2991. << TheCall->getSourceRange();
  2992. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  2993. (BuiltinID == PPC::BI__builtin_bpermd &&
  2994. !Context.getTargetInfo().hasFeature("bpermd")))
  2995. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  2996. << TheCall->getSourceRange();
  2997. auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
  2998. if (!Context.getTargetInfo().hasFeature("vsx"))
  2999. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  3000. << TheCall->getSourceRange();
  3001. return false;
  3002. };
  3003. switch (BuiltinID) {
  3004. default: return false;
  3005. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  3006. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  3007. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  3008. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3009. case PPC::BI__builtin_tbegin:
  3010. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  3011. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  3012. case PPC::BI__builtin_tabortwc:
  3013. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  3014. case PPC::BI__builtin_tabortwci:
  3015. case PPC::BI__builtin_tabortdci:
  3016. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  3017. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  3018. case PPC::BI__builtin_vsx_xxpermdi:
  3019. case PPC::BI__builtin_vsx_xxsldwi:
  3020. return SemaBuiltinVSX(TheCall);
  3021. case PPC::BI__builtin_unpack_vector_int128:
  3022. return SemaVSXCheck(TheCall) ||
  3023. SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  3024. case PPC::BI__builtin_pack_vector_int128:
  3025. return SemaVSXCheck(TheCall);
  3026. }
  3027. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3028. }
  3029. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  3030. CallExpr *TheCall) {
  3031. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  3032. Expr *Arg = TheCall->getArg(0);
  3033. llvm::APSInt AbortCode(32);
  3034. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  3035. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  3036. return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
  3037. << Arg->getSourceRange();
  3038. }
  3039. // For intrinsics which take an immediate value as part of the instruction,
  3040. // range check them here.
  3041. unsigned i = 0, l = 0, u = 0;
  3042. switch (BuiltinID) {
  3043. default: return false;
  3044. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  3045. case SystemZ::BI__builtin_s390_verimb:
  3046. case SystemZ::BI__builtin_s390_verimh:
  3047. case SystemZ::BI__builtin_s390_verimf:
  3048. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  3049. case SystemZ::BI__builtin_s390_vfaeb:
  3050. case SystemZ::BI__builtin_s390_vfaeh:
  3051. case SystemZ::BI__builtin_s390_vfaef:
  3052. case SystemZ::BI__builtin_s390_vfaebs:
  3053. case SystemZ::BI__builtin_s390_vfaehs:
  3054. case SystemZ::BI__builtin_s390_vfaefs:
  3055. case SystemZ::BI__builtin_s390_vfaezb:
  3056. case SystemZ::BI__builtin_s390_vfaezh:
  3057. case SystemZ::BI__builtin_s390_vfaezf:
  3058. case SystemZ::BI__builtin_s390_vfaezbs:
  3059. case SystemZ::BI__builtin_s390_vfaezhs:
  3060. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  3061. case SystemZ::BI__builtin_s390_vfisb:
  3062. case SystemZ::BI__builtin_s390_vfidb:
  3063. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  3064. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3065. case SystemZ::BI__builtin_s390_vftcisb:
  3066. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  3067. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  3068. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  3069. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  3070. case SystemZ::BI__builtin_s390_vstrcb:
  3071. case SystemZ::BI__builtin_s390_vstrch:
  3072. case SystemZ::BI__builtin_s390_vstrcf:
  3073. case SystemZ::BI__builtin_s390_vstrczb:
  3074. case SystemZ::BI__builtin_s390_vstrczh:
  3075. case SystemZ::BI__builtin_s390_vstrczf:
  3076. case SystemZ::BI__builtin_s390_vstrcbs:
  3077. case SystemZ::BI__builtin_s390_vstrchs:
  3078. case SystemZ::BI__builtin_s390_vstrcfs:
  3079. case SystemZ::BI__builtin_s390_vstrczbs:
  3080. case SystemZ::BI__builtin_s390_vstrczhs:
  3081. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  3082. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  3083. case SystemZ::BI__builtin_s390_vfminsb:
  3084. case SystemZ::BI__builtin_s390_vfmaxsb:
  3085. case SystemZ::BI__builtin_s390_vfmindb:
  3086. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  3087. }
  3088. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3089. }
  3090. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  3091. /// This checks that the target supports __builtin_cpu_supports and
  3092. /// that the string argument is constant and valid.
  3093. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  3094. Expr *Arg = TheCall->getArg(0);
  3095. // Check if the argument is a string literal.
  3096. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3097. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3098. << Arg->getSourceRange();
  3099. // Check the contents of the string.
  3100. StringRef Feature =
  3101. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3102. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  3103. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
  3104. << Arg->getSourceRange();
  3105. return false;
  3106. }
  3107. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  3108. /// This checks that the target supports __builtin_cpu_is and
  3109. /// that the string argument is constant and valid.
  3110. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  3111. Expr *Arg = TheCall->getArg(0);
  3112. // Check if the argument is a string literal.
  3113. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3114. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3115. << Arg->getSourceRange();
  3116. // Check the contents of the string.
  3117. StringRef Feature =
  3118. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3119. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  3120. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
  3121. << Arg->getSourceRange();
  3122. return false;
  3123. }
  3124. // Check if the rounding mode is legal.
  3125. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  3126. // Indicates if this instruction has rounding control or just SAE.
  3127. bool HasRC = false;
  3128. unsigned ArgNum = 0;
  3129. switch (BuiltinID) {
  3130. default:
  3131. return false;
  3132. case X86::BI__builtin_ia32_vcvttsd2si32:
  3133. case X86::BI__builtin_ia32_vcvttsd2si64:
  3134. case X86::BI__builtin_ia32_vcvttsd2usi32:
  3135. case X86::BI__builtin_ia32_vcvttsd2usi64:
  3136. case X86::BI__builtin_ia32_vcvttss2si32:
  3137. case X86::BI__builtin_ia32_vcvttss2si64:
  3138. case X86::BI__builtin_ia32_vcvttss2usi32:
  3139. case X86::BI__builtin_ia32_vcvttss2usi64:
  3140. ArgNum = 1;
  3141. break;
  3142. case X86::BI__builtin_ia32_maxpd512:
  3143. case X86::BI__builtin_ia32_maxps512:
  3144. case X86::BI__builtin_ia32_minpd512:
  3145. case X86::BI__builtin_ia32_minps512:
  3146. ArgNum = 2;
  3147. break;
  3148. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  3149. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  3150. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  3151. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  3152. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  3153. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  3154. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  3155. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  3156. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  3157. case X86::BI__builtin_ia32_exp2pd_mask:
  3158. case X86::BI__builtin_ia32_exp2ps_mask:
  3159. case X86::BI__builtin_ia32_getexppd512_mask:
  3160. case X86::BI__builtin_ia32_getexpps512_mask:
  3161. case X86::BI__builtin_ia32_rcp28pd_mask:
  3162. case X86::BI__builtin_ia32_rcp28ps_mask:
  3163. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  3164. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  3165. case X86::BI__builtin_ia32_vcomisd:
  3166. case X86::BI__builtin_ia32_vcomiss:
  3167. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  3168. ArgNum = 3;
  3169. break;
  3170. case X86::BI__builtin_ia32_cmppd512_mask:
  3171. case X86::BI__builtin_ia32_cmpps512_mask:
  3172. case X86::BI__builtin_ia32_cmpsd_mask:
  3173. case X86::BI__builtin_ia32_cmpss_mask:
  3174. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  3175. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  3176. case X86::BI__builtin_ia32_getexpss128_round_mask:
  3177. case X86::BI__builtin_ia32_getmantpd512_mask:
  3178. case X86::BI__builtin_ia32_getmantps512_mask:
  3179. case X86::BI__builtin_ia32_maxsd_round_mask:
  3180. case X86::BI__builtin_ia32_maxss_round_mask:
  3181. case X86::BI__builtin_ia32_minsd_round_mask:
  3182. case X86::BI__builtin_ia32_minss_round_mask:
  3183. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  3184. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  3185. case X86::BI__builtin_ia32_reducepd512_mask:
  3186. case X86::BI__builtin_ia32_reduceps512_mask:
  3187. case X86::BI__builtin_ia32_rndscalepd_mask:
  3188. case X86::BI__builtin_ia32_rndscaleps_mask:
  3189. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  3190. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  3191. ArgNum = 4;
  3192. break;
  3193. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3194. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3195. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3196. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3197. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3198. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3199. case X86::BI__builtin_ia32_fixupimmss_mask:
  3200. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3201. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3202. case X86::BI__builtin_ia32_getmantss_round_mask:
  3203. case X86::BI__builtin_ia32_rangepd512_mask:
  3204. case X86::BI__builtin_ia32_rangeps512_mask:
  3205. case X86::BI__builtin_ia32_rangesd128_round_mask:
  3206. case X86::BI__builtin_ia32_rangess128_round_mask:
  3207. case X86::BI__builtin_ia32_reducesd_mask:
  3208. case X86::BI__builtin_ia32_reducess_mask:
  3209. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3210. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3211. ArgNum = 5;
  3212. break;
  3213. case X86::BI__builtin_ia32_vcvtsd2si64:
  3214. case X86::BI__builtin_ia32_vcvtsd2si32:
  3215. case X86::BI__builtin_ia32_vcvtsd2usi32:
  3216. case X86::BI__builtin_ia32_vcvtsd2usi64:
  3217. case X86::BI__builtin_ia32_vcvtss2si32:
  3218. case X86::BI__builtin_ia32_vcvtss2si64:
  3219. case X86::BI__builtin_ia32_vcvtss2usi32:
  3220. case X86::BI__builtin_ia32_vcvtss2usi64:
  3221. case X86::BI__builtin_ia32_sqrtpd512:
  3222. case X86::BI__builtin_ia32_sqrtps512:
  3223. ArgNum = 1;
  3224. HasRC = true;
  3225. break;
  3226. case X86::BI__builtin_ia32_addpd512:
  3227. case X86::BI__builtin_ia32_addps512:
  3228. case X86::BI__builtin_ia32_divpd512:
  3229. case X86::BI__builtin_ia32_divps512:
  3230. case X86::BI__builtin_ia32_mulpd512:
  3231. case X86::BI__builtin_ia32_mulps512:
  3232. case X86::BI__builtin_ia32_subpd512:
  3233. case X86::BI__builtin_ia32_subps512:
  3234. case X86::BI__builtin_ia32_cvtsi2sd64:
  3235. case X86::BI__builtin_ia32_cvtsi2ss32:
  3236. case X86::BI__builtin_ia32_cvtsi2ss64:
  3237. case X86::BI__builtin_ia32_cvtusi2sd64:
  3238. case X86::BI__builtin_ia32_cvtusi2ss32:
  3239. case X86::BI__builtin_ia32_cvtusi2ss64:
  3240. ArgNum = 2;
  3241. HasRC = true;
  3242. break;
  3243. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  3244. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  3245. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  3246. case X86::BI__builtin_ia32_cvtpd2dq512_mask:
  3247. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  3248. case X86::BI__builtin_ia32_cvtpd2udq512_mask:
  3249. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  3250. case X86::BI__builtin_ia32_cvtps2dq512_mask:
  3251. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  3252. case X86::BI__builtin_ia32_cvtps2udq512_mask:
  3253. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  3254. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  3255. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  3256. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  3257. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  3258. ArgNum = 3;
  3259. HasRC = true;
  3260. break;
  3261. case X86::BI__builtin_ia32_addss_round_mask:
  3262. case X86::BI__builtin_ia32_addsd_round_mask:
  3263. case X86::BI__builtin_ia32_divss_round_mask:
  3264. case X86::BI__builtin_ia32_divsd_round_mask:
  3265. case X86::BI__builtin_ia32_mulss_round_mask:
  3266. case X86::BI__builtin_ia32_mulsd_round_mask:
  3267. case X86::BI__builtin_ia32_subss_round_mask:
  3268. case X86::BI__builtin_ia32_subsd_round_mask:
  3269. case X86::BI__builtin_ia32_scalefpd512_mask:
  3270. case X86::BI__builtin_ia32_scalefps512_mask:
  3271. case X86::BI__builtin_ia32_scalefsd_round_mask:
  3272. case X86::BI__builtin_ia32_scalefss_round_mask:
  3273. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  3274. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  3275. case X86::BI__builtin_ia32_sqrtss_round_mask:
  3276. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  3277. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  3278. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  3279. case X86::BI__builtin_ia32_vfmaddss3_mask:
  3280. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  3281. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  3282. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  3283. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  3284. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  3285. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  3286. case X86::BI__builtin_ia32_vfmaddps512_mask:
  3287. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  3288. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  3289. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  3290. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  3291. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  3292. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  3293. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  3294. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  3295. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  3296. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  3297. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  3298. ArgNum = 4;
  3299. HasRC = true;
  3300. break;
  3301. }
  3302. llvm::APSInt Result;
  3303. // We can't check the value of a dependent argument.
  3304. Expr *Arg = TheCall->getArg(ArgNum);
  3305. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3306. return false;
  3307. // Check constant-ness first.
  3308. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3309. return true;
  3310. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  3311. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  3312. // combined with ROUND_NO_EXC.
  3313. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  3314. Result == 8/*ROUND_NO_EXC*/ ||
  3315. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  3316. return false;
  3317. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
  3318. << Arg->getSourceRange();
  3319. }
  3320. // Check if the gather/scatter scale is legal.
  3321. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  3322. CallExpr *TheCall) {
  3323. unsigned ArgNum = 0;
  3324. switch (BuiltinID) {
  3325. default:
  3326. return false;
  3327. case X86::BI__builtin_ia32_gatherpfdpd:
  3328. case X86::BI__builtin_ia32_gatherpfdps:
  3329. case X86::BI__builtin_ia32_gatherpfqpd:
  3330. case X86::BI__builtin_ia32_gatherpfqps:
  3331. case X86::BI__builtin_ia32_scatterpfdpd:
  3332. case X86::BI__builtin_ia32_scatterpfdps:
  3333. case X86::BI__builtin_ia32_scatterpfqpd:
  3334. case X86::BI__builtin_ia32_scatterpfqps:
  3335. ArgNum = 3;
  3336. break;
  3337. case X86::BI__builtin_ia32_gatherd_pd:
  3338. case X86::BI__builtin_ia32_gatherd_pd256:
  3339. case X86::BI__builtin_ia32_gatherq_pd:
  3340. case X86::BI__builtin_ia32_gatherq_pd256:
  3341. case X86::BI__builtin_ia32_gatherd_ps:
  3342. case X86::BI__builtin_ia32_gatherd_ps256:
  3343. case X86::BI__builtin_ia32_gatherq_ps:
  3344. case X86::BI__builtin_ia32_gatherq_ps256:
  3345. case X86::BI__builtin_ia32_gatherd_q:
  3346. case X86::BI__builtin_ia32_gatherd_q256:
  3347. case X86::BI__builtin_ia32_gatherq_q:
  3348. case X86::BI__builtin_ia32_gatherq_q256:
  3349. case X86::BI__builtin_ia32_gatherd_d:
  3350. case X86::BI__builtin_ia32_gatherd_d256:
  3351. case X86::BI__builtin_ia32_gatherq_d:
  3352. case X86::BI__builtin_ia32_gatherq_d256:
  3353. case X86::BI__builtin_ia32_gather3div2df:
  3354. case X86::BI__builtin_ia32_gather3div2di:
  3355. case X86::BI__builtin_ia32_gather3div4df:
  3356. case X86::BI__builtin_ia32_gather3div4di:
  3357. case X86::BI__builtin_ia32_gather3div4sf:
  3358. case X86::BI__builtin_ia32_gather3div4si:
  3359. case X86::BI__builtin_ia32_gather3div8sf:
  3360. case X86::BI__builtin_ia32_gather3div8si:
  3361. case X86::BI__builtin_ia32_gather3siv2df:
  3362. case X86::BI__builtin_ia32_gather3siv2di:
  3363. case X86::BI__builtin_ia32_gather3siv4df:
  3364. case X86::BI__builtin_ia32_gather3siv4di:
  3365. case X86::BI__builtin_ia32_gather3siv4sf:
  3366. case X86::BI__builtin_ia32_gather3siv4si:
  3367. case X86::BI__builtin_ia32_gather3siv8sf:
  3368. case X86::BI__builtin_ia32_gather3siv8si:
  3369. case X86::BI__builtin_ia32_gathersiv8df:
  3370. case X86::BI__builtin_ia32_gathersiv16sf:
  3371. case X86::BI__builtin_ia32_gatherdiv8df:
  3372. case X86::BI__builtin_ia32_gatherdiv16sf:
  3373. case X86::BI__builtin_ia32_gathersiv8di:
  3374. case X86::BI__builtin_ia32_gathersiv16si:
  3375. case X86::BI__builtin_ia32_gatherdiv8di:
  3376. case X86::BI__builtin_ia32_gatherdiv16si:
  3377. case X86::BI__builtin_ia32_scatterdiv2df:
  3378. case X86::BI__builtin_ia32_scatterdiv2di:
  3379. case X86::BI__builtin_ia32_scatterdiv4df:
  3380. case X86::BI__builtin_ia32_scatterdiv4di:
  3381. case X86::BI__builtin_ia32_scatterdiv4sf:
  3382. case X86::BI__builtin_ia32_scatterdiv4si:
  3383. case X86::BI__builtin_ia32_scatterdiv8sf:
  3384. case X86::BI__builtin_ia32_scatterdiv8si:
  3385. case X86::BI__builtin_ia32_scattersiv2df:
  3386. case X86::BI__builtin_ia32_scattersiv2di:
  3387. case X86::BI__builtin_ia32_scattersiv4df:
  3388. case X86::BI__builtin_ia32_scattersiv4di:
  3389. case X86::BI__builtin_ia32_scattersiv4sf:
  3390. case X86::BI__builtin_ia32_scattersiv4si:
  3391. case X86::BI__builtin_ia32_scattersiv8sf:
  3392. case X86::BI__builtin_ia32_scattersiv8si:
  3393. case X86::BI__builtin_ia32_scattersiv8df:
  3394. case X86::BI__builtin_ia32_scattersiv16sf:
  3395. case X86::BI__builtin_ia32_scatterdiv8df:
  3396. case X86::BI__builtin_ia32_scatterdiv16sf:
  3397. case X86::BI__builtin_ia32_scattersiv8di:
  3398. case X86::BI__builtin_ia32_scattersiv16si:
  3399. case X86::BI__builtin_ia32_scatterdiv8di:
  3400. case X86::BI__builtin_ia32_scatterdiv16si:
  3401. ArgNum = 4;
  3402. break;
  3403. }
  3404. llvm::APSInt Result;
  3405. // We can't check the value of a dependent argument.
  3406. Expr *Arg = TheCall->getArg(ArgNum);
  3407. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3408. return false;
  3409. // Check constant-ness first.
  3410. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3411. return true;
  3412. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  3413. return false;
  3414. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
  3415. << Arg->getSourceRange();
  3416. }
  3417. static bool isX86_32Builtin(unsigned BuiltinID) {
  3418. // These builtins only work on x86-32 targets.
  3419. switch (BuiltinID) {
  3420. case X86::BI__builtin_ia32_readeflags_u32:
  3421. case X86::BI__builtin_ia32_writeeflags_u32:
  3422. return true;
  3423. }
  3424. return false;
  3425. }
  3426. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  3427. if (BuiltinID == X86::BI__builtin_cpu_supports)
  3428. return SemaBuiltinCpuSupports(*this, TheCall);
  3429. if (BuiltinID == X86::BI__builtin_cpu_is)
  3430. return SemaBuiltinCpuIs(*this, TheCall);
  3431. // Check for 32-bit only builtins on a 64-bit target.
  3432. const llvm::Triple &TT = Context.getTargetInfo().getTriple();
  3433. if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
  3434. return Diag(TheCall->getCallee()->getBeginLoc(),
  3435. diag::err_32_bit_builtin_64_bit_tgt);
  3436. // If the intrinsic has rounding or SAE make sure its valid.
  3437. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  3438. return true;
  3439. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  3440. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  3441. return true;
  3442. // For intrinsics which take an immediate value as part of the instruction,
  3443. // range check them here.
  3444. int i = 0, l = 0, u = 0;
  3445. switch (BuiltinID) {
  3446. default:
  3447. return false;
  3448. case X86::BI__builtin_ia32_vec_ext_v2si:
  3449. case X86::BI__builtin_ia32_vec_ext_v2di:
  3450. case X86::BI__builtin_ia32_vextractf128_pd256:
  3451. case X86::BI__builtin_ia32_vextractf128_ps256:
  3452. case X86::BI__builtin_ia32_vextractf128_si256:
  3453. case X86::BI__builtin_ia32_extract128i256:
  3454. case X86::BI__builtin_ia32_extractf64x4_mask:
  3455. case X86::BI__builtin_ia32_extracti64x4_mask:
  3456. case X86::BI__builtin_ia32_extractf32x8_mask:
  3457. case X86::BI__builtin_ia32_extracti32x8_mask:
  3458. case X86::BI__builtin_ia32_extractf64x2_256_mask:
  3459. case X86::BI__builtin_ia32_extracti64x2_256_mask:
  3460. case X86::BI__builtin_ia32_extractf32x4_256_mask:
  3461. case X86::BI__builtin_ia32_extracti32x4_256_mask:
  3462. i = 1; l = 0; u = 1;
  3463. break;
  3464. case X86::BI__builtin_ia32_vec_set_v2di:
  3465. case X86::BI__builtin_ia32_vinsertf128_pd256:
  3466. case X86::BI__builtin_ia32_vinsertf128_ps256:
  3467. case X86::BI__builtin_ia32_vinsertf128_si256:
  3468. case X86::BI__builtin_ia32_insert128i256:
  3469. case X86::BI__builtin_ia32_insertf32x8:
  3470. case X86::BI__builtin_ia32_inserti32x8:
  3471. case X86::BI__builtin_ia32_insertf64x4:
  3472. case X86::BI__builtin_ia32_inserti64x4:
  3473. case X86::BI__builtin_ia32_insertf64x2_256:
  3474. case X86::BI__builtin_ia32_inserti64x2_256:
  3475. case X86::BI__builtin_ia32_insertf32x4_256:
  3476. case X86::BI__builtin_ia32_inserti32x4_256:
  3477. i = 2; l = 0; u = 1;
  3478. break;
  3479. case X86::BI__builtin_ia32_vpermilpd:
  3480. case X86::BI__builtin_ia32_vec_ext_v4hi:
  3481. case X86::BI__builtin_ia32_vec_ext_v4si:
  3482. case X86::BI__builtin_ia32_vec_ext_v4sf:
  3483. case X86::BI__builtin_ia32_vec_ext_v4di:
  3484. case X86::BI__builtin_ia32_extractf32x4_mask:
  3485. case X86::BI__builtin_ia32_extracti32x4_mask:
  3486. case X86::BI__builtin_ia32_extractf64x2_512_mask:
  3487. case X86::BI__builtin_ia32_extracti64x2_512_mask:
  3488. i = 1; l = 0; u = 3;
  3489. break;
  3490. case X86::BI_mm_prefetch:
  3491. case X86::BI__builtin_ia32_vec_ext_v8hi:
  3492. case X86::BI__builtin_ia32_vec_ext_v8si:
  3493. i = 1; l = 0; u = 7;
  3494. break;
  3495. case X86::BI__builtin_ia32_sha1rnds4:
  3496. case X86::BI__builtin_ia32_blendpd:
  3497. case X86::BI__builtin_ia32_shufpd:
  3498. case X86::BI__builtin_ia32_vec_set_v4hi:
  3499. case X86::BI__builtin_ia32_vec_set_v4si:
  3500. case X86::BI__builtin_ia32_vec_set_v4di:
  3501. case X86::BI__builtin_ia32_shuf_f32x4_256:
  3502. case X86::BI__builtin_ia32_shuf_f64x2_256:
  3503. case X86::BI__builtin_ia32_shuf_i32x4_256:
  3504. case X86::BI__builtin_ia32_shuf_i64x2_256:
  3505. case X86::BI__builtin_ia32_insertf64x2_512:
  3506. case X86::BI__builtin_ia32_inserti64x2_512:
  3507. case X86::BI__builtin_ia32_insertf32x4:
  3508. case X86::BI__builtin_ia32_inserti32x4:
  3509. i = 2; l = 0; u = 3;
  3510. break;
  3511. case X86::BI__builtin_ia32_vpermil2pd:
  3512. case X86::BI__builtin_ia32_vpermil2pd256:
  3513. case X86::BI__builtin_ia32_vpermil2ps:
  3514. case X86::BI__builtin_ia32_vpermil2ps256:
  3515. i = 3; l = 0; u = 3;
  3516. break;
  3517. case X86::BI__builtin_ia32_cmpb128_mask:
  3518. case X86::BI__builtin_ia32_cmpw128_mask:
  3519. case X86::BI__builtin_ia32_cmpd128_mask:
  3520. case X86::BI__builtin_ia32_cmpq128_mask:
  3521. case X86::BI__builtin_ia32_cmpb256_mask:
  3522. case X86::BI__builtin_ia32_cmpw256_mask:
  3523. case X86::BI__builtin_ia32_cmpd256_mask:
  3524. case X86::BI__builtin_ia32_cmpq256_mask:
  3525. case X86::BI__builtin_ia32_cmpb512_mask:
  3526. case X86::BI__builtin_ia32_cmpw512_mask:
  3527. case X86::BI__builtin_ia32_cmpd512_mask:
  3528. case X86::BI__builtin_ia32_cmpq512_mask:
  3529. case X86::BI__builtin_ia32_ucmpb128_mask:
  3530. case X86::BI__builtin_ia32_ucmpw128_mask:
  3531. case X86::BI__builtin_ia32_ucmpd128_mask:
  3532. case X86::BI__builtin_ia32_ucmpq128_mask:
  3533. case X86::BI__builtin_ia32_ucmpb256_mask:
  3534. case X86::BI__builtin_ia32_ucmpw256_mask:
  3535. case X86::BI__builtin_ia32_ucmpd256_mask:
  3536. case X86::BI__builtin_ia32_ucmpq256_mask:
  3537. case X86::BI__builtin_ia32_ucmpb512_mask:
  3538. case X86::BI__builtin_ia32_ucmpw512_mask:
  3539. case X86::BI__builtin_ia32_ucmpd512_mask:
  3540. case X86::BI__builtin_ia32_ucmpq512_mask:
  3541. case X86::BI__builtin_ia32_vpcomub:
  3542. case X86::BI__builtin_ia32_vpcomuw:
  3543. case X86::BI__builtin_ia32_vpcomud:
  3544. case X86::BI__builtin_ia32_vpcomuq:
  3545. case X86::BI__builtin_ia32_vpcomb:
  3546. case X86::BI__builtin_ia32_vpcomw:
  3547. case X86::BI__builtin_ia32_vpcomd:
  3548. case X86::BI__builtin_ia32_vpcomq:
  3549. case X86::BI__builtin_ia32_vec_set_v8hi:
  3550. case X86::BI__builtin_ia32_vec_set_v8si:
  3551. i = 2; l = 0; u = 7;
  3552. break;
  3553. case X86::BI__builtin_ia32_vpermilpd256:
  3554. case X86::BI__builtin_ia32_roundps:
  3555. case X86::BI__builtin_ia32_roundpd:
  3556. case X86::BI__builtin_ia32_roundps256:
  3557. case X86::BI__builtin_ia32_roundpd256:
  3558. case X86::BI__builtin_ia32_getmantpd128_mask:
  3559. case X86::BI__builtin_ia32_getmantpd256_mask:
  3560. case X86::BI__builtin_ia32_getmantps128_mask:
  3561. case X86::BI__builtin_ia32_getmantps256_mask:
  3562. case X86::BI__builtin_ia32_getmantpd512_mask:
  3563. case X86::BI__builtin_ia32_getmantps512_mask:
  3564. case X86::BI__builtin_ia32_vec_ext_v16qi:
  3565. case X86::BI__builtin_ia32_vec_ext_v16hi:
  3566. i = 1; l = 0; u = 15;
  3567. break;
  3568. case X86::BI__builtin_ia32_pblendd128:
  3569. case X86::BI__builtin_ia32_blendps:
  3570. case X86::BI__builtin_ia32_blendpd256:
  3571. case X86::BI__builtin_ia32_shufpd256:
  3572. case X86::BI__builtin_ia32_roundss:
  3573. case X86::BI__builtin_ia32_roundsd:
  3574. case X86::BI__builtin_ia32_rangepd128_mask:
  3575. case X86::BI__builtin_ia32_rangepd256_mask:
  3576. case X86::BI__builtin_ia32_rangepd512_mask:
  3577. case X86::BI__builtin_ia32_rangeps128_mask:
  3578. case X86::BI__builtin_ia32_rangeps256_mask:
  3579. case X86::BI__builtin_ia32_rangeps512_mask:
  3580. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3581. case X86::BI__builtin_ia32_getmantss_round_mask:
  3582. case X86::BI__builtin_ia32_vec_set_v16qi:
  3583. case X86::BI__builtin_ia32_vec_set_v16hi:
  3584. i = 2; l = 0; u = 15;
  3585. break;
  3586. case X86::BI__builtin_ia32_vec_ext_v32qi:
  3587. i = 1; l = 0; u = 31;
  3588. break;
  3589. case X86::BI__builtin_ia32_cmpps:
  3590. case X86::BI__builtin_ia32_cmpss:
  3591. case X86::BI__builtin_ia32_cmppd:
  3592. case X86::BI__builtin_ia32_cmpsd:
  3593. case X86::BI__builtin_ia32_cmpps256:
  3594. case X86::BI__builtin_ia32_cmppd256:
  3595. case X86::BI__builtin_ia32_cmpps128_mask:
  3596. case X86::BI__builtin_ia32_cmppd128_mask:
  3597. case X86::BI__builtin_ia32_cmpps256_mask:
  3598. case X86::BI__builtin_ia32_cmppd256_mask:
  3599. case X86::BI__builtin_ia32_cmpps512_mask:
  3600. case X86::BI__builtin_ia32_cmppd512_mask:
  3601. case X86::BI__builtin_ia32_cmpsd_mask:
  3602. case X86::BI__builtin_ia32_cmpss_mask:
  3603. case X86::BI__builtin_ia32_vec_set_v32qi:
  3604. i = 2; l = 0; u = 31;
  3605. break;
  3606. case X86::BI__builtin_ia32_permdf256:
  3607. case X86::BI__builtin_ia32_permdi256:
  3608. case X86::BI__builtin_ia32_permdf512:
  3609. case X86::BI__builtin_ia32_permdi512:
  3610. case X86::BI__builtin_ia32_vpermilps:
  3611. case X86::BI__builtin_ia32_vpermilps256:
  3612. case X86::BI__builtin_ia32_vpermilpd512:
  3613. case X86::BI__builtin_ia32_vpermilps512:
  3614. case X86::BI__builtin_ia32_pshufd:
  3615. case X86::BI__builtin_ia32_pshufd256:
  3616. case X86::BI__builtin_ia32_pshufd512:
  3617. case X86::BI__builtin_ia32_pshufhw:
  3618. case X86::BI__builtin_ia32_pshufhw256:
  3619. case X86::BI__builtin_ia32_pshufhw512:
  3620. case X86::BI__builtin_ia32_pshuflw:
  3621. case X86::BI__builtin_ia32_pshuflw256:
  3622. case X86::BI__builtin_ia32_pshuflw512:
  3623. case X86::BI__builtin_ia32_vcvtps2ph:
  3624. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  3625. case X86::BI__builtin_ia32_vcvtps2ph256:
  3626. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  3627. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  3628. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  3629. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  3630. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  3631. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  3632. case X86::BI__builtin_ia32_rndscaleps_mask:
  3633. case X86::BI__builtin_ia32_rndscalepd_mask:
  3634. case X86::BI__builtin_ia32_reducepd128_mask:
  3635. case X86::BI__builtin_ia32_reducepd256_mask:
  3636. case X86::BI__builtin_ia32_reducepd512_mask:
  3637. case X86::BI__builtin_ia32_reduceps128_mask:
  3638. case X86::BI__builtin_ia32_reduceps256_mask:
  3639. case X86::BI__builtin_ia32_reduceps512_mask:
  3640. case X86::BI__builtin_ia32_prold512:
  3641. case X86::BI__builtin_ia32_prolq512:
  3642. case X86::BI__builtin_ia32_prold128:
  3643. case X86::BI__builtin_ia32_prold256:
  3644. case X86::BI__builtin_ia32_prolq128:
  3645. case X86::BI__builtin_ia32_prolq256:
  3646. case X86::BI__builtin_ia32_prord512:
  3647. case X86::BI__builtin_ia32_prorq512:
  3648. case X86::BI__builtin_ia32_prord128:
  3649. case X86::BI__builtin_ia32_prord256:
  3650. case X86::BI__builtin_ia32_prorq128:
  3651. case X86::BI__builtin_ia32_prorq256:
  3652. case X86::BI__builtin_ia32_fpclasspd128_mask:
  3653. case X86::BI__builtin_ia32_fpclasspd256_mask:
  3654. case X86::BI__builtin_ia32_fpclassps128_mask:
  3655. case X86::BI__builtin_ia32_fpclassps256_mask:
  3656. case X86::BI__builtin_ia32_fpclassps512_mask:
  3657. case X86::BI__builtin_ia32_fpclasspd512_mask:
  3658. case X86::BI__builtin_ia32_fpclasssd_mask:
  3659. case X86::BI__builtin_ia32_fpclassss_mask:
  3660. case X86::BI__builtin_ia32_pslldqi128_byteshift:
  3661. case X86::BI__builtin_ia32_pslldqi256_byteshift:
  3662. case X86::BI__builtin_ia32_pslldqi512_byteshift:
  3663. case X86::BI__builtin_ia32_psrldqi128_byteshift:
  3664. case X86::BI__builtin_ia32_psrldqi256_byteshift:
  3665. case X86::BI__builtin_ia32_psrldqi512_byteshift:
  3666. case X86::BI__builtin_ia32_kshiftliqi:
  3667. case X86::BI__builtin_ia32_kshiftlihi:
  3668. case X86::BI__builtin_ia32_kshiftlisi:
  3669. case X86::BI__builtin_ia32_kshiftlidi:
  3670. case X86::BI__builtin_ia32_kshiftriqi:
  3671. case X86::BI__builtin_ia32_kshiftrihi:
  3672. case X86::BI__builtin_ia32_kshiftrisi:
  3673. case X86::BI__builtin_ia32_kshiftridi:
  3674. i = 1; l = 0; u = 255;
  3675. break;
  3676. case X86::BI__builtin_ia32_vperm2f128_pd256:
  3677. case X86::BI__builtin_ia32_vperm2f128_ps256:
  3678. case X86::BI__builtin_ia32_vperm2f128_si256:
  3679. case X86::BI__builtin_ia32_permti256:
  3680. case X86::BI__builtin_ia32_pblendw128:
  3681. case X86::BI__builtin_ia32_pblendw256:
  3682. case X86::BI__builtin_ia32_blendps256:
  3683. case X86::BI__builtin_ia32_pblendd256:
  3684. case X86::BI__builtin_ia32_palignr128:
  3685. case X86::BI__builtin_ia32_palignr256:
  3686. case X86::BI__builtin_ia32_palignr512:
  3687. case X86::BI__builtin_ia32_alignq512:
  3688. case X86::BI__builtin_ia32_alignd512:
  3689. case X86::BI__builtin_ia32_alignd128:
  3690. case X86::BI__builtin_ia32_alignd256:
  3691. case X86::BI__builtin_ia32_alignq128:
  3692. case X86::BI__builtin_ia32_alignq256:
  3693. case X86::BI__builtin_ia32_vcomisd:
  3694. case X86::BI__builtin_ia32_vcomiss:
  3695. case X86::BI__builtin_ia32_shuf_f32x4:
  3696. case X86::BI__builtin_ia32_shuf_f64x2:
  3697. case X86::BI__builtin_ia32_shuf_i32x4:
  3698. case X86::BI__builtin_ia32_shuf_i64x2:
  3699. case X86::BI__builtin_ia32_shufpd512:
  3700. case X86::BI__builtin_ia32_shufps:
  3701. case X86::BI__builtin_ia32_shufps256:
  3702. case X86::BI__builtin_ia32_shufps512:
  3703. case X86::BI__builtin_ia32_dbpsadbw128:
  3704. case X86::BI__builtin_ia32_dbpsadbw256:
  3705. case X86::BI__builtin_ia32_dbpsadbw512:
  3706. case X86::BI__builtin_ia32_vpshldd128:
  3707. case X86::BI__builtin_ia32_vpshldd256:
  3708. case X86::BI__builtin_ia32_vpshldd512:
  3709. case X86::BI__builtin_ia32_vpshldq128:
  3710. case X86::BI__builtin_ia32_vpshldq256:
  3711. case X86::BI__builtin_ia32_vpshldq512:
  3712. case X86::BI__builtin_ia32_vpshldw128:
  3713. case X86::BI__builtin_ia32_vpshldw256:
  3714. case X86::BI__builtin_ia32_vpshldw512:
  3715. case X86::BI__builtin_ia32_vpshrdd128:
  3716. case X86::BI__builtin_ia32_vpshrdd256:
  3717. case X86::BI__builtin_ia32_vpshrdd512:
  3718. case X86::BI__builtin_ia32_vpshrdq128:
  3719. case X86::BI__builtin_ia32_vpshrdq256:
  3720. case X86::BI__builtin_ia32_vpshrdq512:
  3721. case X86::BI__builtin_ia32_vpshrdw128:
  3722. case X86::BI__builtin_ia32_vpshrdw256:
  3723. case X86::BI__builtin_ia32_vpshrdw512:
  3724. i = 2; l = 0; u = 255;
  3725. break;
  3726. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3727. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3728. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3729. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3730. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3731. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3732. case X86::BI__builtin_ia32_fixupimmss_mask:
  3733. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3734. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  3735. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  3736. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  3737. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  3738. case X86::BI__builtin_ia32_fixupimmps128_mask:
  3739. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  3740. case X86::BI__builtin_ia32_fixupimmps256_mask:
  3741. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  3742. case X86::BI__builtin_ia32_pternlogd512_mask:
  3743. case X86::BI__builtin_ia32_pternlogd512_maskz:
  3744. case X86::BI__builtin_ia32_pternlogq512_mask:
  3745. case X86::BI__builtin_ia32_pternlogq512_maskz:
  3746. case X86::BI__builtin_ia32_pternlogd128_mask:
  3747. case X86::BI__builtin_ia32_pternlogd128_maskz:
  3748. case X86::BI__builtin_ia32_pternlogd256_mask:
  3749. case X86::BI__builtin_ia32_pternlogd256_maskz:
  3750. case X86::BI__builtin_ia32_pternlogq128_mask:
  3751. case X86::BI__builtin_ia32_pternlogq128_maskz:
  3752. case X86::BI__builtin_ia32_pternlogq256_mask:
  3753. case X86::BI__builtin_ia32_pternlogq256_maskz:
  3754. i = 3; l = 0; u = 255;
  3755. break;
  3756. case X86::BI__builtin_ia32_gatherpfdpd:
  3757. case X86::BI__builtin_ia32_gatherpfdps:
  3758. case X86::BI__builtin_ia32_gatherpfqpd:
  3759. case X86::BI__builtin_ia32_gatherpfqps:
  3760. case X86::BI__builtin_ia32_scatterpfdpd:
  3761. case X86::BI__builtin_ia32_scatterpfdps:
  3762. case X86::BI__builtin_ia32_scatterpfqpd:
  3763. case X86::BI__builtin_ia32_scatterpfqps:
  3764. i = 4; l = 2; u = 3;
  3765. break;
  3766. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3767. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3768. i = 4; l = 0; u = 255;
  3769. break;
  3770. }
  3771. // Note that we don't force a hard error on the range check here, allowing
  3772. // template-generated or macro-generated dead code to potentially have out-of-
  3773. // range values. These need to code generate, but don't need to necessarily
  3774. // make any sense. We use a warning that defaults to an error.
  3775. return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
  3776. }
  3777. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  3778. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  3779. /// Returns true when the format fits the function and the FormatStringInfo has
  3780. /// been populated.
  3781. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  3782. FormatStringInfo *FSI) {
  3783. FSI->HasVAListArg = Format->getFirstArg() == 0;
  3784. FSI->FormatIdx = Format->getFormatIdx() - 1;
  3785. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  3786. // The way the format attribute works in GCC, the implicit this argument
  3787. // of member functions is counted. However, it doesn't appear in our own
  3788. // lists, so decrement format_idx in that case.
  3789. if (IsCXXMember) {
  3790. if(FSI->FormatIdx == 0)
  3791. return false;
  3792. --FSI->FormatIdx;
  3793. if (FSI->FirstDataArg != 0)
  3794. --FSI->FirstDataArg;
  3795. }
  3796. return true;
  3797. }
  3798. /// Checks if a the given expression evaluates to null.
  3799. ///
  3800. /// Returns true if the value evaluates to null.
  3801. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  3802. // If the expression has non-null type, it doesn't evaluate to null.
  3803. if (auto nullability
  3804. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  3805. if (*nullability == NullabilityKind::NonNull)
  3806. return false;
  3807. }
  3808. // As a special case, transparent unions initialized with zero are
  3809. // considered null for the purposes of the nonnull attribute.
  3810. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  3811. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  3812. if (const CompoundLiteralExpr *CLE =
  3813. dyn_cast<CompoundLiteralExpr>(Expr))
  3814. if (const InitListExpr *ILE =
  3815. dyn_cast<InitListExpr>(CLE->getInitializer()))
  3816. Expr = ILE->getInit(0);
  3817. }
  3818. bool Result;
  3819. return (!Expr->isValueDependent() &&
  3820. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  3821. !Result);
  3822. }
  3823. static void CheckNonNullArgument(Sema &S,
  3824. const Expr *ArgExpr,
  3825. SourceLocation CallSiteLoc) {
  3826. if (CheckNonNullExpr(S, ArgExpr))
  3827. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  3828. S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
  3829. }
  3830. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  3831. FormatStringInfo FSI;
  3832. if ((GetFormatStringType(Format) == FST_NSString) &&
  3833. getFormatStringInfo(Format, false, &FSI)) {
  3834. Idx = FSI.FormatIdx;
  3835. return true;
  3836. }
  3837. return false;
  3838. }
  3839. /// Diagnose use of %s directive in an NSString which is being passed
  3840. /// as formatting string to formatting method.
  3841. static void
  3842. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  3843. const NamedDecl *FDecl,
  3844. Expr **Args,
  3845. unsigned NumArgs) {
  3846. unsigned Idx = 0;
  3847. bool Format = false;
  3848. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  3849. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  3850. Idx = 2;
  3851. Format = true;
  3852. }
  3853. else
  3854. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3855. if (S.GetFormatNSStringIdx(I, Idx)) {
  3856. Format = true;
  3857. break;
  3858. }
  3859. }
  3860. if (!Format || NumArgs <= Idx)
  3861. return;
  3862. const Expr *FormatExpr = Args[Idx];
  3863. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  3864. FormatExpr = CSCE->getSubExpr();
  3865. const StringLiteral *FormatString;
  3866. if (const ObjCStringLiteral *OSL =
  3867. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  3868. FormatString = OSL->getString();
  3869. else
  3870. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  3871. if (!FormatString)
  3872. return;
  3873. if (S.FormatStringHasSArg(FormatString)) {
  3874. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  3875. << "%s" << 1 << 1;
  3876. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  3877. << FDecl->getDeclName();
  3878. }
  3879. }
  3880. /// Determine whether the given type has a non-null nullability annotation.
  3881. static bool isNonNullType(ASTContext &ctx, QualType type) {
  3882. if (auto nullability = type->getNullability(ctx))
  3883. return *nullability == NullabilityKind::NonNull;
  3884. return false;
  3885. }
  3886. static void CheckNonNullArguments(Sema &S,
  3887. const NamedDecl *FDecl,
  3888. const FunctionProtoType *Proto,
  3889. ArrayRef<const Expr *> Args,
  3890. SourceLocation CallSiteLoc) {
  3891. assert((FDecl || Proto) && "Need a function declaration or prototype");
  3892. // Check the attributes attached to the method/function itself.
  3893. llvm::SmallBitVector NonNullArgs;
  3894. if (FDecl) {
  3895. // Handle the nonnull attribute on the function/method declaration itself.
  3896. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  3897. if (!NonNull->args_size()) {
  3898. // Easy case: all pointer arguments are nonnull.
  3899. for (const auto *Arg : Args)
  3900. if (S.isValidPointerAttrType(Arg->getType()))
  3901. CheckNonNullArgument(S, Arg, CallSiteLoc);
  3902. return;
  3903. }
  3904. for (const ParamIdx &Idx : NonNull->args()) {
  3905. unsigned IdxAST = Idx.getASTIndex();
  3906. if (IdxAST >= Args.size())
  3907. continue;
  3908. if (NonNullArgs.empty())
  3909. NonNullArgs.resize(Args.size());
  3910. NonNullArgs.set(IdxAST);
  3911. }
  3912. }
  3913. }
  3914. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  3915. // Handle the nonnull attribute on the parameters of the
  3916. // function/method.
  3917. ArrayRef<ParmVarDecl*> parms;
  3918. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  3919. parms = FD->parameters();
  3920. else
  3921. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  3922. unsigned ParamIndex = 0;
  3923. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  3924. I != E; ++I, ++ParamIndex) {
  3925. const ParmVarDecl *PVD = *I;
  3926. if (PVD->hasAttr<NonNullAttr>() ||
  3927. isNonNullType(S.Context, PVD->getType())) {
  3928. if (NonNullArgs.empty())
  3929. NonNullArgs.resize(Args.size());
  3930. NonNullArgs.set(ParamIndex);
  3931. }
  3932. }
  3933. } else {
  3934. // If we have a non-function, non-method declaration but no
  3935. // function prototype, try to dig out the function prototype.
  3936. if (!Proto) {
  3937. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  3938. QualType type = VD->getType().getNonReferenceType();
  3939. if (auto pointerType = type->getAs<PointerType>())
  3940. type = pointerType->getPointeeType();
  3941. else if (auto blockType = type->getAs<BlockPointerType>())
  3942. type = blockType->getPointeeType();
  3943. // FIXME: data member pointers?
  3944. // Dig out the function prototype, if there is one.
  3945. Proto = type->getAs<FunctionProtoType>();
  3946. }
  3947. }
  3948. // Fill in non-null argument information from the nullability
  3949. // information on the parameter types (if we have them).
  3950. if (Proto) {
  3951. unsigned Index = 0;
  3952. for (auto paramType : Proto->getParamTypes()) {
  3953. if (isNonNullType(S.Context, paramType)) {
  3954. if (NonNullArgs.empty())
  3955. NonNullArgs.resize(Args.size());
  3956. NonNullArgs.set(Index);
  3957. }
  3958. ++Index;
  3959. }
  3960. }
  3961. }
  3962. // Check for non-null arguments.
  3963. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  3964. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  3965. if (NonNullArgs[ArgIndex])
  3966. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  3967. }
  3968. }
  3969. /// Handles the checks for format strings, non-POD arguments to vararg
  3970. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  3971. /// attributes.
  3972. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  3973. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  3974. bool IsMemberFunction, SourceLocation Loc,
  3975. SourceRange Range, VariadicCallType CallType) {
  3976. // FIXME: We should check as much as we can in the template definition.
  3977. if (CurContext->isDependentContext())
  3978. return;
  3979. // Printf and scanf checking.
  3980. llvm::SmallBitVector CheckedVarArgs;
  3981. if (FDecl) {
  3982. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3983. // Only create vector if there are format attributes.
  3984. CheckedVarArgs.resize(Args.size());
  3985. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  3986. CheckedVarArgs);
  3987. }
  3988. }
  3989. // Refuse POD arguments that weren't caught by the format string
  3990. // checks above.
  3991. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  3992. if (CallType != VariadicDoesNotApply &&
  3993. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  3994. unsigned NumParams = Proto ? Proto->getNumParams()
  3995. : FDecl && isa<FunctionDecl>(FDecl)
  3996. ? cast<FunctionDecl>(FDecl)->getNumParams()
  3997. : FDecl && isa<ObjCMethodDecl>(FDecl)
  3998. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  3999. : 0;
  4000. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  4001. // Args[ArgIdx] can be null in malformed code.
  4002. if (const Expr *Arg = Args[ArgIdx]) {
  4003. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  4004. checkVariadicArgument(Arg, CallType);
  4005. }
  4006. }
  4007. }
  4008. if (FDecl || Proto) {
  4009. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  4010. // Type safety checking.
  4011. if (FDecl) {
  4012. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  4013. CheckArgumentWithTypeTag(I, Args, Loc);
  4014. }
  4015. }
  4016. if (FD)
  4017. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  4018. }
  4019. /// CheckConstructorCall - Check a constructor call for correctness and safety
  4020. /// properties not enforced by the C type system.
  4021. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  4022. ArrayRef<const Expr *> Args,
  4023. const FunctionProtoType *Proto,
  4024. SourceLocation Loc) {
  4025. VariadicCallType CallType =
  4026. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  4027. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  4028. Loc, SourceRange(), CallType);
  4029. }
  4030. /// CheckFunctionCall - Check a direct function call for various correctness
  4031. /// and safety properties not strictly enforced by the C type system.
  4032. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  4033. const FunctionProtoType *Proto) {
  4034. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  4035. isa<CXXMethodDecl>(FDecl);
  4036. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  4037. IsMemberOperatorCall;
  4038. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  4039. TheCall->getCallee());
  4040. Expr** Args = TheCall->getArgs();
  4041. unsigned NumArgs = TheCall->getNumArgs();
  4042. Expr *ImplicitThis = nullptr;
  4043. if (IsMemberOperatorCall) {
  4044. // If this is a call to a member operator, hide the first argument
  4045. // from checkCall.
  4046. // FIXME: Our choice of AST representation here is less than ideal.
  4047. ImplicitThis = Args[0];
  4048. ++Args;
  4049. --NumArgs;
  4050. } else if (IsMemberFunction)
  4051. ImplicitThis =
  4052. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  4053. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  4054. IsMemberFunction, TheCall->getRParenLoc(),
  4055. TheCall->getCallee()->getSourceRange(), CallType);
  4056. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  4057. // None of the checks below are needed for functions that don't have
  4058. // simple names (e.g., C++ conversion functions).
  4059. if (!FnInfo)
  4060. return false;
  4061. CheckAbsoluteValueFunction(TheCall, FDecl);
  4062. CheckMaxUnsignedZero(TheCall, FDecl);
  4063. if (getLangOpts().ObjC)
  4064. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  4065. unsigned CMId = FDecl->getMemoryFunctionKind();
  4066. if (CMId == 0)
  4067. return false;
  4068. // Handle memory setting and copying functions.
  4069. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  4070. CheckStrlcpycatArguments(TheCall, FnInfo);
  4071. else if (CMId == Builtin::BIstrncat)
  4072. CheckStrncatArguments(TheCall, FnInfo);
  4073. else
  4074. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  4075. return false;
  4076. }
  4077. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  4078. ArrayRef<const Expr *> Args) {
  4079. VariadicCallType CallType =
  4080. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  4081. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  4082. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  4083. CallType);
  4084. return false;
  4085. }
  4086. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  4087. const FunctionProtoType *Proto) {
  4088. QualType Ty;
  4089. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  4090. Ty = V->getType().getNonReferenceType();
  4091. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  4092. Ty = F->getType().getNonReferenceType();
  4093. else
  4094. return false;
  4095. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  4096. !Ty->isFunctionProtoType())
  4097. return false;
  4098. VariadicCallType CallType;
  4099. if (!Proto || !Proto->isVariadic()) {
  4100. CallType = VariadicDoesNotApply;
  4101. } else if (Ty->isBlockPointerType()) {
  4102. CallType = VariadicBlock;
  4103. } else { // Ty->isFunctionPointerType()
  4104. CallType = VariadicFunction;
  4105. }
  4106. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  4107. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4108. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4109. TheCall->getCallee()->getSourceRange(), CallType);
  4110. return false;
  4111. }
  4112. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  4113. /// such as function pointers returned from functions.
  4114. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  4115. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  4116. TheCall->getCallee());
  4117. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  4118. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4119. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4120. TheCall->getCallee()->getSourceRange(), CallType);
  4121. return false;
  4122. }
  4123. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  4124. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  4125. return false;
  4126. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  4127. switch (Op) {
  4128. case AtomicExpr::AO__c11_atomic_init:
  4129. case AtomicExpr::AO__opencl_atomic_init:
  4130. llvm_unreachable("There is no ordering argument for an init");
  4131. case AtomicExpr::AO__c11_atomic_load:
  4132. case AtomicExpr::AO__opencl_atomic_load:
  4133. case AtomicExpr::AO__atomic_load_n:
  4134. case AtomicExpr::AO__atomic_load:
  4135. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  4136. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4137. case AtomicExpr::AO__c11_atomic_store:
  4138. case AtomicExpr::AO__opencl_atomic_store:
  4139. case AtomicExpr::AO__atomic_store:
  4140. case AtomicExpr::AO__atomic_store_n:
  4141. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  4142. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  4143. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4144. default:
  4145. return true;
  4146. }
  4147. }
  4148. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  4149. AtomicExpr::AtomicOp Op) {
  4150. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  4151. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4152. // All the non-OpenCL operations take one of the following forms.
  4153. // The OpenCL operations take the __c11 forms with one extra argument for
  4154. // synchronization scope.
  4155. enum {
  4156. // C __c11_atomic_init(A *, C)
  4157. Init,
  4158. // C __c11_atomic_load(A *, int)
  4159. Load,
  4160. // void __atomic_load(A *, CP, int)
  4161. LoadCopy,
  4162. // void __atomic_store(A *, CP, int)
  4163. Copy,
  4164. // C __c11_atomic_add(A *, M, int)
  4165. Arithmetic,
  4166. // C __atomic_exchange_n(A *, CP, int)
  4167. Xchg,
  4168. // void __atomic_exchange(A *, C *, CP, int)
  4169. GNUXchg,
  4170. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  4171. C11CmpXchg,
  4172. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  4173. GNUCmpXchg
  4174. } Form = Init;
  4175. const unsigned NumForm = GNUCmpXchg + 1;
  4176. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  4177. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  4178. // where:
  4179. // C is an appropriate type,
  4180. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  4181. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  4182. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  4183. // the int parameters are for orderings.
  4184. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  4185. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  4186. "need to update code for modified forms");
  4187. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  4188. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  4189. AtomicExpr::AO__atomic_load,
  4190. "need to update code for modified C11 atomics");
  4191. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  4192. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  4193. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  4194. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  4195. IsOpenCL;
  4196. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  4197. Op == AtomicExpr::AO__atomic_store_n ||
  4198. Op == AtomicExpr::AO__atomic_exchange_n ||
  4199. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  4200. bool IsAddSub = false;
  4201. bool IsMinMax = false;
  4202. switch (Op) {
  4203. case AtomicExpr::AO__c11_atomic_init:
  4204. case AtomicExpr::AO__opencl_atomic_init:
  4205. Form = Init;
  4206. break;
  4207. case AtomicExpr::AO__c11_atomic_load:
  4208. case AtomicExpr::AO__opencl_atomic_load:
  4209. case AtomicExpr::AO__atomic_load_n:
  4210. Form = Load;
  4211. break;
  4212. case AtomicExpr::AO__atomic_load:
  4213. Form = LoadCopy;
  4214. break;
  4215. case AtomicExpr::AO__c11_atomic_store:
  4216. case AtomicExpr::AO__opencl_atomic_store:
  4217. case AtomicExpr::AO__atomic_store:
  4218. case AtomicExpr::AO__atomic_store_n:
  4219. Form = Copy;
  4220. break;
  4221. case AtomicExpr::AO__c11_atomic_fetch_add:
  4222. case AtomicExpr::AO__c11_atomic_fetch_sub:
  4223. case AtomicExpr::AO__opencl_atomic_fetch_add:
  4224. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  4225. case AtomicExpr::AO__opencl_atomic_fetch_min:
  4226. case AtomicExpr::AO__opencl_atomic_fetch_max:
  4227. case AtomicExpr::AO__atomic_fetch_add:
  4228. case AtomicExpr::AO__atomic_fetch_sub:
  4229. case AtomicExpr::AO__atomic_add_fetch:
  4230. case AtomicExpr::AO__atomic_sub_fetch:
  4231. IsAddSub = true;
  4232. LLVM_FALLTHROUGH;
  4233. case AtomicExpr::AO__c11_atomic_fetch_and:
  4234. case AtomicExpr::AO__c11_atomic_fetch_or:
  4235. case AtomicExpr::AO__c11_atomic_fetch_xor:
  4236. case AtomicExpr::AO__opencl_atomic_fetch_and:
  4237. case AtomicExpr::AO__opencl_atomic_fetch_or:
  4238. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  4239. case AtomicExpr::AO__atomic_fetch_and:
  4240. case AtomicExpr::AO__atomic_fetch_or:
  4241. case AtomicExpr::AO__atomic_fetch_xor:
  4242. case AtomicExpr::AO__atomic_fetch_nand:
  4243. case AtomicExpr::AO__atomic_and_fetch:
  4244. case AtomicExpr::AO__atomic_or_fetch:
  4245. case AtomicExpr::AO__atomic_xor_fetch:
  4246. case AtomicExpr::AO__atomic_nand_fetch:
  4247. Form = Arithmetic;
  4248. break;
  4249. case AtomicExpr::AO__atomic_fetch_min:
  4250. case AtomicExpr::AO__atomic_fetch_max:
  4251. IsMinMax = true;
  4252. Form = Arithmetic;
  4253. break;
  4254. case AtomicExpr::AO__c11_atomic_exchange:
  4255. case AtomicExpr::AO__opencl_atomic_exchange:
  4256. case AtomicExpr::AO__atomic_exchange_n:
  4257. Form = Xchg;
  4258. break;
  4259. case AtomicExpr::AO__atomic_exchange:
  4260. Form = GNUXchg;
  4261. break;
  4262. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  4263. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  4264. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  4265. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  4266. Form = C11CmpXchg;
  4267. break;
  4268. case AtomicExpr::AO__atomic_compare_exchange:
  4269. case AtomicExpr::AO__atomic_compare_exchange_n:
  4270. Form = GNUCmpXchg;
  4271. break;
  4272. }
  4273. unsigned AdjustedNumArgs = NumArgs[Form];
  4274. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  4275. ++AdjustedNumArgs;
  4276. // Check we have the right number of arguments.
  4277. if (TheCall->getNumArgs() < AdjustedNumArgs) {
  4278. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  4279. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4280. << TheCall->getCallee()->getSourceRange();
  4281. return ExprError();
  4282. } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
  4283. Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
  4284. diag::err_typecheck_call_too_many_args)
  4285. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4286. << TheCall->getCallee()->getSourceRange();
  4287. return ExprError();
  4288. }
  4289. // Inspect the first argument of the atomic operation.
  4290. Expr *Ptr = TheCall->getArg(0);
  4291. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  4292. if (ConvertedPtr.isInvalid())
  4293. return ExprError();
  4294. Ptr = ConvertedPtr.get();
  4295. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  4296. if (!pointerType) {
  4297. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4298. << Ptr->getType() << Ptr->getSourceRange();
  4299. return ExprError();
  4300. }
  4301. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  4302. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  4303. QualType ValType = AtomTy; // 'C'
  4304. if (IsC11) {
  4305. if (!AtomTy->isAtomicType()) {
  4306. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
  4307. << Ptr->getType() << Ptr->getSourceRange();
  4308. return ExprError();
  4309. }
  4310. if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
  4311. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  4312. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
  4313. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  4314. << Ptr->getSourceRange();
  4315. return ExprError();
  4316. }
  4317. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  4318. } else if (Form != Load && Form != LoadCopy) {
  4319. if (ValType.isConstQualified()) {
  4320. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
  4321. << Ptr->getType() << Ptr->getSourceRange();
  4322. return ExprError();
  4323. }
  4324. }
  4325. // For an arithmetic operation, the implied arithmetic must be well-formed.
  4326. if (Form == Arithmetic) {
  4327. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  4328. if (IsAddSub && !ValType->isIntegerType()
  4329. && !ValType->isPointerType()) {
  4330. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4331. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4332. return ExprError();
  4333. }
  4334. if (IsMinMax) {
  4335. const BuiltinType *BT = ValType->getAs<BuiltinType>();
  4336. if (!BT || (BT->getKind() != BuiltinType::Int &&
  4337. BT->getKind() != BuiltinType::UInt)) {
  4338. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
  4339. return ExprError();
  4340. }
  4341. }
  4342. if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
  4343. Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
  4344. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4345. return ExprError();
  4346. }
  4347. if (IsC11 && ValType->isPointerType() &&
  4348. RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
  4349. diag::err_incomplete_type)) {
  4350. return ExprError();
  4351. }
  4352. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  4353. // For __atomic_*_n operations, the value type must be a scalar integral or
  4354. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  4355. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4356. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4357. return ExprError();
  4358. }
  4359. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  4360. !AtomTy->isScalarType()) {
  4361. // For GNU atomics, require a trivially-copyable type. This is not part of
  4362. // the GNU atomics specification, but we enforce it for sanity.
  4363. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
  4364. << Ptr->getType() << Ptr->getSourceRange();
  4365. return ExprError();
  4366. }
  4367. switch (ValType.getObjCLifetime()) {
  4368. case Qualifiers::OCL_None:
  4369. case Qualifiers::OCL_ExplicitNone:
  4370. // okay
  4371. break;
  4372. case Qualifiers::OCL_Weak:
  4373. case Qualifiers::OCL_Strong:
  4374. case Qualifiers::OCL_Autoreleasing:
  4375. // FIXME: Can this happen? By this point, ValType should be known
  4376. // to be trivially copyable.
  4377. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4378. << ValType << Ptr->getSourceRange();
  4379. return ExprError();
  4380. }
  4381. // All atomic operations have an overload which takes a pointer to a volatile
  4382. // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
  4383. // into the result or the other operands. Similarly atomic_load takes a
  4384. // pointer to a const 'A'.
  4385. ValType.removeLocalVolatile();
  4386. ValType.removeLocalConst();
  4387. QualType ResultType = ValType;
  4388. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  4389. Form == Init)
  4390. ResultType = Context.VoidTy;
  4391. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  4392. ResultType = Context.BoolTy;
  4393. // The type of a parameter passed 'by value'. In the GNU atomics, such
  4394. // arguments are actually passed as pointers.
  4395. QualType ByValType = ValType; // 'CP'
  4396. bool IsPassedByAddress = false;
  4397. if (!IsC11 && !IsN) {
  4398. ByValType = Ptr->getType();
  4399. IsPassedByAddress = true;
  4400. }
  4401. // The first argument's non-CV pointer type is used to deduce the type of
  4402. // subsequent arguments, except for:
  4403. // - weak flag (always converted to bool)
  4404. // - memory order (always converted to int)
  4405. // - scope (always converted to int)
  4406. for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
  4407. QualType Ty;
  4408. if (i < NumVals[Form] + 1) {
  4409. switch (i) {
  4410. case 0:
  4411. // The first argument is always a pointer. It has a fixed type.
  4412. // It is always dereferenced, a nullptr is undefined.
  4413. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4414. // Nothing else to do: we already know all we want about this pointer.
  4415. continue;
  4416. case 1:
  4417. // The second argument is the non-atomic operand. For arithmetic, this
  4418. // is always passed by value, and for a compare_exchange it is always
  4419. // passed by address. For the rest, GNU uses by-address and C11 uses
  4420. // by-value.
  4421. assert(Form != Load);
  4422. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  4423. Ty = ValType;
  4424. else if (Form == Copy || Form == Xchg) {
  4425. if (IsPassedByAddress)
  4426. // The value pointer is always dereferenced, a nullptr is undefined.
  4427. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4428. Ty = ByValType;
  4429. } else if (Form == Arithmetic)
  4430. Ty = Context.getPointerDiffType();
  4431. else {
  4432. Expr *ValArg = TheCall->getArg(i);
  4433. // The value pointer is always dereferenced, a nullptr is undefined.
  4434. CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
  4435. LangAS AS = LangAS::Default;
  4436. // Keep address space of non-atomic pointer type.
  4437. if (const PointerType *PtrTy =
  4438. ValArg->getType()->getAs<PointerType>()) {
  4439. AS = PtrTy->getPointeeType().getAddressSpace();
  4440. }
  4441. Ty = Context.getPointerType(
  4442. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  4443. }
  4444. break;
  4445. case 2:
  4446. // The third argument to compare_exchange / GNU exchange is the desired
  4447. // value, either by-value (for the C11 and *_n variant) or as a pointer.
  4448. if (IsPassedByAddress)
  4449. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4450. Ty = ByValType;
  4451. break;
  4452. case 3:
  4453. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  4454. Ty = Context.BoolTy;
  4455. break;
  4456. }
  4457. } else {
  4458. // The order(s) and scope are always converted to int.
  4459. Ty = Context.IntTy;
  4460. }
  4461. InitializedEntity Entity =
  4462. InitializedEntity::InitializeParameter(Context, Ty, false);
  4463. ExprResult Arg = TheCall->getArg(i);
  4464. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4465. if (Arg.isInvalid())
  4466. return true;
  4467. TheCall->setArg(i, Arg.get());
  4468. }
  4469. // Permute the arguments into a 'consistent' order.
  4470. SmallVector<Expr*, 5> SubExprs;
  4471. SubExprs.push_back(Ptr);
  4472. switch (Form) {
  4473. case Init:
  4474. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  4475. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4476. break;
  4477. case Load:
  4478. SubExprs.push_back(TheCall->getArg(1)); // Order
  4479. break;
  4480. case LoadCopy:
  4481. case Copy:
  4482. case Arithmetic:
  4483. case Xchg:
  4484. SubExprs.push_back(TheCall->getArg(2)); // Order
  4485. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4486. break;
  4487. case GNUXchg:
  4488. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  4489. SubExprs.push_back(TheCall->getArg(3)); // Order
  4490. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4491. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4492. break;
  4493. case C11CmpXchg:
  4494. SubExprs.push_back(TheCall->getArg(3)); // Order
  4495. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4496. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  4497. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4498. break;
  4499. case GNUCmpXchg:
  4500. SubExprs.push_back(TheCall->getArg(4)); // Order
  4501. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4502. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  4503. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4504. SubExprs.push_back(TheCall->getArg(3)); // Weak
  4505. break;
  4506. }
  4507. if (SubExprs.size() >= 2 && Form != Init) {
  4508. llvm::APSInt Result(32);
  4509. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  4510. !isValidOrderingForOp(Result.getSExtValue(), Op))
  4511. Diag(SubExprs[1]->getBeginLoc(),
  4512. diag::warn_atomic_op_has_invalid_memory_order)
  4513. << SubExprs[1]->getSourceRange();
  4514. }
  4515. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  4516. auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
  4517. llvm::APSInt Result(32);
  4518. if (Scope->isIntegerConstantExpr(Result, Context) &&
  4519. !ScopeModel->isValid(Result.getZExtValue())) {
  4520. Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
  4521. << Scope->getSourceRange();
  4522. }
  4523. SubExprs.push_back(Scope);
  4524. }
  4525. AtomicExpr *AE =
  4526. new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
  4527. ResultType, Op, TheCall->getRParenLoc());
  4528. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  4529. Op == AtomicExpr::AO__c11_atomic_store ||
  4530. Op == AtomicExpr::AO__opencl_atomic_load ||
  4531. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  4532. Context.AtomicUsesUnsupportedLibcall(AE))
  4533. Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
  4534. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  4535. Op == AtomicExpr::AO__opencl_atomic_load)
  4536. ? 0
  4537. : 1);
  4538. return AE;
  4539. }
  4540. /// checkBuiltinArgument - Given a call to a builtin function, perform
  4541. /// normal type-checking on the given argument, updating the call in
  4542. /// place. This is useful when a builtin function requires custom
  4543. /// type-checking for some of its arguments but not necessarily all of
  4544. /// them.
  4545. ///
  4546. /// Returns true on error.
  4547. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  4548. FunctionDecl *Fn = E->getDirectCallee();
  4549. assert(Fn && "builtin call without direct callee!");
  4550. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  4551. InitializedEntity Entity =
  4552. InitializedEntity::InitializeParameter(S.Context, Param);
  4553. ExprResult Arg = E->getArg(0);
  4554. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4555. if (Arg.isInvalid())
  4556. return true;
  4557. E->setArg(ArgIndex, Arg.get());
  4558. return false;
  4559. }
  4560. /// We have a call to a function like __sync_fetch_and_add, which is an
  4561. /// overloaded function based on the pointer type of its first argument.
  4562. /// The main BuildCallExpr routines have already promoted the types of
  4563. /// arguments because all of these calls are prototyped as void(...).
  4564. ///
  4565. /// This function goes through and does final semantic checking for these
  4566. /// builtins, as well as generating any warnings.
  4567. ExprResult
  4568. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  4569. CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
  4570. Expr *Callee = TheCall->getCallee();
  4571. DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
  4572. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4573. // Ensure that we have at least one argument to do type inference from.
  4574. if (TheCall->getNumArgs() < 1) {
  4575. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4576. << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
  4577. return ExprError();
  4578. }
  4579. // Inspect the first argument of the atomic builtin. This should always be
  4580. // a pointer type, whose element is an integral scalar or pointer type.
  4581. // Because it is a pointer type, we don't have to worry about any implicit
  4582. // casts here.
  4583. // FIXME: We don't allow floating point scalars as input.
  4584. Expr *FirstArg = TheCall->getArg(0);
  4585. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  4586. if (FirstArgResult.isInvalid())
  4587. return ExprError();
  4588. FirstArg = FirstArgResult.get();
  4589. TheCall->setArg(0, FirstArg);
  4590. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  4591. if (!pointerType) {
  4592. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4593. << FirstArg->getType() << FirstArg->getSourceRange();
  4594. return ExprError();
  4595. }
  4596. QualType ValType = pointerType->getPointeeType();
  4597. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4598. !ValType->isBlockPointerType()) {
  4599. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
  4600. << FirstArg->getType() << FirstArg->getSourceRange();
  4601. return ExprError();
  4602. }
  4603. if (ValType.isConstQualified()) {
  4604. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
  4605. << FirstArg->getType() << FirstArg->getSourceRange();
  4606. return ExprError();
  4607. }
  4608. switch (ValType.getObjCLifetime()) {
  4609. case Qualifiers::OCL_None:
  4610. case Qualifiers::OCL_ExplicitNone:
  4611. // okay
  4612. break;
  4613. case Qualifiers::OCL_Weak:
  4614. case Qualifiers::OCL_Strong:
  4615. case Qualifiers::OCL_Autoreleasing:
  4616. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4617. << ValType << FirstArg->getSourceRange();
  4618. return ExprError();
  4619. }
  4620. // Strip any qualifiers off ValType.
  4621. ValType = ValType.getUnqualifiedType();
  4622. // The majority of builtins return a value, but a few have special return
  4623. // types, so allow them to override appropriately below.
  4624. QualType ResultType = ValType;
  4625. // We need to figure out which concrete builtin this maps onto. For example,
  4626. // __sync_fetch_and_add with a 2 byte object turns into
  4627. // __sync_fetch_and_add_2.
  4628. #define BUILTIN_ROW(x) \
  4629. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  4630. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  4631. static const unsigned BuiltinIndices[][5] = {
  4632. BUILTIN_ROW(__sync_fetch_and_add),
  4633. BUILTIN_ROW(__sync_fetch_and_sub),
  4634. BUILTIN_ROW(__sync_fetch_and_or),
  4635. BUILTIN_ROW(__sync_fetch_and_and),
  4636. BUILTIN_ROW(__sync_fetch_and_xor),
  4637. BUILTIN_ROW(__sync_fetch_and_nand),
  4638. BUILTIN_ROW(__sync_add_and_fetch),
  4639. BUILTIN_ROW(__sync_sub_and_fetch),
  4640. BUILTIN_ROW(__sync_and_and_fetch),
  4641. BUILTIN_ROW(__sync_or_and_fetch),
  4642. BUILTIN_ROW(__sync_xor_and_fetch),
  4643. BUILTIN_ROW(__sync_nand_and_fetch),
  4644. BUILTIN_ROW(__sync_val_compare_and_swap),
  4645. BUILTIN_ROW(__sync_bool_compare_and_swap),
  4646. BUILTIN_ROW(__sync_lock_test_and_set),
  4647. BUILTIN_ROW(__sync_lock_release),
  4648. BUILTIN_ROW(__sync_swap)
  4649. };
  4650. #undef BUILTIN_ROW
  4651. // Determine the index of the size.
  4652. unsigned SizeIndex;
  4653. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  4654. case 1: SizeIndex = 0; break;
  4655. case 2: SizeIndex = 1; break;
  4656. case 4: SizeIndex = 2; break;
  4657. case 8: SizeIndex = 3; break;
  4658. case 16: SizeIndex = 4; break;
  4659. default:
  4660. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
  4661. << FirstArg->getType() << FirstArg->getSourceRange();
  4662. return ExprError();
  4663. }
  4664. // Each of these builtins has one pointer argument, followed by some number of
  4665. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  4666. // that we ignore. Find out which row of BuiltinIndices to read from as well
  4667. // as the number of fixed args.
  4668. unsigned BuiltinID = FDecl->getBuiltinID();
  4669. unsigned BuiltinIndex, NumFixed = 1;
  4670. bool WarnAboutSemanticsChange = false;
  4671. switch (BuiltinID) {
  4672. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  4673. case Builtin::BI__sync_fetch_and_add:
  4674. case Builtin::BI__sync_fetch_and_add_1:
  4675. case Builtin::BI__sync_fetch_and_add_2:
  4676. case Builtin::BI__sync_fetch_and_add_4:
  4677. case Builtin::BI__sync_fetch_and_add_8:
  4678. case Builtin::BI__sync_fetch_and_add_16:
  4679. BuiltinIndex = 0;
  4680. break;
  4681. case Builtin::BI__sync_fetch_and_sub:
  4682. case Builtin::BI__sync_fetch_and_sub_1:
  4683. case Builtin::BI__sync_fetch_and_sub_2:
  4684. case Builtin::BI__sync_fetch_and_sub_4:
  4685. case Builtin::BI__sync_fetch_and_sub_8:
  4686. case Builtin::BI__sync_fetch_and_sub_16:
  4687. BuiltinIndex = 1;
  4688. break;
  4689. case Builtin::BI__sync_fetch_and_or:
  4690. case Builtin::BI__sync_fetch_and_or_1:
  4691. case Builtin::BI__sync_fetch_and_or_2:
  4692. case Builtin::BI__sync_fetch_and_or_4:
  4693. case Builtin::BI__sync_fetch_and_or_8:
  4694. case Builtin::BI__sync_fetch_and_or_16:
  4695. BuiltinIndex = 2;
  4696. break;
  4697. case Builtin::BI__sync_fetch_and_and:
  4698. case Builtin::BI__sync_fetch_and_and_1:
  4699. case Builtin::BI__sync_fetch_and_and_2:
  4700. case Builtin::BI__sync_fetch_and_and_4:
  4701. case Builtin::BI__sync_fetch_and_and_8:
  4702. case Builtin::BI__sync_fetch_and_and_16:
  4703. BuiltinIndex = 3;
  4704. break;
  4705. case Builtin::BI__sync_fetch_and_xor:
  4706. case Builtin::BI__sync_fetch_and_xor_1:
  4707. case Builtin::BI__sync_fetch_and_xor_2:
  4708. case Builtin::BI__sync_fetch_and_xor_4:
  4709. case Builtin::BI__sync_fetch_and_xor_8:
  4710. case Builtin::BI__sync_fetch_and_xor_16:
  4711. BuiltinIndex = 4;
  4712. break;
  4713. case Builtin::BI__sync_fetch_and_nand:
  4714. case Builtin::BI__sync_fetch_and_nand_1:
  4715. case Builtin::BI__sync_fetch_and_nand_2:
  4716. case Builtin::BI__sync_fetch_and_nand_4:
  4717. case Builtin::BI__sync_fetch_and_nand_8:
  4718. case Builtin::BI__sync_fetch_and_nand_16:
  4719. BuiltinIndex = 5;
  4720. WarnAboutSemanticsChange = true;
  4721. break;
  4722. case Builtin::BI__sync_add_and_fetch:
  4723. case Builtin::BI__sync_add_and_fetch_1:
  4724. case Builtin::BI__sync_add_and_fetch_2:
  4725. case Builtin::BI__sync_add_and_fetch_4:
  4726. case Builtin::BI__sync_add_and_fetch_8:
  4727. case Builtin::BI__sync_add_and_fetch_16:
  4728. BuiltinIndex = 6;
  4729. break;
  4730. case Builtin::BI__sync_sub_and_fetch:
  4731. case Builtin::BI__sync_sub_and_fetch_1:
  4732. case Builtin::BI__sync_sub_and_fetch_2:
  4733. case Builtin::BI__sync_sub_and_fetch_4:
  4734. case Builtin::BI__sync_sub_and_fetch_8:
  4735. case Builtin::BI__sync_sub_and_fetch_16:
  4736. BuiltinIndex = 7;
  4737. break;
  4738. case Builtin::BI__sync_and_and_fetch:
  4739. case Builtin::BI__sync_and_and_fetch_1:
  4740. case Builtin::BI__sync_and_and_fetch_2:
  4741. case Builtin::BI__sync_and_and_fetch_4:
  4742. case Builtin::BI__sync_and_and_fetch_8:
  4743. case Builtin::BI__sync_and_and_fetch_16:
  4744. BuiltinIndex = 8;
  4745. break;
  4746. case Builtin::BI__sync_or_and_fetch:
  4747. case Builtin::BI__sync_or_and_fetch_1:
  4748. case Builtin::BI__sync_or_and_fetch_2:
  4749. case Builtin::BI__sync_or_and_fetch_4:
  4750. case Builtin::BI__sync_or_and_fetch_8:
  4751. case Builtin::BI__sync_or_and_fetch_16:
  4752. BuiltinIndex = 9;
  4753. break;
  4754. case Builtin::BI__sync_xor_and_fetch:
  4755. case Builtin::BI__sync_xor_and_fetch_1:
  4756. case Builtin::BI__sync_xor_and_fetch_2:
  4757. case Builtin::BI__sync_xor_and_fetch_4:
  4758. case Builtin::BI__sync_xor_and_fetch_8:
  4759. case Builtin::BI__sync_xor_and_fetch_16:
  4760. BuiltinIndex = 10;
  4761. break;
  4762. case Builtin::BI__sync_nand_and_fetch:
  4763. case Builtin::BI__sync_nand_and_fetch_1:
  4764. case Builtin::BI__sync_nand_and_fetch_2:
  4765. case Builtin::BI__sync_nand_and_fetch_4:
  4766. case Builtin::BI__sync_nand_and_fetch_8:
  4767. case Builtin::BI__sync_nand_and_fetch_16:
  4768. BuiltinIndex = 11;
  4769. WarnAboutSemanticsChange = true;
  4770. break;
  4771. case Builtin::BI__sync_val_compare_and_swap:
  4772. case Builtin::BI__sync_val_compare_and_swap_1:
  4773. case Builtin::BI__sync_val_compare_and_swap_2:
  4774. case Builtin::BI__sync_val_compare_and_swap_4:
  4775. case Builtin::BI__sync_val_compare_and_swap_8:
  4776. case Builtin::BI__sync_val_compare_and_swap_16:
  4777. BuiltinIndex = 12;
  4778. NumFixed = 2;
  4779. break;
  4780. case Builtin::BI__sync_bool_compare_and_swap:
  4781. case Builtin::BI__sync_bool_compare_and_swap_1:
  4782. case Builtin::BI__sync_bool_compare_and_swap_2:
  4783. case Builtin::BI__sync_bool_compare_and_swap_4:
  4784. case Builtin::BI__sync_bool_compare_and_swap_8:
  4785. case Builtin::BI__sync_bool_compare_and_swap_16:
  4786. BuiltinIndex = 13;
  4787. NumFixed = 2;
  4788. ResultType = Context.BoolTy;
  4789. break;
  4790. case Builtin::BI__sync_lock_test_and_set:
  4791. case Builtin::BI__sync_lock_test_and_set_1:
  4792. case Builtin::BI__sync_lock_test_and_set_2:
  4793. case Builtin::BI__sync_lock_test_and_set_4:
  4794. case Builtin::BI__sync_lock_test_and_set_8:
  4795. case Builtin::BI__sync_lock_test_and_set_16:
  4796. BuiltinIndex = 14;
  4797. break;
  4798. case Builtin::BI__sync_lock_release:
  4799. case Builtin::BI__sync_lock_release_1:
  4800. case Builtin::BI__sync_lock_release_2:
  4801. case Builtin::BI__sync_lock_release_4:
  4802. case Builtin::BI__sync_lock_release_8:
  4803. case Builtin::BI__sync_lock_release_16:
  4804. BuiltinIndex = 15;
  4805. NumFixed = 0;
  4806. ResultType = Context.VoidTy;
  4807. break;
  4808. case Builtin::BI__sync_swap:
  4809. case Builtin::BI__sync_swap_1:
  4810. case Builtin::BI__sync_swap_2:
  4811. case Builtin::BI__sync_swap_4:
  4812. case Builtin::BI__sync_swap_8:
  4813. case Builtin::BI__sync_swap_16:
  4814. BuiltinIndex = 16;
  4815. break;
  4816. }
  4817. // Now that we know how many fixed arguments we expect, first check that we
  4818. // have at least that many.
  4819. if (TheCall->getNumArgs() < 1+NumFixed) {
  4820. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4821. << 0 << 1 + NumFixed << TheCall->getNumArgs()
  4822. << Callee->getSourceRange();
  4823. return ExprError();
  4824. }
  4825. Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
  4826. << Callee->getSourceRange();
  4827. if (WarnAboutSemanticsChange) {
  4828. Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
  4829. << Callee->getSourceRange();
  4830. }
  4831. // Get the decl for the concrete builtin from this, we can tell what the
  4832. // concrete integer type we should convert to is.
  4833. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  4834. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  4835. FunctionDecl *NewBuiltinDecl;
  4836. if (NewBuiltinID == BuiltinID)
  4837. NewBuiltinDecl = FDecl;
  4838. else {
  4839. // Perform builtin lookup to avoid redeclaring it.
  4840. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  4841. LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
  4842. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  4843. assert(Res.getFoundDecl());
  4844. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  4845. if (!NewBuiltinDecl)
  4846. return ExprError();
  4847. }
  4848. // The first argument --- the pointer --- has a fixed type; we
  4849. // deduce the types of the rest of the arguments accordingly. Walk
  4850. // the remaining arguments, converting them to the deduced value type.
  4851. for (unsigned i = 0; i != NumFixed; ++i) {
  4852. ExprResult Arg = TheCall->getArg(i+1);
  4853. // GCC does an implicit conversion to the pointer or integer ValType. This
  4854. // can fail in some cases (1i -> int**), check for this error case now.
  4855. // Initialize the argument.
  4856. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  4857. ValType, /*consume*/ false);
  4858. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4859. if (Arg.isInvalid())
  4860. return ExprError();
  4861. // Okay, we have something that *can* be converted to the right type. Check
  4862. // to see if there is a potentially weird extension going on here. This can
  4863. // happen when you do an atomic operation on something like an char* and
  4864. // pass in 42. The 42 gets converted to char. This is even more strange
  4865. // for things like 45.123 -> char, etc.
  4866. // FIXME: Do this check.
  4867. TheCall->setArg(i+1, Arg.get());
  4868. }
  4869. // Create a new DeclRefExpr to refer to the new decl.
  4870. DeclRefExpr *NewDRE = DeclRefExpr::Create(
  4871. Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
  4872. /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
  4873. DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
  4874. // Set the callee in the CallExpr.
  4875. // FIXME: This loses syntactic information.
  4876. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  4877. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  4878. CK_BuiltinFnToFnPtr);
  4879. TheCall->setCallee(PromotedCall.get());
  4880. // Change the result type of the call to match the original value type. This
  4881. // is arbitrary, but the codegen for these builtins ins design to handle it
  4882. // gracefully.
  4883. TheCall->setType(ResultType);
  4884. return TheCallResult;
  4885. }
  4886. /// SemaBuiltinNontemporalOverloaded - We have a call to
  4887. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  4888. /// overloaded function based on the pointer type of its last argument.
  4889. ///
  4890. /// This function goes through and does final semantic checking for these
  4891. /// builtins.
  4892. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  4893. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  4894. DeclRefExpr *DRE =
  4895. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4896. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4897. unsigned BuiltinID = FDecl->getBuiltinID();
  4898. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  4899. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  4900. "Unexpected nontemporal load/store builtin!");
  4901. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  4902. unsigned numArgs = isStore ? 2 : 1;
  4903. // Ensure that we have the proper number of arguments.
  4904. if (checkArgCount(*this, TheCall, numArgs))
  4905. return ExprError();
  4906. // Inspect the last argument of the nontemporal builtin. This should always
  4907. // be a pointer type, from which we imply the type of the memory access.
  4908. // Because it is a pointer type, we don't have to worry about any implicit
  4909. // casts here.
  4910. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  4911. ExprResult PointerArgResult =
  4912. DefaultFunctionArrayLvalueConversion(PointerArg);
  4913. if (PointerArgResult.isInvalid())
  4914. return ExprError();
  4915. PointerArg = PointerArgResult.get();
  4916. TheCall->setArg(numArgs - 1, PointerArg);
  4917. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  4918. if (!pointerType) {
  4919. Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
  4920. << PointerArg->getType() << PointerArg->getSourceRange();
  4921. return ExprError();
  4922. }
  4923. QualType ValType = pointerType->getPointeeType();
  4924. // Strip any qualifiers off ValType.
  4925. ValType = ValType.getUnqualifiedType();
  4926. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4927. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  4928. !ValType->isVectorType()) {
  4929. Diag(DRE->getBeginLoc(),
  4930. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  4931. << PointerArg->getType() << PointerArg->getSourceRange();
  4932. return ExprError();
  4933. }
  4934. if (!isStore) {
  4935. TheCall->setType(ValType);
  4936. return TheCallResult;
  4937. }
  4938. ExprResult ValArg = TheCall->getArg(0);
  4939. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4940. Context, ValType, /*consume*/ false);
  4941. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  4942. if (ValArg.isInvalid())
  4943. return ExprError();
  4944. TheCall->setArg(0, ValArg.get());
  4945. TheCall->setType(Context.VoidTy);
  4946. return TheCallResult;
  4947. }
  4948. /// CheckObjCString - Checks that the argument to the builtin
  4949. /// CFString constructor is correct
  4950. /// Note: It might also make sense to do the UTF-16 conversion here (would
  4951. /// simplify the backend).
  4952. bool Sema::CheckObjCString(Expr *Arg) {
  4953. Arg = Arg->IgnoreParenCasts();
  4954. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  4955. if (!Literal || !Literal->isAscii()) {
  4956. Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
  4957. << Arg->getSourceRange();
  4958. return true;
  4959. }
  4960. if (Literal->containsNonAsciiOrNull()) {
  4961. StringRef String = Literal->getString();
  4962. unsigned NumBytes = String.size();
  4963. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  4964. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  4965. llvm::UTF16 *ToPtr = &ToBuf[0];
  4966. llvm::ConversionResult Result =
  4967. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  4968. ToPtr + NumBytes, llvm::strictConversion);
  4969. // Check for conversion failure.
  4970. if (Result != llvm::conversionOK)
  4971. Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
  4972. << Arg->getSourceRange();
  4973. }
  4974. return false;
  4975. }
  4976. /// CheckObjCString - Checks that the format string argument to the os_log()
  4977. /// and os_trace() functions is correct, and converts it to const char *.
  4978. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  4979. Arg = Arg->IgnoreParenCasts();
  4980. auto *Literal = dyn_cast<StringLiteral>(Arg);
  4981. if (!Literal) {
  4982. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  4983. Literal = ObjcLiteral->getString();
  4984. }
  4985. }
  4986. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  4987. return ExprError(
  4988. Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
  4989. << Arg->getSourceRange());
  4990. }
  4991. ExprResult Result(Literal);
  4992. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  4993. InitializedEntity Entity =
  4994. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  4995. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  4996. return Result;
  4997. }
  4998. /// Check that the user is calling the appropriate va_start builtin for the
  4999. /// target and calling convention.
  5000. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  5001. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  5002. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  5003. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  5004. bool IsWindows = TT.isOSWindows();
  5005. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  5006. if (IsX64 || IsAArch64) {
  5007. CallingConv CC = CC_C;
  5008. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  5009. CC = FD->getType()->getAs<FunctionType>()->getCallConv();
  5010. if (IsMSVAStart) {
  5011. // Don't allow this in System V ABI functions.
  5012. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  5013. return S.Diag(Fn->getBeginLoc(),
  5014. diag::err_ms_va_start_used_in_sysv_function);
  5015. } else {
  5016. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  5017. // On x64 Windows, don't allow this in System V ABI functions.
  5018. // (Yes, that means there's no corresponding way to support variadic
  5019. // System V ABI functions on Windows.)
  5020. if ((IsWindows && CC == CC_X86_64SysV) ||
  5021. (!IsWindows && CC == CC_Win64))
  5022. return S.Diag(Fn->getBeginLoc(),
  5023. diag::err_va_start_used_in_wrong_abi_function)
  5024. << !IsWindows;
  5025. }
  5026. return false;
  5027. }
  5028. if (IsMSVAStart)
  5029. return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
  5030. return false;
  5031. }
  5032. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  5033. ParmVarDecl **LastParam = nullptr) {
  5034. // Determine whether the current function, block, or obj-c method is variadic
  5035. // and get its parameter list.
  5036. bool IsVariadic = false;
  5037. ArrayRef<ParmVarDecl *> Params;
  5038. DeclContext *Caller = S.CurContext;
  5039. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  5040. IsVariadic = Block->isVariadic();
  5041. Params = Block->parameters();
  5042. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  5043. IsVariadic = FD->isVariadic();
  5044. Params = FD->parameters();
  5045. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  5046. IsVariadic = MD->isVariadic();
  5047. // FIXME: This isn't correct for methods (results in bogus warning).
  5048. Params = MD->parameters();
  5049. } else if (isa<CapturedDecl>(Caller)) {
  5050. // We don't support va_start in a CapturedDecl.
  5051. S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
  5052. return true;
  5053. } else {
  5054. // This must be some other declcontext that parses exprs.
  5055. S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
  5056. return true;
  5057. }
  5058. if (!IsVariadic) {
  5059. S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
  5060. return true;
  5061. }
  5062. if (LastParam)
  5063. *LastParam = Params.empty() ? nullptr : Params.back();
  5064. return false;
  5065. }
  5066. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  5067. /// for validity. Emit an error and return true on failure; return false
  5068. /// on success.
  5069. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  5070. Expr *Fn = TheCall->getCallee();
  5071. if (checkVAStartABI(*this, BuiltinID, Fn))
  5072. return true;
  5073. if (TheCall->getNumArgs() > 2) {
  5074. Diag(TheCall->getArg(2)->getBeginLoc(),
  5075. diag::err_typecheck_call_too_many_args)
  5076. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5077. << Fn->getSourceRange()
  5078. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5079. (*(TheCall->arg_end() - 1))->getEndLoc());
  5080. return true;
  5081. }
  5082. if (TheCall->getNumArgs() < 2) {
  5083. return Diag(TheCall->getEndLoc(),
  5084. diag::err_typecheck_call_too_few_args_at_least)
  5085. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  5086. }
  5087. // Type-check the first argument normally.
  5088. if (checkBuiltinArgument(*this, TheCall, 0))
  5089. return true;
  5090. // Check that the current function is variadic, and get its last parameter.
  5091. ParmVarDecl *LastParam;
  5092. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  5093. return true;
  5094. // Verify that the second argument to the builtin is the last argument of the
  5095. // current function or method.
  5096. bool SecondArgIsLastNamedArgument = false;
  5097. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  5098. // These are valid if SecondArgIsLastNamedArgument is false after the next
  5099. // block.
  5100. QualType Type;
  5101. SourceLocation ParamLoc;
  5102. bool IsCRegister = false;
  5103. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  5104. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  5105. SecondArgIsLastNamedArgument = PV == LastParam;
  5106. Type = PV->getType();
  5107. ParamLoc = PV->getLocation();
  5108. IsCRegister =
  5109. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  5110. }
  5111. }
  5112. if (!SecondArgIsLastNamedArgument)
  5113. Diag(TheCall->getArg(1)->getBeginLoc(),
  5114. diag::warn_second_arg_of_va_start_not_last_named_param);
  5115. else if (IsCRegister || Type->isReferenceType() ||
  5116. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  5117. // Promotable integers are UB, but enumerations need a bit of
  5118. // extra checking to see what their promotable type actually is.
  5119. if (!Type->isPromotableIntegerType())
  5120. return false;
  5121. if (!Type->isEnumeralType())
  5122. return true;
  5123. const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
  5124. return !(ED &&
  5125. Context.typesAreCompatible(ED->getPromotionType(), Type));
  5126. }()) {
  5127. unsigned Reason = 0;
  5128. if (Type->isReferenceType()) Reason = 1;
  5129. else if (IsCRegister) Reason = 2;
  5130. Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
  5131. Diag(ParamLoc, diag::note_parameter_type) << Type;
  5132. }
  5133. TheCall->setType(Context.VoidTy);
  5134. return false;
  5135. }
  5136. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  5137. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  5138. // const char *named_addr);
  5139. Expr *Func = Call->getCallee();
  5140. if (Call->getNumArgs() < 3)
  5141. return Diag(Call->getEndLoc(),
  5142. diag::err_typecheck_call_too_few_args_at_least)
  5143. << 0 /*function call*/ << 3 << Call->getNumArgs();
  5144. // Type-check the first argument normally.
  5145. if (checkBuiltinArgument(*this, Call, 0))
  5146. return true;
  5147. // Check that the current function is variadic.
  5148. if (checkVAStartIsInVariadicFunction(*this, Func))
  5149. return true;
  5150. // __va_start on Windows does not validate the parameter qualifiers
  5151. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  5152. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  5153. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  5154. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  5155. const QualType &ConstCharPtrTy =
  5156. Context.getPointerType(Context.CharTy.withConst());
  5157. if (!Arg1Ty->isPointerType() ||
  5158. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  5159. Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5160. << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
  5161. << 0 /* qualifier difference */
  5162. << 3 /* parameter mismatch */
  5163. << 2 << Arg1->getType() << ConstCharPtrTy;
  5164. const QualType SizeTy = Context.getSizeType();
  5165. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  5166. Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5167. << Arg2->getType() << SizeTy << 1 /* different class */
  5168. << 0 /* qualifier difference */
  5169. << 3 /* parameter mismatch */
  5170. << 3 << Arg2->getType() << SizeTy;
  5171. return false;
  5172. }
  5173. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  5174. /// friends. This is declared to take (...), so we have to check everything.
  5175. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  5176. if (TheCall->getNumArgs() < 2)
  5177. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5178. << 0 << 2 << TheCall->getNumArgs() /*function call*/;
  5179. if (TheCall->getNumArgs() > 2)
  5180. return Diag(TheCall->getArg(2)->getBeginLoc(),
  5181. diag::err_typecheck_call_too_many_args)
  5182. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5183. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5184. (*(TheCall->arg_end() - 1))->getEndLoc());
  5185. ExprResult OrigArg0 = TheCall->getArg(0);
  5186. ExprResult OrigArg1 = TheCall->getArg(1);
  5187. // Do standard promotions between the two arguments, returning their common
  5188. // type.
  5189. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  5190. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  5191. return true;
  5192. // Make sure any conversions are pushed back into the call; this is
  5193. // type safe since unordered compare builtins are declared as "_Bool
  5194. // foo(...)".
  5195. TheCall->setArg(0, OrigArg0.get());
  5196. TheCall->setArg(1, OrigArg1.get());
  5197. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  5198. return false;
  5199. // If the common type isn't a real floating type, then the arguments were
  5200. // invalid for this operation.
  5201. if (Res.isNull() || !Res->isRealFloatingType())
  5202. return Diag(OrigArg0.get()->getBeginLoc(),
  5203. diag::err_typecheck_call_invalid_ordered_compare)
  5204. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  5205. << SourceRange(OrigArg0.get()->getBeginLoc(),
  5206. OrigArg1.get()->getEndLoc());
  5207. return false;
  5208. }
  5209. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  5210. /// __builtin_isnan and friends. This is declared to take (...), so we have
  5211. /// to check everything. We expect the last argument to be a floating point
  5212. /// value.
  5213. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  5214. if (TheCall->getNumArgs() < NumArgs)
  5215. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5216. << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
  5217. if (TheCall->getNumArgs() > NumArgs)
  5218. return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
  5219. diag::err_typecheck_call_too_many_args)
  5220. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  5221. << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
  5222. (*(TheCall->arg_end() - 1))->getEndLoc());
  5223. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  5224. if (OrigArg->isTypeDependent())
  5225. return false;
  5226. // This operation requires a non-_Complex floating-point number.
  5227. if (!OrigArg->getType()->isRealFloatingType())
  5228. return Diag(OrigArg->getBeginLoc(),
  5229. diag::err_typecheck_call_invalid_unary_fp)
  5230. << OrigArg->getType() << OrigArg->getSourceRange();
  5231. // If this is an implicit conversion from float -> float, double, or
  5232. // long double, remove it.
  5233. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  5234. // Only remove standard FloatCasts, leaving other casts inplace
  5235. if (Cast->getCastKind() == CK_FloatingCast) {
  5236. Expr *CastArg = Cast->getSubExpr();
  5237. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  5238. assert(
  5239. (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  5240. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
  5241. Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
  5242. "promotion from float to either float, double, or long double is "
  5243. "the only expected cast here");
  5244. Cast->setSubExpr(nullptr);
  5245. TheCall->setArg(NumArgs-1, CastArg);
  5246. }
  5247. }
  5248. }
  5249. return false;
  5250. }
  5251. // Customized Sema Checking for VSX builtins that have the following signature:
  5252. // vector [...] builtinName(vector [...], vector [...], const int);
  5253. // Which takes the same type of vectors (any legal vector type) for the first
  5254. // two arguments and takes compile time constant for the third argument.
  5255. // Example builtins are :
  5256. // vector double vec_xxpermdi(vector double, vector double, int);
  5257. // vector short vec_xxsldwi(vector short, vector short, int);
  5258. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  5259. unsigned ExpectedNumArgs = 3;
  5260. if (TheCall->getNumArgs() < ExpectedNumArgs)
  5261. return Diag(TheCall->getEndLoc(),
  5262. diag::err_typecheck_call_too_few_args_at_least)
  5263. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5264. << TheCall->getSourceRange();
  5265. if (TheCall->getNumArgs() > ExpectedNumArgs)
  5266. return Diag(TheCall->getEndLoc(),
  5267. diag::err_typecheck_call_too_many_args_at_most)
  5268. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5269. << TheCall->getSourceRange();
  5270. // Check the third argument is a compile time constant
  5271. llvm::APSInt Value;
  5272. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  5273. return Diag(TheCall->getBeginLoc(),
  5274. diag::err_vsx_builtin_nonconstant_argument)
  5275. << 3 /* argument index */ << TheCall->getDirectCallee()
  5276. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5277. TheCall->getArg(2)->getEndLoc());
  5278. QualType Arg1Ty = TheCall->getArg(0)->getType();
  5279. QualType Arg2Ty = TheCall->getArg(1)->getType();
  5280. // Check the type of argument 1 and argument 2 are vectors.
  5281. SourceLocation BuiltinLoc = TheCall->getBeginLoc();
  5282. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  5283. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  5284. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  5285. << TheCall->getDirectCallee()
  5286. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5287. TheCall->getArg(1)->getEndLoc());
  5288. }
  5289. // Check the first two arguments are the same type.
  5290. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  5291. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  5292. << TheCall->getDirectCallee()
  5293. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5294. TheCall->getArg(1)->getEndLoc());
  5295. }
  5296. // When default clang type checking is turned off and the customized type
  5297. // checking is used, the returning type of the function must be explicitly
  5298. // set. Otherwise it is _Bool by default.
  5299. TheCall->setType(Arg1Ty);
  5300. return false;
  5301. }
  5302. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  5303. // This is declared to take (...), so we have to check everything.
  5304. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  5305. if (TheCall->getNumArgs() < 2)
  5306. return ExprError(Diag(TheCall->getEndLoc(),
  5307. diag::err_typecheck_call_too_few_args_at_least)
  5308. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5309. << TheCall->getSourceRange());
  5310. // Determine which of the following types of shufflevector we're checking:
  5311. // 1) unary, vector mask: (lhs, mask)
  5312. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  5313. QualType resType = TheCall->getArg(0)->getType();
  5314. unsigned numElements = 0;
  5315. if (!TheCall->getArg(0)->isTypeDependent() &&
  5316. !TheCall->getArg(1)->isTypeDependent()) {
  5317. QualType LHSType = TheCall->getArg(0)->getType();
  5318. QualType RHSType = TheCall->getArg(1)->getType();
  5319. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  5320. return ExprError(
  5321. Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
  5322. << TheCall->getDirectCallee()
  5323. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5324. TheCall->getArg(1)->getEndLoc()));
  5325. numElements = LHSType->getAs<VectorType>()->getNumElements();
  5326. unsigned numResElements = TheCall->getNumArgs() - 2;
  5327. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  5328. // with mask. If so, verify that RHS is an integer vector type with the
  5329. // same number of elts as lhs.
  5330. if (TheCall->getNumArgs() == 2) {
  5331. if (!RHSType->hasIntegerRepresentation() ||
  5332. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  5333. return ExprError(Diag(TheCall->getBeginLoc(),
  5334. diag::err_vec_builtin_incompatible_vector)
  5335. << TheCall->getDirectCallee()
  5336. << SourceRange(TheCall->getArg(1)->getBeginLoc(),
  5337. TheCall->getArg(1)->getEndLoc()));
  5338. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  5339. return ExprError(Diag(TheCall->getBeginLoc(),
  5340. diag::err_vec_builtin_incompatible_vector)
  5341. << TheCall->getDirectCallee()
  5342. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5343. TheCall->getArg(1)->getEndLoc()));
  5344. } else if (numElements != numResElements) {
  5345. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  5346. resType = Context.getVectorType(eltType, numResElements,
  5347. VectorType::GenericVector);
  5348. }
  5349. }
  5350. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  5351. if (TheCall->getArg(i)->isTypeDependent() ||
  5352. TheCall->getArg(i)->isValueDependent())
  5353. continue;
  5354. llvm::APSInt Result(32);
  5355. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  5356. return ExprError(Diag(TheCall->getBeginLoc(),
  5357. diag::err_shufflevector_nonconstant_argument)
  5358. << TheCall->getArg(i)->getSourceRange());
  5359. // Allow -1 which will be translated to undef in the IR.
  5360. if (Result.isSigned() && Result.isAllOnesValue())
  5361. continue;
  5362. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  5363. return ExprError(Diag(TheCall->getBeginLoc(),
  5364. diag::err_shufflevector_argument_too_large)
  5365. << TheCall->getArg(i)->getSourceRange());
  5366. }
  5367. SmallVector<Expr*, 32> exprs;
  5368. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  5369. exprs.push_back(TheCall->getArg(i));
  5370. TheCall->setArg(i, nullptr);
  5371. }
  5372. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  5373. TheCall->getCallee()->getBeginLoc(),
  5374. TheCall->getRParenLoc());
  5375. }
  5376. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  5377. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  5378. SourceLocation BuiltinLoc,
  5379. SourceLocation RParenLoc) {
  5380. ExprValueKind VK = VK_RValue;
  5381. ExprObjectKind OK = OK_Ordinary;
  5382. QualType DstTy = TInfo->getType();
  5383. QualType SrcTy = E->getType();
  5384. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  5385. return ExprError(Diag(BuiltinLoc,
  5386. diag::err_convertvector_non_vector)
  5387. << E->getSourceRange());
  5388. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  5389. return ExprError(Diag(BuiltinLoc,
  5390. diag::err_convertvector_non_vector_type));
  5391. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  5392. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  5393. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  5394. if (SrcElts != DstElts)
  5395. return ExprError(Diag(BuiltinLoc,
  5396. diag::err_convertvector_incompatible_vector)
  5397. << E->getSourceRange());
  5398. }
  5399. return new (Context)
  5400. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5401. }
  5402. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  5403. // This is declared to take (const void*, ...) and can take two
  5404. // optional constant int args.
  5405. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  5406. unsigned NumArgs = TheCall->getNumArgs();
  5407. if (NumArgs > 3)
  5408. return Diag(TheCall->getEndLoc(),
  5409. diag::err_typecheck_call_too_many_args_at_most)
  5410. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5411. // Argument 0 is checked for us and the remaining arguments must be
  5412. // constant integers.
  5413. for (unsigned i = 1; i != NumArgs; ++i)
  5414. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  5415. return true;
  5416. return false;
  5417. }
  5418. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  5419. // __assume does not evaluate its arguments, and should warn if its argument
  5420. // has side effects.
  5421. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  5422. Expr *Arg = TheCall->getArg(0);
  5423. if (Arg->isInstantiationDependent()) return false;
  5424. if (Arg->HasSideEffects(Context))
  5425. Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
  5426. << Arg->getSourceRange()
  5427. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  5428. return false;
  5429. }
  5430. /// Handle __builtin_alloca_with_align. This is declared
  5431. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  5432. /// than 8.
  5433. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  5434. // The alignment must be a constant integer.
  5435. Expr *Arg = TheCall->getArg(1);
  5436. // We can't check the value of a dependent argument.
  5437. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5438. if (const auto *UE =
  5439. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  5440. if (UE->getKind() == UETT_AlignOf ||
  5441. UE->getKind() == UETT_PreferredAlignOf)
  5442. Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
  5443. << Arg->getSourceRange();
  5444. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  5445. if (!Result.isPowerOf2())
  5446. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5447. << Arg->getSourceRange();
  5448. if (Result < Context.getCharWidth())
  5449. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
  5450. << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
  5451. if (Result > std::numeric_limits<int32_t>::max())
  5452. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
  5453. << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
  5454. }
  5455. return false;
  5456. }
  5457. /// Handle __builtin_assume_aligned. This is declared
  5458. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  5459. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  5460. unsigned NumArgs = TheCall->getNumArgs();
  5461. if (NumArgs > 3)
  5462. return Diag(TheCall->getEndLoc(),
  5463. diag::err_typecheck_call_too_many_args_at_most)
  5464. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5465. // The alignment must be a constant integer.
  5466. Expr *Arg = TheCall->getArg(1);
  5467. // We can't check the value of a dependent argument.
  5468. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5469. llvm::APSInt Result;
  5470. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5471. return true;
  5472. if (!Result.isPowerOf2())
  5473. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5474. << Arg->getSourceRange();
  5475. }
  5476. if (NumArgs > 2) {
  5477. ExprResult Arg(TheCall->getArg(2));
  5478. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  5479. Context.getSizeType(), false);
  5480. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5481. if (Arg.isInvalid()) return true;
  5482. TheCall->setArg(2, Arg.get());
  5483. }
  5484. return false;
  5485. }
  5486. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  5487. unsigned BuiltinID =
  5488. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  5489. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  5490. unsigned NumArgs = TheCall->getNumArgs();
  5491. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  5492. if (NumArgs < NumRequiredArgs) {
  5493. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5494. << 0 /* function call */ << NumRequiredArgs << NumArgs
  5495. << TheCall->getSourceRange();
  5496. }
  5497. if (NumArgs >= NumRequiredArgs + 0x100) {
  5498. return Diag(TheCall->getEndLoc(),
  5499. diag::err_typecheck_call_too_many_args_at_most)
  5500. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  5501. << TheCall->getSourceRange();
  5502. }
  5503. unsigned i = 0;
  5504. // For formatting call, check buffer arg.
  5505. if (!IsSizeCall) {
  5506. ExprResult Arg(TheCall->getArg(i));
  5507. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5508. Context, Context.VoidPtrTy, false);
  5509. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5510. if (Arg.isInvalid())
  5511. return true;
  5512. TheCall->setArg(i, Arg.get());
  5513. i++;
  5514. }
  5515. // Check string literal arg.
  5516. unsigned FormatIdx = i;
  5517. {
  5518. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  5519. if (Arg.isInvalid())
  5520. return true;
  5521. TheCall->setArg(i, Arg.get());
  5522. i++;
  5523. }
  5524. // Make sure variadic args are scalar.
  5525. unsigned FirstDataArg = i;
  5526. while (i < NumArgs) {
  5527. ExprResult Arg = DefaultVariadicArgumentPromotion(
  5528. TheCall->getArg(i), VariadicFunction, nullptr);
  5529. if (Arg.isInvalid())
  5530. return true;
  5531. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  5532. if (ArgSize.getQuantity() >= 0x100) {
  5533. return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
  5534. << i << (int)ArgSize.getQuantity() << 0xff
  5535. << TheCall->getSourceRange();
  5536. }
  5537. TheCall->setArg(i, Arg.get());
  5538. i++;
  5539. }
  5540. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  5541. // call to avoid duplicate diagnostics.
  5542. if (!IsSizeCall) {
  5543. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  5544. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  5545. bool Success = CheckFormatArguments(
  5546. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  5547. VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
  5548. CheckedVarArgs);
  5549. if (!Success)
  5550. return true;
  5551. }
  5552. if (IsSizeCall) {
  5553. TheCall->setType(Context.getSizeType());
  5554. } else {
  5555. TheCall->setType(Context.VoidPtrTy);
  5556. }
  5557. return false;
  5558. }
  5559. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  5560. /// TheCall is a constant expression.
  5561. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  5562. llvm::APSInt &Result) {
  5563. Expr *Arg = TheCall->getArg(ArgNum);
  5564. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5565. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  5566. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  5567. if (!Arg->isIntegerConstantExpr(Result, Context))
  5568. return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
  5569. << FDecl->getDeclName() << Arg->getSourceRange();
  5570. return false;
  5571. }
  5572. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  5573. /// TheCall is a constant expression in the range [Low, High].
  5574. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  5575. int Low, int High, bool RangeIsError) {
  5576. llvm::APSInt Result;
  5577. // We can't check the value of a dependent argument.
  5578. Expr *Arg = TheCall->getArg(ArgNum);
  5579. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5580. return false;
  5581. // Check constant-ness first.
  5582. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5583. return true;
  5584. if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
  5585. if (RangeIsError)
  5586. return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
  5587. << Result.toString(10) << Low << High << Arg->getSourceRange();
  5588. else
  5589. // Defer the warning until we know if the code will be emitted so that
  5590. // dead code can ignore this.
  5591. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  5592. PDiag(diag::warn_argument_invalid_range)
  5593. << Result.toString(10) << Low << High
  5594. << Arg->getSourceRange());
  5595. }
  5596. return false;
  5597. }
  5598. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  5599. /// TheCall is a constant expression is a multiple of Num..
  5600. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  5601. unsigned Num) {
  5602. llvm::APSInt Result;
  5603. // We can't check the value of a dependent argument.
  5604. Expr *Arg = TheCall->getArg(ArgNum);
  5605. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5606. return false;
  5607. // Check constant-ness first.
  5608. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5609. return true;
  5610. if (Result.getSExtValue() % Num != 0)
  5611. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
  5612. << Num << Arg->getSourceRange();
  5613. return false;
  5614. }
  5615. /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
  5616. bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
  5617. if (BuiltinID == AArch64::BI__builtin_arm_irg) {
  5618. if (checkArgCount(*this, TheCall, 2))
  5619. return true;
  5620. Expr *Arg0 = TheCall->getArg(0);
  5621. Expr *Arg1 = TheCall->getArg(1);
  5622. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5623. if (FirstArg.isInvalid())
  5624. return true;
  5625. QualType FirstArgType = FirstArg.get()->getType();
  5626. if (!FirstArgType->isAnyPointerType())
  5627. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5628. << "first" << FirstArgType << Arg0->getSourceRange();
  5629. TheCall->setArg(0, FirstArg.get());
  5630. ExprResult SecArg = DefaultLvalueConversion(Arg1);
  5631. if (SecArg.isInvalid())
  5632. return true;
  5633. QualType SecArgType = SecArg.get()->getType();
  5634. if (!SecArgType->isIntegerType())
  5635. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5636. << "second" << SecArgType << Arg1->getSourceRange();
  5637. // Derive the return type from the pointer argument.
  5638. TheCall->setType(FirstArgType);
  5639. return false;
  5640. }
  5641. if (BuiltinID == AArch64::BI__builtin_arm_addg) {
  5642. if (checkArgCount(*this, TheCall, 2))
  5643. return true;
  5644. Expr *Arg0 = TheCall->getArg(0);
  5645. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5646. if (FirstArg.isInvalid())
  5647. return true;
  5648. QualType FirstArgType = FirstArg.get()->getType();
  5649. if (!FirstArgType->isAnyPointerType())
  5650. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5651. << "first" << FirstArgType << Arg0->getSourceRange();
  5652. TheCall->setArg(0, FirstArg.get());
  5653. // Derive the return type from the pointer argument.
  5654. TheCall->setType(FirstArgType);
  5655. // Second arg must be an constant in range [0,15]
  5656. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5657. }
  5658. if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
  5659. if (checkArgCount(*this, TheCall, 2))
  5660. return true;
  5661. Expr *Arg0 = TheCall->getArg(0);
  5662. Expr *Arg1 = TheCall->getArg(1);
  5663. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5664. if (FirstArg.isInvalid())
  5665. return true;
  5666. QualType FirstArgType = FirstArg.get()->getType();
  5667. if (!FirstArgType->isAnyPointerType())
  5668. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5669. << "first" << FirstArgType << Arg0->getSourceRange();
  5670. QualType SecArgType = Arg1->getType();
  5671. if (!SecArgType->isIntegerType())
  5672. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5673. << "second" << SecArgType << Arg1->getSourceRange();
  5674. TheCall->setType(Context.IntTy);
  5675. return false;
  5676. }
  5677. if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
  5678. BuiltinID == AArch64::BI__builtin_arm_stg) {
  5679. if (checkArgCount(*this, TheCall, 1))
  5680. return true;
  5681. Expr *Arg0 = TheCall->getArg(0);
  5682. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5683. if (FirstArg.isInvalid())
  5684. return true;
  5685. QualType FirstArgType = FirstArg.get()->getType();
  5686. if (!FirstArgType->isAnyPointerType())
  5687. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5688. << "first" << FirstArgType << Arg0->getSourceRange();
  5689. TheCall->setArg(0, FirstArg.get());
  5690. // Derive the return type from the pointer argument.
  5691. if (BuiltinID == AArch64::BI__builtin_arm_ldg)
  5692. TheCall->setType(FirstArgType);
  5693. return false;
  5694. }
  5695. if (BuiltinID == AArch64::BI__builtin_arm_subp) {
  5696. Expr *ArgA = TheCall->getArg(0);
  5697. Expr *ArgB = TheCall->getArg(1);
  5698. ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
  5699. ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
  5700. if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
  5701. return true;
  5702. QualType ArgTypeA = ArgExprA.get()->getType();
  5703. QualType ArgTypeB = ArgExprB.get()->getType();
  5704. auto isNull = [&] (Expr *E) -> bool {
  5705. return E->isNullPointerConstant(
  5706. Context, Expr::NPC_ValueDependentIsNotNull); };
  5707. // argument should be either a pointer or null
  5708. if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
  5709. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5710. << "first" << ArgTypeA << ArgA->getSourceRange();
  5711. if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
  5712. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5713. << "second" << ArgTypeB << ArgB->getSourceRange();
  5714. // Ensure Pointee types are compatible
  5715. if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
  5716. ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
  5717. QualType pointeeA = ArgTypeA->getPointeeType();
  5718. QualType pointeeB = ArgTypeB->getPointeeType();
  5719. if (!Context.typesAreCompatible(
  5720. Context.getCanonicalType(pointeeA).getUnqualifiedType(),
  5721. Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
  5722. return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
  5723. << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
  5724. << ArgB->getSourceRange();
  5725. }
  5726. }
  5727. // at least one argument should be pointer type
  5728. if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
  5729. return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
  5730. << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
  5731. if (isNull(ArgA)) // adopt type of the other pointer
  5732. ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
  5733. if (isNull(ArgB))
  5734. ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
  5735. TheCall->setArg(0, ArgExprA.get());
  5736. TheCall->setArg(1, ArgExprB.get());
  5737. TheCall->setType(Context.LongLongTy);
  5738. return false;
  5739. }
  5740. assert(false && "Unhandled ARM MTE intrinsic");
  5741. return true;
  5742. }
  5743. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  5744. /// TheCall is an ARM/AArch64 special register string literal.
  5745. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  5746. int ArgNum, unsigned ExpectedFieldNum,
  5747. bool AllowName) {
  5748. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  5749. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  5750. BuiltinID == ARM::BI__builtin_arm_rsr ||
  5751. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  5752. BuiltinID == ARM::BI__builtin_arm_wsr ||
  5753. BuiltinID == ARM::BI__builtin_arm_wsrp;
  5754. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  5755. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  5756. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  5757. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  5758. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  5759. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  5760. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  5761. // We can't check the value of a dependent argument.
  5762. Expr *Arg = TheCall->getArg(ArgNum);
  5763. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5764. return false;
  5765. // Check if the argument is a string literal.
  5766. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  5767. return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  5768. << Arg->getSourceRange();
  5769. // Check the type of special register given.
  5770. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  5771. SmallVector<StringRef, 6> Fields;
  5772. Reg.split(Fields, ":");
  5773. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  5774. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5775. << Arg->getSourceRange();
  5776. // If the string is the name of a register then we cannot check that it is
  5777. // valid here but if the string is of one the forms described in ACLE then we
  5778. // can check that the supplied fields are integers and within the valid
  5779. // ranges.
  5780. if (Fields.size() > 1) {
  5781. bool FiveFields = Fields.size() == 5;
  5782. bool ValidString = true;
  5783. if (IsARMBuiltin) {
  5784. ValidString &= Fields[0].startswith_lower("cp") ||
  5785. Fields[0].startswith_lower("p");
  5786. if (ValidString)
  5787. Fields[0] =
  5788. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  5789. ValidString &= Fields[2].startswith_lower("c");
  5790. if (ValidString)
  5791. Fields[2] = Fields[2].drop_front(1);
  5792. if (FiveFields) {
  5793. ValidString &= Fields[3].startswith_lower("c");
  5794. if (ValidString)
  5795. Fields[3] = Fields[3].drop_front(1);
  5796. }
  5797. }
  5798. SmallVector<int, 5> Ranges;
  5799. if (FiveFields)
  5800. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  5801. else
  5802. Ranges.append({15, 7, 15});
  5803. for (unsigned i=0; i<Fields.size(); ++i) {
  5804. int IntField;
  5805. ValidString &= !Fields[i].getAsInteger(10, IntField);
  5806. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  5807. }
  5808. if (!ValidString)
  5809. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5810. << Arg->getSourceRange();
  5811. } else if (IsAArch64Builtin && Fields.size() == 1) {
  5812. // If the register name is one of those that appear in the condition below
  5813. // and the special register builtin being used is one of the write builtins,
  5814. // then we require that the argument provided for writing to the register
  5815. // is an integer constant expression. This is because it will be lowered to
  5816. // an MSR (immediate) instruction, so we need to know the immediate at
  5817. // compile time.
  5818. if (TheCall->getNumArgs() != 2)
  5819. return false;
  5820. std::string RegLower = Reg.lower();
  5821. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  5822. RegLower != "pan" && RegLower != "uao")
  5823. return false;
  5824. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5825. }
  5826. return false;
  5827. }
  5828. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  5829. /// This checks that the target supports __builtin_longjmp and
  5830. /// that val is a constant 1.
  5831. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  5832. if (!Context.getTargetInfo().hasSjLjLowering())
  5833. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
  5834. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5835. Expr *Arg = TheCall->getArg(1);
  5836. llvm::APSInt Result;
  5837. // TODO: This is less than ideal. Overload this to take a value.
  5838. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5839. return true;
  5840. if (Result != 1)
  5841. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
  5842. << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
  5843. return false;
  5844. }
  5845. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  5846. /// This checks that the target supports __builtin_setjmp.
  5847. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  5848. if (!Context.getTargetInfo().hasSjLjLowering())
  5849. return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
  5850. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5851. return false;
  5852. }
  5853. namespace {
  5854. class UncoveredArgHandler {
  5855. enum { Unknown = -1, AllCovered = -2 };
  5856. signed FirstUncoveredArg = Unknown;
  5857. SmallVector<const Expr *, 4> DiagnosticExprs;
  5858. public:
  5859. UncoveredArgHandler() = default;
  5860. bool hasUncoveredArg() const {
  5861. return (FirstUncoveredArg >= 0);
  5862. }
  5863. unsigned getUncoveredArg() const {
  5864. assert(hasUncoveredArg() && "no uncovered argument");
  5865. return FirstUncoveredArg;
  5866. }
  5867. void setAllCovered() {
  5868. // A string has been found with all arguments covered, so clear out
  5869. // the diagnostics.
  5870. DiagnosticExprs.clear();
  5871. FirstUncoveredArg = AllCovered;
  5872. }
  5873. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  5874. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  5875. // Don't update if a previous string covers all arguments.
  5876. if (FirstUncoveredArg == AllCovered)
  5877. return;
  5878. // UncoveredArgHandler tracks the highest uncovered argument index
  5879. // and with it all the strings that match this index.
  5880. if (NewFirstUncoveredArg == FirstUncoveredArg)
  5881. DiagnosticExprs.push_back(StrExpr);
  5882. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  5883. DiagnosticExprs.clear();
  5884. DiagnosticExprs.push_back(StrExpr);
  5885. FirstUncoveredArg = NewFirstUncoveredArg;
  5886. }
  5887. }
  5888. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  5889. };
  5890. enum StringLiteralCheckType {
  5891. SLCT_NotALiteral,
  5892. SLCT_UncheckedLiteral,
  5893. SLCT_CheckedLiteral
  5894. };
  5895. } // namespace
  5896. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  5897. BinaryOperatorKind BinOpKind,
  5898. bool AddendIsRight) {
  5899. unsigned BitWidth = Offset.getBitWidth();
  5900. unsigned AddendBitWidth = Addend.getBitWidth();
  5901. // There might be negative interim results.
  5902. if (Addend.isUnsigned()) {
  5903. Addend = Addend.zext(++AddendBitWidth);
  5904. Addend.setIsSigned(true);
  5905. }
  5906. // Adjust the bit width of the APSInts.
  5907. if (AddendBitWidth > BitWidth) {
  5908. Offset = Offset.sext(AddendBitWidth);
  5909. BitWidth = AddendBitWidth;
  5910. } else if (BitWidth > AddendBitWidth) {
  5911. Addend = Addend.sext(BitWidth);
  5912. }
  5913. bool Ov = false;
  5914. llvm::APSInt ResOffset = Offset;
  5915. if (BinOpKind == BO_Add)
  5916. ResOffset = Offset.sadd_ov(Addend, Ov);
  5917. else {
  5918. assert(AddendIsRight && BinOpKind == BO_Sub &&
  5919. "operator must be add or sub with addend on the right");
  5920. ResOffset = Offset.ssub_ov(Addend, Ov);
  5921. }
  5922. // We add an offset to a pointer here so we should support an offset as big as
  5923. // possible.
  5924. if (Ov) {
  5925. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  5926. "index (intermediate) result too big");
  5927. Offset = Offset.sext(2 * BitWidth);
  5928. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  5929. return;
  5930. }
  5931. Offset = ResOffset;
  5932. }
  5933. namespace {
  5934. // This is a wrapper class around StringLiteral to support offsetted string
  5935. // literals as format strings. It takes the offset into account when returning
  5936. // the string and its length or the source locations to display notes correctly.
  5937. class FormatStringLiteral {
  5938. const StringLiteral *FExpr;
  5939. int64_t Offset;
  5940. public:
  5941. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  5942. : FExpr(fexpr), Offset(Offset) {}
  5943. StringRef getString() const {
  5944. return FExpr->getString().drop_front(Offset);
  5945. }
  5946. unsigned getByteLength() const {
  5947. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  5948. }
  5949. unsigned getLength() const { return FExpr->getLength() - Offset; }
  5950. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  5951. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  5952. QualType getType() const { return FExpr->getType(); }
  5953. bool isAscii() const { return FExpr->isAscii(); }
  5954. bool isWide() const { return FExpr->isWide(); }
  5955. bool isUTF8() const { return FExpr->isUTF8(); }
  5956. bool isUTF16() const { return FExpr->isUTF16(); }
  5957. bool isUTF32() const { return FExpr->isUTF32(); }
  5958. bool isPascal() const { return FExpr->isPascal(); }
  5959. SourceLocation getLocationOfByte(
  5960. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  5961. const TargetInfo &Target, unsigned *StartToken = nullptr,
  5962. unsigned *StartTokenByteOffset = nullptr) const {
  5963. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  5964. StartToken, StartTokenByteOffset);
  5965. }
  5966. SourceLocation getBeginLoc() const LLVM_READONLY {
  5967. return FExpr->getBeginLoc().getLocWithOffset(Offset);
  5968. }
  5969. SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
  5970. };
  5971. } // namespace
  5972. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  5973. const Expr *OrigFormatExpr,
  5974. ArrayRef<const Expr *> Args,
  5975. bool HasVAListArg, unsigned format_idx,
  5976. unsigned firstDataArg,
  5977. Sema::FormatStringType Type,
  5978. bool inFunctionCall,
  5979. Sema::VariadicCallType CallType,
  5980. llvm::SmallBitVector &CheckedVarArgs,
  5981. UncoveredArgHandler &UncoveredArg);
  5982. // Determine if an expression is a string literal or constant string.
  5983. // If this function returns false on the arguments to a function expecting a
  5984. // format string, we will usually need to emit a warning.
  5985. // True string literals are then checked by CheckFormatString.
  5986. static StringLiteralCheckType
  5987. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  5988. bool HasVAListArg, unsigned format_idx,
  5989. unsigned firstDataArg, Sema::FormatStringType Type,
  5990. Sema::VariadicCallType CallType, bool InFunctionCall,
  5991. llvm::SmallBitVector &CheckedVarArgs,
  5992. UncoveredArgHandler &UncoveredArg,
  5993. llvm::APSInt Offset) {
  5994. tryAgain:
  5995. assert(Offset.isSigned() && "invalid offset");
  5996. if (E->isTypeDependent() || E->isValueDependent())
  5997. return SLCT_NotALiteral;
  5998. E = E->IgnoreParenCasts();
  5999. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  6000. // Technically -Wformat-nonliteral does not warn about this case.
  6001. // The behavior of printf and friends in this case is implementation
  6002. // dependent. Ideally if the format string cannot be null then
  6003. // it should have a 'nonnull' attribute in the function prototype.
  6004. return SLCT_UncheckedLiteral;
  6005. switch (E->getStmtClass()) {
  6006. case Stmt::BinaryConditionalOperatorClass:
  6007. case Stmt::ConditionalOperatorClass: {
  6008. // The expression is a literal if both sub-expressions were, and it was
  6009. // completely checked only if both sub-expressions were checked.
  6010. const AbstractConditionalOperator *C =
  6011. cast<AbstractConditionalOperator>(E);
  6012. // Determine whether it is necessary to check both sub-expressions, for
  6013. // example, because the condition expression is a constant that can be
  6014. // evaluated at compile time.
  6015. bool CheckLeft = true, CheckRight = true;
  6016. bool Cond;
  6017. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
  6018. if (Cond)
  6019. CheckRight = false;
  6020. else
  6021. CheckLeft = false;
  6022. }
  6023. // We need to maintain the offsets for the right and the left hand side
  6024. // separately to check if every possible indexed expression is a valid
  6025. // string literal. They might have different offsets for different string
  6026. // literals in the end.
  6027. StringLiteralCheckType Left;
  6028. if (!CheckLeft)
  6029. Left = SLCT_UncheckedLiteral;
  6030. else {
  6031. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  6032. HasVAListArg, format_idx, firstDataArg,
  6033. Type, CallType, InFunctionCall,
  6034. CheckedVarArgs, UncoveredArg, Offset);
  6035. if (Left == SLCT_NotALiteral || !CheckRight) {
  6036. return Left;
  6037. }
  6038. }
  6039. StringLiteralCheckType Right =
  6040. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  6041. HasVAListArg, format_idx, firstDataArg,
  6042. Type, CallType, InFunctionCall, CheckedVarArgs,
  6043. UncoveredArg, Offset);
  6044. return (CheckLeft && Left < Right) ? Left : Right;
  6045. }
  6046. case Stmt::ImplicitCastExprClass:
  6047. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  6048. goto tryAgain;
  6049. case Stmt::OpaqueValueExprClass:
  6050. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  6051. E = src;
  6052. goto tryAgain;
  6053. }
  6054. return SLCT_NotALiteral;
  6055. case Stmt::PredefinedExprClass:
  6056. // While __func__, etc., are technically not string literals, they
  6057. // cannot contain format specifiers and thus are not a security
  6058. // liability.
  6059. return SLCT_UncheckedLiteral;
  6060. case Stmt::DeclRefExprClass: {
  6061. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  6062. // As an exception, do not flag errors for variables binding to
  6063. // const string literals.
  6064. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  6065. bool isConstant = false;
  6066. QualType T = DR->getType();
  6067. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  6068. isConstant = AT->getElementType().isConstant(S.Context);
  6069. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  6070. isConstant = T.isConstant(S.Context) &&
  6071. PT->getPointeeType().isConstant(S.Context);
  6072. } else if (T->isObjCObjectPointerType()) {
  6073. // In ObjC, there is usually no "const ObjectPointer" type,
  6074. // so don't check if the pointee type is constant.
  6075. isConstant = T.isConstant(S.Context);
  6076. }
  6077. if (isConstant) {
  6078. if (const Expr *Init = VD->getAnyInitializer()) {
  6079. // Look through initializers like const char c[] = { "foo" }
  6080. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  6081. if (InitList->isStringLiteralInit())
  6082. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  6083. }
  6084. return checkFormatStringExpr(S, Init, Args,
  6085. HasVAListArg, format_idx,
  6086. firstDataArg, Type, CallType,
  6087. /*InFunctionCall*/ false, CheckedVarArgs,
  6088. UncoveredArg, Offset);
  6089. }
  6090. }
  6091. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  6092. // special check to see if the format string is a function parameter
  6093. // of the function calling the printf function. If the function
  6094. // has an attribute indicating it is a printf-like function, then we
  6095. // should suppress warnings concerning non-literals being used in a call
  6096. // to a vprintf function. For example:
  6097. //
  6098. // void
  6099. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  6100. // va_list ap;
  6101. // va_start(ap, fmt);
  6102. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  6103. // ...
  6104. // }
  6105. if (HasVAListArg) {
  6106. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  6107. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  6108. int PVIndex = PV->getFunctionScopeIndex() + 1;
  6109. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  6110. // adjust for implicit parameter
  6111. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  6112. if (MD->isInstance())
  6113. ++PVIndex;
  6114. // We also check if the formats are compatible.
  6115. // We can't pass a 'scanf' string to a 'printf' function.
  6116. if (PVIndex == PVFormat->getFormatIdx() &&
  6117. Type == S.GetFormatStringType(PVFormat))
  6118. return SLCT_UncheckedLiteral;
  6119. }
  6120. }
  6121. }
  6122. }
  6123. }
  6124. return SLCT_NotALiteral;
  6125. }
  6126. case Stmt::CallExprClass:
  6127. case Stmt::CXXMemberCallExprClass: {
  6128. const CallExpr *CE = cast<CallExpr>(E);
  6129. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  6130. bool IsFirst = true;
  6131. StringLiteralCheckType CommonResult;
  6132. for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
  6133. const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
  6134. StringLiteralCheckType Result = checkFormatStringExpr(
  6135. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6136. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  6137. if (IsFirst) {
  6138. CommonResult = Result;
  6139. IsFirst = false;
  6140. }
  6141. }
  6142. if (!IsFirst)
  6143. return CommonResult;
  6144. if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
  6145. unsigned BuiltinID = FD->getBuiltinID();
  6146. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  6147. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  6148. const Expr *Arg = CE->getArg(0);
  6149. return checkFormatStringExpr(S, Arg, Args,
  6150. HasVAListArg, format_idx,
  6151. firstDataArg, Type, CallType,
  6152. InFunctionCall, CheckedVarArgs,
  6153. UncoveredArg, Offset);
  6154. }
  6155. }
  6156. }
  6157. return SLCT_NotALiteral;
  6158. }
  6159. case Stmt::ObjCMessageExprClass: {
  6160. const auto *ME = cast<ObjCMessageExpr>(E);
  6161. if (const auto *ND = ME->getMethodDecl()) {
  6162. if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
  6163. const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
  6164. return checkFormatStringExpr(
  6165. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6166. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  6167. }
  6168. }
  6169. return SLCT_NotALiteral;
  6170. }
  6171. case Stmt::ObjCStringLiteralClass:
  6172. case Stmt::StringLiteralClass: {
  6173. const StringLiteral *StrE = nullptr;
  6174. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  6175. StrE = ObjCFExpr->getString();
  6176. else
  6177. StrE = cast<StringLiteral>(E);
  6178. if (StrE) {
  6179. if (Offset.isNegative() || Offset > StrE->getLength()) {
  6180. // TODO: It would be better to have an explicit warning for out of
  6181. // bounds literals.
  6182. return SLCT_NotALiteral;
  6183. }
  6184. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  6185. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  6186. firstDataArg, Type, InFunctionCall, CallType,
  6187. CheckedVarArgs, UncoveredArg);
  6188. return SLCT_CheckedLiteral;
  6189. }
  6190. return SLCT_NotALiteral;
  6191. }
  6192. case Stmt::BinaryOperatorClass: {
  6193. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  6194. // A string literal + an int offset is still a string literal.
  6195. if (BinOp->isAdditiveOp()) {
  6196. Expr::EvalResult LResult, RResult;
  6197. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
  6198. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
  6199. if (LIsInt != RIsInt) {
  6200. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  6201. if (LIsInt) {
  6202. if (BinOpKind == BO_Add) {
  6203. sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
  6204. E = BinOp->getRHS();
  6205. goto tryAgain;
  6206. }
  6207. } else {
  6208. sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
  6209. E = BinOp->getLHS();
  6210. goto tryAgain;
  6211. }
  6212. }
  6213. }
  6214. return SLCT_NotALiteral;
  6215. }
  6216. case Stmt::UnaryOperatorClass: {
  6217. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  6218. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  6219. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  6220. Expr::EvalResult IndexResult;
  6221. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
  6222. sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
  6223. /*RHS is int*/ true);
  6224. E = ASE->getBase();
  6225. goto tryAgain;
  6226. }
  6227. }
  6228. return SLCT_NotALiteral;
  6229. }
  6230. default:
  6231. return SLCT_NotALiteral;
  6232. }
  6233. }
  6234. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  6235. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  6236. .Case("scanf", FST_Scanf)
  6237. .Cases("printf", "printf0", FST_Printf)
  6238. .Cases("NSString", "CFString", FST_NSString)
  6239. .Case("strftime", FST_Strftime)
  6240. .Case("strfmon", FST_Strfmon)
  6241. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  6242. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  6243. .Case("os_trace", FST_OSLog)
  6244. .Case("os_log", FST_OSLog)
  6245. .Default(FST_Unknown);
  6246. }
  6247. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  6248. /// functions) for correct use of format strings.
  6249. /// Returns true if a format string has been fully checked.
  6250. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  6251. ArrayRef<const Expr *> Args,
  6252. bool IsCXXMember,
  6253. VariadicCallType CallType,
  6254. SourceLocation Loc, SourceRange Range,
  6255. llvm::SmallBitVector &CheckedVarArgs) {
  6256. FormatStringInfo FSI;
  6257. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  6258. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  6259. FSI.FirstDataArg, GetFormatStringType(Format),
  6260. CallType, Loc, Range, CheckedVarArgs);
  6261. return false;
  6262. }
  6263. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  6264. bool HasVAListArg, unsigned format_idx,
  6265. unsigned firstDataArg, FormatStringType Type,
  6266. VariadicCallType CallType,
  6267. SourceLocation Loc, SourceRange Range,
  6268. llvm::SmallBitVector &CheckedVarArgs) {
  6269. // CHECK: printf/scanf-like function is called with no format string.
  6270. if (format_idx >= Args.size()) {
  6271. Diag(Loc, diag::warn_missing_format_string) << Range;
  6272. return false;
  6273. }
  6274. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  6275. // CHECK: format string is not a string literal.
  6276. //
  6277. // Dynamically generated format strings are difficult to
  6278. // automatically vet at compile time. Requiring that format strings
  6279. // are string literals: (1) permits the checking of format strings by
  6280. // the compiler and thereby (2) can practically remove the source of
  6281. // many format string exploits.
  6282. // Format string can be either ObjC string (e.g. @"%d") or
  6283. // C string (e.g. "%d")
  6284. // ObjC string uses the same format specifiers as C string, so we can use
  6285. // the same format string checking logic for both ObjC and C strings.
  6286. UncoveredArgHandler UncoveredArg;
  6287. StringLiteralCheckType CT =
  6288. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  6289. format_idx, firstDataArg, Type, CallType,
  6290. /*IsFunctionCall*/ true, CheckedVarArgs,
  6291. UncoveredArg,
  6292. /*no string offset*/ llvm::APSInt(64, false) = 0);
  6293. // Generate a diagnostic where an uncovered argument is detected.
  6294. if (UncoveredArg.hasUncoveredArg()) {
  6295. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  6296. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  6297. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  6298. }
  6299. if (CT != SLCT_NotALiteral)
  6300. // Literal format string found, check done!
  6301. return CT == SLCT_CheckedLiteral;
  6302. // Strftime is particular as it always uses a single 'time' argument,
  6303. // so it is safe to pass a non-literal string.
  6304. if (Type == FST_Strftime)
  6305. return false;
  6306. // Do not emit diag when the string param is a macro expansion and the
  6307. // format is either NSString or CFString. This is a hack to prevent
  6308. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  6309. // which are usually used in place of NS and CF string literals.
  6310. SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
  6311. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  6312. return false;
  6313. // If there are no arguments specified, warn with -Wformat-security, otherwise
  6314. // warn only with -Wformat-nonliteral.
  6315. if (Args.size() == firstDataArg) {
  6316. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  6317. << OrigFormatExpr->getSourceRange();
  6318. switch (Type) {
  6319. default:
  6320. break;
  6321. case FST_Kprintf:
  6322. case FST_FreeBSDKPrintf:
  6323. case FST_Printf:
  6324. Diag(FormatLoc, diag::note_format_security_fixit)
  6325. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  6326. break;
  6327. case FST_NSString:
  6328. Diag(FormatLoc, diag::note_format_security_fixit)
  6329. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  6330. break;
  6331. }
  6332. } else {
  6333. Diag(FormatLoc, diag::warn_format_nonliteral)
  6334. << OrigFormatExpr->getSourceRange();
  6335. }
  6336. return false;
  6337. }
  6338. namespace {
  6339. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  6340. protected:
  6341. Sema &S;
  6342. const FormatStringLiteral *FExpr;
  6343. const Expr *OrigFormatExpr;
  6344. const Sema::FormatStringType FSType;
  6345. const unsigned FirstDataArg;
  6346. const unsigned NumDataArgs;
  6347. const char *Beg; // Start of format string.
  6348. const bool HasVAListArg;
  6349. ArrayRef<const Expr *> Args;
  6350. unsigned FormatIdx;
  6351. llvm::SmallBitVector CoveredArgs;
  6352. bool usesPositionalArgs = false;
  6353. bool atFirstArg = true;
  6354. bool inFunctionCall;
  6355. Sema::VariadicCallType CallType;
  6356. llvm::SmallBitVector &CheckedVarArgs;
  6357. UncoveredArgHandler &UncoveredArg;
  6358. public:
  6359. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  6360. const Expr *origFormatExpr,
  6361. const Sema::FormatStringType type, unsigned firstDataArg,
  6362. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  6363. ArrayRef<const Expr *> Args, unsigned formatIdx,
  6364. bool inFunctionCall, Sema::VariadicCallType callType,
  6365. llvm::SmallBitVector &CheckedVarArgs,
  6366. UncoveredArgHandler &UncoveredArg)
  6367. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  6368. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  6369. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  6370. inFunctionCall(inFunctionCall), CallType(callType),
  6371. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  6372. CoveredArgs.resize(numDataArgs);
  6373. CoveredArgs.reset();
  6374. }
  6375. void DoneProcessing();
  6376. void HandleIncompleteSpecifier(const char *startSpecifier,
  6377. unsigned specifierLen) override;
  6378. void HandleInvalidLengthModifier(
  6379. const analyze_format_string::FormatSpecifier &FS,
  6380. const analyze_format_string::ConversionSpecifier &CS,
  6381. const char *startSpecifier, unsigned specifierLen,
  6382. unsigned DiagID);
  6383. void HandleNonStandardLengthModifier(
  6384. const analyze_format_string::FormatSpecifier &FS,
  6385. const char *startSpecifier, unsigned specifierLen);
  6386. void HandleNonStandardConversionSpecifier(
  6387. const analyze_format_string::ConversionSpecifier &CS,
  6388. const char *startSpecifier, unsigned specifierLen);
  6389. void HandlePosition(const char *startPos, unsigned posLen) override;
  6390. void HandleInvalidPosition(const char *startSpecifier,
  6391. unsigned specifierLen,
  6392. analyze_format_string::PositionContext p) override;
  6393. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  6394. void HandleNullChar(const char *nullCharacter) override;
  6395. template <typename Range>
  6396. static void
  6397. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  6398. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  6399. bool IsStringLocation, Range StringRange,
  6400. ArrayRef<FixItHint> Fixit = None);
  6401. protected:
  6402. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  6403. const char *startSpec,
  6404. unsigned specifierLen,
  6405. const char *csStart, unsigned csLen);
  6406. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6407. const char *startSpec,
  6408. unsigned specifierLen);
  6409. SourceRange getFormatStringRange();
  6410. CharSourceRange getSpecifierRange(const char *startSpecifier,
  6411. unsigned specifierLen);
  6412. SourceLocation getLocationOfByte(const char *x);
  6413. const Expr *getDataArg(unsigned i) const;
  6414. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  6415. const analyze_format_string::ConversionSpecifier &CS,
  6416. const char *startSpecifier, unsigned specifierLen,
  6417. unsigned argIndex);
  6418. template <typename Range>
  6419. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  6420. bool IsStringLocation, Range StringRange,
  6421. ArrayRef<FixItHint> Fixit = None);
  6422. };
  6423. } // namespace
  6424. SourceRange CheckFormatHandler::getFormatStringRange() {
  6425. return OrigFormatExpr->getSourceRange();
  6426. }
  6427. CharSourceRange CheckFormatHandler::
  6428. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  6429. SourceLocation Start = getLocationOfByte(startSpecifier);
  6430. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  6431. // Advance the end SourceLocation by one due to half-open ranges.
  6432. End = End.getLocWithOffset(1);
  6433. return CharSourceRange::getCharRange(Start, End);
  6434. }
  6435. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  6436. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  6437. S.getLangOpts(), S.Context.getTargetInfo());
  6438. }
  6439. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  6440. unsigned specifierLen){
  6441. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  6442. getLocationOfByte(startSpecifier),
  6443. /*IsStringLocation*/true,
  6444. getSpecifierRange(startSpecifier, specifierLen));
  6445. }
  6446. void CheckFormatHandler::HandleInvalidLengthModifier(
  6447. const analyze_format_string::FormatSpecifier &FS,
  6448. const analyze_format_string::ConversionSpecifier &CS,
  6449. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  6450. using namespace analyze_format_string;
  6451. const LengthModifier &LM = FS.getLengthModifier();
  6452. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6453. // See if we know how to fix this length modifier.
  6454. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6455. if (FixedLM) {
  6456. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6457. getLocationOfByte(LM.getStart()),
  6458. /*IsStringLocation*/true,
  6459. getSpecifierRange(startSpecifier, specifierLen));
  6460. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6461. << FixedLM->toString()
  6462. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6463. } else {
  6464. FixItHint Hint;
  6465. if (DiagID == diag::warn_format_nonsensical_length)
  6466. Hint = FixItHint::CreateRemoval(LMRange);
  6467. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6468. getLocationOfByte(LM.getStart()),
  6469. /*IsStringLocation*/true,
  6470. getSpecifierRange(startSpecifier, specifierLen),
  6471. Hint);
  6472. }
  6473. }
  6474. void CheckFormatHandler::HandleNonStandardLengthModifier(
  6475. const analyze_format_string::FormatSpecifier &FS,
  6476. const char *startSpecifier, unsigned specifierLen) {
  6477. using namespace analyze_format_string;
  6478. const LengthModifier &LM = FS.getLengthModifier();
  6479. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6480. // See if we know how to fix this length modifier.
  6481. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6482. if (FixedLM) {
  6483. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6484. << LM.toString() << 0,
  6485. getLocationOfByte(LM.getStart()),
  6486. /*IsStringLocation*/true,
  6487. getSpecifierRange(startSpecifier, specifierLen));
  6488. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6489. << FixedLM->toString()
  6490. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6491. } else {
  6492. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6493. << LM.toString() << 0,
  6494. getLocationOfByte(LM.getStart()),
  6495. /*IsStringLocation*/true,
  6496. getSpecifierRange(startSpecifier, specifierLen));
  6497. }
  6498. }
  6499. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  6500. const analyze_format_string::ConversionSpecifier &CS,
  6501. const char *startSpecifier, unsigned specifierLen) {
  6502. using namespace analyze_format_string;
  6503. // See if we know how to fix this conversion specifier.
  6504. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  6505. if (FixedCS) {
  6506. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6507. << CS.toString() << /*conversion specifier*/1,
  6508. getLocationOfByte(CS.getStart()),
  6509. /*IsStringLocation*/true,
  6510. getSpecifierRange(startSpecifier, specifierLen));
  6511. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  6512. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  6513. << FixedCS->toString()
  6514. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  6515. } else {
  6516. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6517. << CS.toString() << /*conversion specifier*/1,
  6518. getLocationOfByte(CS.getStart()),
  6519. /*IsStringLocation*/true,
  6520. getSpecifierRange(startSpecifier, specifierLen));
  6521. }
  6522. }
  6523. void CheckFormatHandler::HandlePosition(const char *startPos,
  6524. unsigned posLen) {
  6525. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  6526. getLocationOfByte(startPos),
  6527. /*IsStringLocation*/true,
  6528. getSpecifierRange(startPos, posLen));
  6529. }
  6530. void
  6531. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  6532. analyze_format_string::PositionContext p) {
  6533. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  6534. << (unsigned) p,
  6535. getLocationOfByte(startPos), /*IsStringLocation*/true,
  6536. getSpecifierRange(startPos, posLen));
  6537. }
  6538. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  6539. unsigned posLen) {
  6540. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  6541. getLocationOfByte(startPos),
  6542. /*IsStringLocation*/true,
  6543. getSpecifierRange(startPos, posLen));
  6544. }
  6545. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  6546. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  6547. // The presence of a null character is likely an error.
  6548. EmitFormatDiagnostic(
  6549. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  6550. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  6551. getFormatStringRange());
  6552. }
  6553. }
  6554. // Note that this may return NULL if there was an error parsing or building
  6555. // one of the argument expressions.
  6556. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  6557. return Args[FirstDataArg + i];
  6558. }
  6559. void CheckFormatHandler::DoneProcessing() {
  6560. // Does the number of data arguments exceed the number of
  6561. // format conversions in the format string?
  6562. if (!HasVAListArg) {
  6563. // Find any arguments that weren't covered.
  6564. CoveredArgs.flip();
  6565. signed notCoveredArg = CoveredArgs.find_first();
  6566. if (notCoveredArg >= 0) {
  6567. assert((unsigned)notCoveredArg < NumDataArgs);
  6568. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  6569. } else {
  6570. UncoveredArg.setAllCovered();
  6571. }
  6572. }
  6573. }
  6574. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  6575. const Expr *ArgExpr) {
  6576. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  6577. "Invalid state");
  6578. if (!ArgExpr)
  6579. return;
  6580. SourceLocation Loc = ArgExpr->getBeginLoc();
  6581. if (S.getSourceManager().isInSystemMacro(Loc))
  6582. return;
  6583. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  6584. for (auto E : DiagnosticExprs)
  6585. PDiag << E->getSourceRange();
  6586. CheckFormatHandler::EmitFormatDiagnostic(
  6587. S, IsFunctionCall, DiagnosticExprs[0],
  6588. PDiag, Loc, /*IsStringLocation*/false,
  6589. DiagnosticExprs[0]->getSourceRange());
  6590. }
  6591. bool
  6592. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  6593. SourceLocation Loc,
  6594. const char *startSpec,
  6595. unsigned specifierLen,
  6596. const char *csStart,
  6597. unsigned csLen) {
  6598. bool keepGoing = true;
  6599. if (argIndex < NumDataArgs) {
  6600. // Consider the argument coverered, even though the specifier doesn't
  6601. // make sense.
  6602. CoveredArgs.set(argIndex);
  6603. }
  6604. else {
  6605. // If argIndex exceeds the number of data arguments we
  6606. // don't issue a warning because that is just a cascade of warnings (and
  6607. // they may have intended '%%' anyway). We don't want to continue processing
  6608. // the format string after this point, however, as we will like just get
  6609. // gibberish when trying to match arguments.
  6610. keepGoing = false;
  6611. }
  6612. StringRef Specifier(csStart, csLen);
  6613. // If the specifier in non-printable, it could be the first byte of a UTF-8
  6614. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  6615. // hex value.
  6616. std::string CodePointStr;
  6617. if (!llvm::sys::locale::isPrint(*csStart)) {
  6618. llvm::UTF32 CodePoint;
  6619. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  6620. const llvm::UTF8 *E =
  6621. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  6622. llvm::ConversionResult Result =
  6623. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  6624. if (Result != llvm::conversionOK) {
  6625. unsigned char FirstChar = *csStart;
  6626. CodePoint = (llvm::UTF32)FirstChar;
  6627. }
  6628. llvm::raw_string_ostream OS(CodePointStr);
  6629. if (CodePoint < 256)
  6630. OS << "\\x" << llvm::format("%02x", CodePoint);
  6631. else if (CodePoint <= 0xFFFF)
  6632. OS << "\\u" << llvm::format("%04x", CodePoint);
  6633. else
  6634. OS << "\\U" << llvm::format("%08x", CodePoint);
  6635. OS.flush();
  6636. Specifier = CodePointStr;
  6637. }
  6638. EmitFormatDiagnostic(
  6639. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  6640. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  6641. return keepGoing;
  6642. }
  6643. void
  6644. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6645. const char *startSpec,
  6646. unsigned specifierLen) {
  6647. EmitFormatDiagnostic(
  6648. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  6649. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  6650. }
  6651. bool
  6652. CheckFormatHandler::CheckNumArgs(
  6653. const analyze_format_string::FormatSpecifier &FS,
  6654. const analyze_format_string::ConversionSpecifier &CS,
  6655. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  6656. if (argIndex >= NumDataArgs) {
  6657. PartialDiagnostic PDiag = FS.usesPositionalArg()
  6658. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  6659. << (argIndex+1) << NumDataArgs)
  6660. : S.PDiag(diag::warn_printf_insufficient_data_args);
  6661. EmitFormatDiagnostic(
  6662. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  6663. getSpecifierRange(startSpecifier, specifierLen));
  6664. // Since more arguments than conversion tokens are given, by extension
  6665. // all arguments are covered, so mark this as so.
  6666. UncoveredArg.setAllCovered();
  6667. return false;
  6668. }
  6669. return true;
  6670. }
  6671. template<typename Range>
  6672. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  6673. SourceLocation Loc,
  6674. bool IsStringLocation,
  6675. Range StringRange,
  6676. ArrayRef<FixItHint> FixIt) {
  6677. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  6678. Loc, IsStringLocation, StringRange, FixIt);
  6679. }
  6680. /// If the format string is not within the function call, emit a note
  6681. /// so that the function call and string are in diagnostic messages.
  6682. ///
  6683. /// \param InFunctionCall if true, the format string is within the function
  6684. /// call and only one diagnostic message will be produced. Otherwise, an
  6685. /// extra note will be emitted pointing to location of the format string.
  6686. ///
  6687. /// \param ArgumentExpr the expression that is passed as the format string
  6688. /// argument in the function call. Used for getting locations when two
  6689. /// diagnostics are emitted.
  6690. ///
  6691. /// \param PDiag the callee should already have provided any strings for the
  6692. /// diagnostic message. This function only adds locations and fixits
  6693. /// to diagnostics.
  6694. ///
  6695. /// \param Loc primary location for diagnostic. If two diagnostics are
  6696. /// required, one will be at Loc and a new SourceLocation will be created for
  6697. /// the other one.
  6698. ///
  6699. /// \param IsStringLocation if true, Loc points to the format string should be
  6700. /// used for the note. Otherwise, Loc points to the argument list and will
  6701. /// be used with PDiag.
  6702. ///
  6703. /// \param StringRange some or all of the string to highlight. This is
  6704. /// templated so it can accept either a CharSourceRange or a SourceRange.
  6705. ///
  6706. /// \param FixIt optional fix it hint for the format string.
  6707. template <typename Range>
  6708. void CheckFormatHandler::EmitFormatDiagnostic(
  6709. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  6710. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  6711. Range StringRange, ArrayRef<FixItHint> FixIt) {
  6712. if (InFunctionCall) {
  6713. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  6714. D << StringRange;
  6715. D << FixIt;
  6716. } else {
  6717. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  6718. << ArgumentExpr->getSourceRange();
  6719. const Sema::SemaDiagnosticBuilder &Note =
  6720. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  6721. diag::note_format_string_defined);
  6722. Note << StringRange;
  6723. Note << FixIt;
  6724. }
  6725. }
  6726. //===--- CHECK: Printf format string checking ------------------------------===//
  6727. namespace {
  6728. class CheckPrintfHandler : public CheckFormatHandler {
  6729. public:
  6730. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  6731. const Expr *origFormatExpr,
  6732. const Sema::FormatStringType type, unsigned firstDataArg,
  6733. unsigned numDataArgs, bool isObjC, const char *beg,
  6734. bool hasVAListArg, ArrayRef<const Expr *> Args,
  6735. unsigned formatIdx, bool inFunctionCall,
  6736. Sema::VariadicCallType CallType,
  6737. llvm::SmallBitVector &CheckedVarArgs,
  6738. UncoveredArgHandler &UncoveredArg)
  6739. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  6740. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  6741. inFunctionCall, CallType, CheckedVarArgs,
  6742. UncoveredArg) {}
  6743. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  6744. /// Returns true if '%@' specifiers are allowed in the format string.
  6745. bool allowsObjCArg() const {
  6746. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  6747. FSType == Sema::FST_OSTrace;
  6748. }
  6749. bool HandleInvalidPrintfConversionSpecifier(
  6750. const analyze_printf::PrintfSpecifier &FS,
  6751. const char *startSpecifier,
  6752. unsigned specifierLen) override;
  6753. void handleInvalidMaskType(StringRef MaskType) override;
  6754. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  6755. const char *startSpecifier,
  6756. unsigned specifierLen) override;
  6757. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  6758. const char *StartSpecifier,
  6759. unsigned SpecifierLen,
  6760. const Expr *E);
  6761. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  6762. const char *startSpecifier, unsigned specifierLen);
  6763. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  6764. const analyze_printf::OptionalAmount &Amt,
  6765. unsigned type,
  6766. const char *startSpecifier, unsigned specifierLen);
  6767. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6768. const analyze_printf::OptionalFlag &flag,
  6769. const char *startSpecifier, unsigned specifierLen);
  6770. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  6771. const analyze_printf::OptionalFlag &ignoredFlag,
  6772. const analyze_printf::OptionalFlag &flag,
  6773. const char *startSpecifier, unsigned specifierLen);
  6774. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  6775. const Expr *E);
  6776. void HandleEmptyObjCModifierFlag(const char *startFlag,
  6777. unsigned flagLen) override;
  6778. void HandleInvalidObjCModifierFlag(const char *startFlag,
  6779. unsigned flagLen) override;
  6780. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  6781. const char *flagsEnd,
  6782. const char *conversionPosition)
  6783. override;
  6784. };
  6785. } // namespace
  6786. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  6787. const analyze_printf::PrintfSpecifier &FS,
  6788. const char *startSpecifier,
  6789. unsigned specifierLen) {
  6790. const analyze_printf::PrintfConversionSpecifier &CS =
  6791. FS.getConversionSpecifier();
  6792. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  6793. getLocationOfByte(CS.getStart()),
  6794. startSpecifier, specifierLen,
  6795. CS.getStart(), CS.getLength());
  6796. }
  6797. void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
  6798. S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
  6799. }
  6800. bool CheckPrintfHandler::HandleAmount(
  6801. const analyze_format_string::OptionalAmount &Amt,
  6802. unsigned k, const char *startSpecifier,
  6803. unsigned specifierLen) {
  6804. if (Amt.hasDataArgument()) {
  6805. if (!HasVAListArg) {
  6806. unsigned argIndex = Amt.getArgIndex();
  6807. if (argIndex >= NumDataArgs) {
  6808. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  6809. << k,
  6810. getLocationOfByte(Amt.getStart()),
  6811. /*IsStringLocation*/true,
  6812. getSpecifierRange(startSpecifier, specifierLen));
  6813. // Don't do any more checking. We will just emit
  6814. // spurious errors.
  6815. return false;
  6816. }
  6817. // Type check the data argument. It should be an 'int'.
  6818. // Although not in conformance with C99, we also allow the argument to be
  6819. // an 'unsigned int' as that is a reasonably safe case. GCC also
  6820. // doesn't emit a warning for that case.
  6821. CoveredArgs.set(argIndex);
  6822. const Expr *Arg = getDataArg(argIndex);
  6823. if (!Arg)
  6824. return false;
  6825. QualType T = Arg->getType();
  6826. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  6827. assert(AT.isValid());
  6828. if (!AT.matchesType(S.Context, T)) {
  6829. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  6830. << k << AT.getRepresentativeTypeName(S.Context)
  6831. << T << Arg->getSourceRange(),
  6832. getLocationOfByte(Amt.getStart()),
  6833. /*IsStringLocation*/true,
  6834. getSpecifierRange(startSpecifier, specifierLen));
  6835. // Don't do any more checking. We will just emit
  6836. // spurious errors.
  6837. return false;
  6838. }
  6839. }
  6840. }
  6841. return true;
  6842. }
  6843. void CheckPrintfHandler::HandleInvalidAmount(
  6844. const analyze_printf::PrintfSpecifier &FS,
  6845. const analyze_printf::OptionalAmount &Amt,
  6846. unsigned type,
  6847. const char *startSpecifier,
  6848. unsigned specifierLen) {
  6849. const analyze_printf::PrintfConversionSpecifier &CS =
  6850. FS.getConversionSpecifier();
  6851. FixItHint fixit =
  6852. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  6853. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  6854. Amt.getConstantLength()))
  6855. : FixItHint();
  6856. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  6857. << type << CS.toString(),
  6858. getLocationOfByte(Amt.getStart()),
  6859. /*IsStringLocation*/true,
  6860. getSpecifierRange(startSpecifier, specifierLen),
  6861. fixit);
  6862. }
  6863. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6864. const analyze_printf::OptionalFlag &flag,
  6865. const char *startSpecifier,
  6866. unsigned specifierLen) {
  6867. // Warn about pointless flag with a fixit removal.
  6868. const analyze_printf::PrintfConversionSpecifier &CS =
  6869. FS.getConversionSpecifier();
  6870. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  6871. << flag.toString() << CS.toString(),
  6872. getLocationOfByte(flag.getPosition()),
  6873. /*IsStringLocation*/true,
  6874. getSpecifierRange(startSpecifier, specifierLen),
  6875. FixItHint::CreateRemoval(
  6876. getSpecifierRange(flag.getPosition(), 1)));
  6877. }
  6878. void CheckPrintfHandler::HandleIgnoredFlag(
  6879. const analyze_printf::PrintfSpecifier &FS,
  6880. const analyze_printf::OptionalFlag &ignoredFlag,
  6881. const analyze_printf::OptionalFlag &flag,
  6882. const char *startSpecifier,
  6883. unsigned specifierLen) {
  6884. // Warn about ignored flag with a fixit removal.
  6885. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  6886. << ignoredFlag.toString() << flag.toString(),
  6887. getLocationOfByte(ignoredFlag.getPosition()),
  6888. /*IsStringLocation*/true,
  6889. getSpecifierRange(startSpecifier, specifierLen),
  6890. FixItHint::CreateRemoval(
  6891. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  6892. }
  6893. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  6894. unsigned flagLen) {
  6895. // Warn about an empty flag.
  6896. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  6897. getLocationOfByte(startFlag),
  6898. /*IsStringLocation*/true,
  6899. getSpecifierRange(startFlag, flagLen));
  6900. }
  6901. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  6902. unsigned flagLen) {
  6903. // Warn about an invalid flag.
  6904. auto Range = getSpecifierRange(startFlag, flagLen);
  6905. StringRef flag(startFlag, flagLen);
  6906. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  6907. getLocationOfByte(startFlag),
  6908. /*IsStringLocation*/true,
  6909. Range, FixItHint::CreateRemoval(Range));
  6910. }
  6911. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  6912. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  6913. // Warn about using '[...]' without a '@' conversion.
  6914. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  6915. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  6916. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  6917. getLocationOfByte(conversionPosition),
  6918. /*IsStringLocation*/true,
  6919. Range, FixItHint::CreateRemoval(Range));
  6920. }
  6921. // Determines if the specified is a C++ class or struct containing
  6922. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  6923. // "c_str()").
  6924. template<typename MemberKind>
  6925. static llvm::SmallPtrSet<MemberKind*, 1>
  6926. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  6927. const RecordType *RT = Ty->getAs<RecordType>();
  6928. llvm::SmallPtrSet<MemberKind*, 1> Results;
  6929. if (!RT)
  6930. return Results;
  6931. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  6932. if (!RD || !RD->getDefinition())
  6933. return Results;
  6934. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  6935. Sema::LookupMemberName);
  6936. R.suppressDiagnostics();
  6937. // We just need to include all members of the right kind turned up by the
  6938. // filter, at this point.
  6939. if (S.LookupQualifiedName(R, RT->getDecl()))
  6940. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  6941. NamedDecl *decl = (*I)->getUnderlyingDecl();
  6942. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  6943. Results.insert(FK);
  6944. }
  6945. return Results;
  6946. }
  6947. /// Check if we could call '.c_str()' on an object.
  6948. ///
  6949. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  6950. /// allow the call, or if it would be ambiguous).
  6951. bool Sema::hasCStrMethod(const Expr *E) {
  6952. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6953. MethodSet Results =
  6954. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  6955. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6956. MI != ME; ++MI)
  6957. if ((*MI)->getMinRequiredArguments() == 0)
  6958. return true;
  6959. return false;
  6960. }
  6961. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  6962. // better diagnostic if so. AT is assumed to be valid.
  6963. // Returns true when a c_str() conversion method is found.
  6964. bool CheckPrintfHandler::checkForCStrMembers(
  6965. const analyze_printf::ArgType &AT, const Expr *E) {
  6966. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6967. MethodSet Results =
  6968. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  6969. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6970. MI != ME; ++MI) {
  6971. const CXXMethodDecl *Method = *MI;
  6972. if (Method->getMinRequiredArguments() == 0 &&
  6973. AT.matchesType(S.Context, Method->getReturnType())) {
  6974. // FIXME: Suggest parens if the expression needs them.
  6975. SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
  6976. S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
  6977. << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  6978. return true;
  6979. }
  6980. }
  6981. return false;
  6982. }
  6983. bool
  6984. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  6985. &FS,
  6986. const char *startSpecifier,
  6987. unsigned specifierLen) {
  6988. using namespace analyze_format_string;
  6989. using namespace analyze_printf;
  6990. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  6991. if (FS.consumesDataArgument()) {
  6992. if (atFirstArg) {
  6993. atFirstArg = false;
  6994. usesPositionalArgs = FS.usesPositionalArg();
  6995. }
  6996. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  6997. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  6998. startSpecifier, specifierLen);
  6999. return false;
  7000. }
  7001. }
  7002. // First check if the field width, precision, and conversion specifier
  7003. // have matching data arguments.
  7004. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  7005. startSpecifier, specifierLen)) {
  7006. return false;
  7007. }
  7008. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  7009. startSpecifier, specifierLen)) {
  7010. return false;
  7011. }
  7012. if (!CS.consumesDataArgument()) {
  7013. // FIXME: Technically specifying a precision or field width here
  7014. // makes no sense. Worth issuing a warning at some point.
  7015. return true;
  7016. }
  7017. // Consume the argument.
  7018. unsigned argIndex = FS.getArgIndex();
  7019. if (argIndex < NumDataArgs) {
  7020. // The check to see if the argIndex is valid will come later.
  7021. // We set the bit here because we may exit early from this
  7022. // function if we encounter some other error.
  7023. CoveredArgs.set(argIndex);
  7024. }
  7025. // FreeBSD kernel extensions.
  7026. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  7027. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  7028. // We need at least two arguments.
  7029. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  7030. return false;
  7031. // Claim the second argument.
  7032. CoveredArgs.set(argIndex + 1);
  7033. // Type check the first argument (int for %b, pointer for %D)
  7034. const Expr *Ex = getDataArg(argIndex);
  7035. const analyze_printf::ArgType &AT =
  7036. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  7037. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  7038. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  7039. EmitFormatDiagnostic(
  7040. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7041. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  7042. << false << Ex->getSourceRange(),
  7043. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7044. getSpecifierRange(startSpecifier, specifierLen));
  7045. // Type check the second argument (char * for both %b and %D)
  7046. Ex = getDataArg(argIndex + 1);
  7047. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  7048. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  7049. EmitFormatDiagnostic(
  7050. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7051. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  7052. << false << Ex->getSourceRange(),
  7053. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7054. getSpecifierRange(startSpecifier, specifierLen));
  7055. return true;
  7056. }
  7057. // Check for using an Objective-C specific conversion specifier
  7058. // in a non-ObjC literal.
  7059. if (!allowsObjCArg() && CS.isObjCArg()) {
  7060. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7061. specifierLen);
  7062. }
  7063. // %P can only be used with os_log.
  7064. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  7065. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7066. specifierLen);
  7067. }
  7068. // %n is not allowed with os_log.
  7069. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  7070. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  7071. getLocationOfByte(CS.getStart()),
  7072. /*IsStringLocation*/ false,
  7073. getSpecifierRange(startSpecifier, specifierLen));
  7074. return true;
  7075. }
  7076. // Only scalars are allowed for os_trace.
  7077. if (FSType == Sema::FST_OSTrace &&
  7078. (CS.getKind() == ConversionSpecifier::PArg ||
  7079. CS.getKind() == ConversionSpecifier::sArg ||
  7080. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  7081. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7082. specifierLen);
  7083. }
  7084. // Check for use of public/private annotation outside of os_log().
  7085. if (FSType != Sema::FST_OSLog) {
  7086. if (FS.isPublic().isSet()) {
  7087. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7088. << "public",
  7089. getLocationOfByte(FS.isPublic().getPosition()),
  7090. /*IsStringLocation*/ false,
  7091. getSpecifierRange(startSpecifier, specifierLen));
  7092. }
  7093. if (FS.isPrivate().isSet()) {
  7094. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7095. << "private",
  7096. getLocationOfByte(FS.isPrivate().getPosition()),
  7097. /*IsStringLocation*/ false,
  7098. getSpecifierRange(startSpecifier, specifierLen));
  7099. }
  7100. }
  7101. // Check for invalid use of field width
  7102. if (!FS.hasValidFieldWidth()) {
  7103. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  7104. startSpecifier, specifierLen);
  7105. }
  7106. // Check for invalid use of precision
  7107. if (!FS.hasValidPrecision()) {
  7108. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  7109. startSpecifier, specifierLen);
  7110. }
  7111. // Precision is mandatory for %P specifier.
  7112. if (CS.getKind() == ConversionSpecifier::PArg &&
  7113. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  7114. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  7115. getLocationOfByte(startSpecifier),
  7116. /*IsStringLocation*/ false,
  7117. getSpecifierRange(startSpecifier, specifierLen));
  7118. }
  7119. // Check each flag does not conflict with any other component.
  7120. if (!FS.hasValidThousandsGroupingPrefix())
  7121. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  7122. if (!FS.hasValidLeadingZeros())
  7123. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  7124. if (!FS.hasValidPlusPrefix())
  7125. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  7126. if (!FS.hasValidSpacePrefix())
  7127. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  7128. if (!FS.hasValidAlternativeForm())
  7129. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  7130. if (!FS.hasValidLeftJustified())
  7131. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  7132. // Check that flags are not ignored by another flag
  7133. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  7134. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  7135. startSpecifier, specifierLen);
  7136. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  7137. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  7138. startSpecifier, specifierLen);
  7139. // Check the length modifier is valid with the given conversion specifier.
  7140. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7141. S.getLangOpts()))
  7142. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7143. diag::warn_format_nonsensical_length);
  7144. else if (!FS.hasStandardLengthModifier())
  7145. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7146. else if (!FS.hasStandardLengthConversionCombination())
  7147. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7148. diag::warn_format_non_standard_conversion_spec);
  7149. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7150. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7151. // The remaining checks depend on the data arguments.
  7152. if (HasVAListArg)
  7153. return true;
  7154. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7155. return false;
  7156. const Expr *Arg = getDataArg(argIndex);
  7157. if (!Arg)
  7158. return true;
  7159. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  7160. }
  7161. static bool requiresParensToAddCast(const Expr *E) {
  7162. // FIXME: We should have a general way to reason about operator
  7163. // precedence and whether parens are actually needed here.
  7164. // Take care of a few common cases where they aren't.
  7165. const Expr *Inside = E->IgnoreImpCasts();
  7166. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  7167. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  7168. switch (Inside->getStmtClass()) {
  7169. case Stmt::ArraySubscriptExprClass:
  7170. case Stmt::CallExprClass:
  7171. case Stmt::CharacterLiteralClass:
  7172. case Stmt::CXXBoolLiteralExprClass:
  7173. case Stmt::DeclRefExprClass:
  7174. case Stmt::FloatingLiteralClass:
  7175. case Stmt::IntegerLiteralClass:
  7176. case Stmt::MemberExprClass:
  7177. case Stmt::ObjCArrayLiteralClass:
  7178. case Stmt::ObjCBoolLiteralExprClass:
  7179. case Stmt::ObjCBoxedExprClass:
  7180. case Stmt::ObjCDictionaryLiteralClass:
  7181. case Stmt::ObjCEncodeExprClass:
  7182. case Stmt::ObjCIvarRefExprClass:
  7183. case Stmt::ObjCMessageExprClass:
  7184. case Stmt::ObjCPropertyRefExprClass:
  7185. case Stmt::ObjCStringLiteralClass:
  7186. case Stmt::ObjCSubscriptRefExprClass:
  7187. case Stmt::ParenExprClass:
  7188. case Stmt::StringLiteralClass:
  7189. case Stmt::UnaryOperatorClass:
  7190. return false;
  7191. default:
  7192. return true;
  7193. }
  7194. }
  7195. static std::pair<QualType, StringRef>
  7196. shouldNotPrintDirectly(const ASTContext &Context,
  7197. QualType IntendedTy,
  7198. const Expr *E) {
  7199. // Use a 'while' to peel off layers of typedefs.
  7200. QualType TyTy = IntendedTy;
  7201. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  7202. StringRef Name = UserTy->getDecl()->getName();
  7203. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  7204. .Case("CFIndex", Context.getNSIntegerType())
  7205. .Case("NSInteger", Context.getNSIntegerType())
  7206. .Case("NSUInteger", Context.getNSUIntegerType())
  7207. .Case("SInt32", Context.IntTy)
  7208. .Case("UInt32", Context.UnsignedIntTy)
  7209. .Default(QualType());
  7210. if (!CastTy.isNull())
  7211. return std::make_pair(CastTy, Name);
  7212. TyTy = UserTy->desugar();
  7213. }
  7214. // Strip parens if necessary.
  7215. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  7216. return shouldNotPrintDirectly(Context,
  7217. PE->getSubExpr()->getType(),
  7218. PE->getSubExpr());
  7219. // If this is a conditional expression, then its result type is constructed
  7220. // via usual arithmetic conversions and thus there might be no necessary
  7221. // typedef sugar there. Recurse to operands to check for NSInteger &
  7222. // Co. usage condition.
  7223. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  7224. QualType TrueTy, FalseTy;
  7225. StringRef TrueName, FalseName;
  7226. std::tie(TrueTy, TrueName) =
  7227. shouldNotPrintDirectly(Context,
  7228. CO->getTrueExpr()->getType(),
  7229. CO->getTrueExpr());
  7230. std::tie(FalseTy, FalseName) =
  7231. shouldNotPrintDirectly(Context,
  7232. CO->getFalseExpr()->getType(),
  7233. CO->getFalseExpr());
  7234. if (TrueTy == FalseTy)
  7235. return std::make_pair(TrueTy, TrueName);
  7236. else if (TrueTy.isNull())
  7237. return std::make_pair(FalseTy, FalseName);
  7238. else if (FalseTy.isNull())
  7239. return std::make_pair(TrueTy, TrueName);
  7240. }
  7241. return std::make_pair(QualType(), StringRef());
  7242. }
  7243. /// Return true if \p ICE is an implicit argument promotion of an arithmetic
  7244. /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
  7245. /// type do not count.
  7246. static bool
  7247. isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
  7248. QualType From = ICE->getSubExpr()->getType();
  7249. QualType To = ICE->getType();
  7250. // It's an integer promotion if the destination type is the promoted
  7251. // source type.
  7252. if (ICE->getCastKind() == CK_IntegralCast &&
  7253. From->isPromotableIntegerType() &&
  7254. S.Context.getPromotedIntegerType(From) == To)
  7255. return true;
  7256. // Look through vector types, since we do default argument promotion for
  7257. // those in OpenCL.
  7258. if (const auto *VecTy = From->getAs<ExtVectorType>())
  7259. From = VecTy->getElementType();
  7260. if (const auto *VecTy = To->getAs<ExtVectorType>())
  7261. To = VecTy->getElementType();
  7262. // It's a floating promotion if the source type is a lower rank.
  7263. return ICE->getCastKind() == CK_FloatingCast &&
  7264. S.Context.getFloatingTypeOrder(From, To) < 0;
  7265. }
  7266. bool
  7267. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  7268. const char *StartSpecifier,
  7269. unsigned SpecifierLen,
  7270. const Expr *E) {
  7271. using namespace analyze_format_string;
  7272. using namespace analyze_printf;
  7273. // Now type check the data expression that matches the
  7274. // format specifier.
  7275. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  7276. if (!AT.isValid())
  7277. return true;
  7278. QualType ExprTy = E->getType();
  7279. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  7280. ExprTy = TET->getUnderlyingExpr()->getType();
  7281. }
  7282. const analyze_printf::ArgType::MatchKind Match =
  7283. AT.matchesType(S.Context, ExprTy);
  7284. bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
  7285. if (Match == analyze_printf::ArgType::Match)
  7286. return true;
  7287. // Look through argument promotions for our error message's reported type.
  7288. // This includes the integral and floating promotions, but excludes array
  7289. // and function pointer decay (seeing that an argument intended to be a
  7290. // string has type 'char [6]' is probably more confusing than 'char *') and
  7291. // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
  7292. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  7293. if (isArithmeticArgumentPromotion(S, ICE)) {
  7294. E = ICE->getSubExpr();
  7295. ExprTy = E->getType();
  7296. // Check if we didn't match because of an implicit cast from a 'char'
  7297. // or 'short' to an 'int'. This is done because printf is a varargs
  7298. // function.
  7299. if (ICE->getType() == S.Context.IntTy ||
  7300. ICE->getType() == S.Context.UnsignedIntTy) {
  7301. // All further checking is done on the subexpression.
  7302. if (AT.matchesType(S.Context, ExprTy))
  7303. return true;
  7304. }
  7305. }
  7306. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  7307. // Special case for 'a', which has type 'int' in C.
  7308. // Note, however, that we do /not/ want to treat multibyte constants like
  7309. // 'MooV' as characters! This form is deprecated but still exists.
  7310. if (ExprTy == S.Context.IntTy)
  7311. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  7312. ExprTy = S.Context.CharTy;
  7313. }
  7314. // Look through enums to their underlying type.
  7315. bool IsEnum = false;
  7316. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  7317. ExprTy = EnumTy->getDecl()->getIntegerType();
  7318. IsEnum = true;
  7319. }
  7320. // %C in an Objective-C context prints a unichar, not a wchar_t.
  7321. // If the argument is an integer of some kind, believe the %C and suggest
  7322. // a cast instead of changing the conversion specifier.
  7323. QualType IntendedTy = ExprTy;
  7324. if (isObjCContext() &&
  7325. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  7326. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  7327. !ExprTy->isCharType()) {
  7328. // 'unichar' is defined as a typedef of unsigned short, but we should
  7329. // prefer using the typedef if it is visible.
  7330. IntendedTy = S.Context.UnsignedShortTy;
  7331. // While we are here, check if the value is an IntegerLiteral that happens
  7332. // to be within the valid range.
  7333. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  7334. const llvm::APInt &V = IL->getValue();
  7335. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  7336. return true;
  7337. }
  7338. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
  7339. Sema::LookupOrdinaryName);
  7340. if (S.LookupName(Result, S.getCurScope())) {
  7341. NamedDecl *ND = Result.getFoundDecl();
  7342. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  7343. if (TD->getUnderlyingType() == IntendedTy)
  7344. IntendedTy = S.Context.getTypedefType(TD);
  7345. }
  7346. }
  7347. }
  7348. // Special-case some of Darwin's platform-independence types by suggesting
  7349. // casts to primitive types that are known to be large enough.
  7350. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  7351. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  7352. QualType CastTy;
  7353. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  7354. if (!CastTy.isNull()) {
  7355. // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
  7356. // (long in ASTContext). Only complain to pedants.
  7357. if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
  7358. (AT.isSizeT() || AT.isPtrdiffT()) &&
  7359. AT.matchesType(S.Context, CastTy))
  7360. Pedantic = true;
  7361. IntendedTy = CastTy;
  7362. ShouldNotPrintDirectly = true;
  7363. }
  7364. }
  7365. // We may be able to offer a FixItHint if it is a supported type.
  7366. PrintfSpecifier fixedFS = FS;
  7367. bool Success =
  7368. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  7369. if (Success) {
  7370. // Get the fix string from the fixed format specifier
  7371. SmallString<16> buf;
  7372. llvm::raw_svector_ostream os(buf);
  7373. fixedFS.toString(os);
  7374. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  7375. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  7376. unsigned Diag =
  7377. Pedantic
  7378. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7379. : diag::warn_format_conversion_argument_type_mismatch;
  7380. // In this case, the specifier is wrong and should be changed to match
  7381. // the argument.
  7382. EmitFormatDiagnostic(S.PDiag(Diag)
  7383. << AT.getRepresentativeTypeName(S.Context)
  7384. << IntendedTy << IsEnum << E->getSourceRange(),
  7385. E->getBeginLoc(),
  7386. /*IsStringLocation*/ false, SpecRange,
  7387. FixItHint::CreateReplacement(SpecRange, os.str()));
  7388. } else {
  7389. // The canonical type for formatting this value is different from the
  7390. // actual type of the expression. (This occurs, for example, with Darwin's
  7391. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  7392. // should be printed as 'long' for 64-bit compatibility.)
  7393. // Rather than emitting a normal format/argument mismatch, we want to
  7394. // add a cast to the recommended type (and correct the format string
  7395. // if necessary).
  7396. SmallString<16> CastBuf;
  7397. llvm::raw_svector_ostream CastFix(CastBuf);
  7398. CastFix << "(";
  7399. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  7400. CastFix << ")";
  7401. SmallVector<FixItHint,4> Hints;
  7402. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  7403. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  7404. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  7405. // If there's already a cast present, just replace it.
  7406. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  7407. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  7408. } else if (!requiresParensToAddCast(E)) {
  7409. // If the expression has high enough precedence,
  7410. // just write the C-style cast.
  7411. Hints.push_back(
  7412. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7413. } else {
  7414. // Otherwise, add parens around the expression as well as the cast.
  7415. CastFix << "(";
  7416. Hints.push_back(
  7417. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7418. SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
  7419. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  7420. }
  7421. if (ShouldNotPrintDirectly) {
  7422. // The expression has a type that should not be printed directly.
  7423. // We extract the name from the typedef because we don't want to show
  7424. // the underlying type in the diagnostic.
  7425. StringRef Name;
  7426. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  7427. Name = TypedefTy->getDecl()->getName();
  7428. else
  7429. Name = CastTyName;
  7430. unsigned Diag = Pedantic
  7431. ? diag::warn_format_argument_needs_cast_pedantic
  7432. : diag::warn_format_argument_needs_cast;
  7433. EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
  7434. << E->getSourceRange(),
  7435. E->getBeginLoc(), /*IsStringLocation=*/false,
  7436. SpecRange, Hints);
  7437. } else {
  7438. // In this case, the expression could be printed using a different
  7439. // specifier, but we've decided that the specifier is probably correct
  7440. // and we should cast instead. Just use the normal warning message.
  7441. EmitFormatDiagnostic(
  7442. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7443. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  7444. << E->getSourceRange(),
  7445. E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
  7446. }
  7447. }
  7448. } else {
  7449. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  7450. SpecifierLen);
  7451. // Since the warning for passing non-POD types to variadic functions
  7452. // was deferred until now, we emit a warning for non-POD
  7453. // arguments here.
  7454. switch (S.isValidVarArgType(ExprTy)) {
  7455. case Sema::VAK_Valid:
  7456. case Sema::VAK_ValidInCXX11: {
  7457. unsigned Diag =
  7458. Pedantic
  7459. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7460. : diag::warn_format_conversion_argument_type_mismatch;
  7461. EmitFormatDiagnostic(
  7462. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  7463. << IsEnum << CSR << E->getSourceRange(),
  7464. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7465. break;
  7466. }
  7467. case Sema::VAK_Undefined:
  7468. case Sema::VAK_MSVCUndefined:
  7469. EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  7470. << S.getLangOpts().CPlusPlus11 << ExprTy
  7471. << CallType
  7472. << AT.getRepresentativeTypeName(S.Context) << CSR
  7473. << E->getSourceRange(),
  7474. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7475. checkForCStrMembers(AT, E);
  7476. break;
  7477. case Sema::VAK_Invalid:
  7478. if (ExprTy->isObjCObjectType())
  7479. EmitFormatDiagnostic(
  7480. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  7481. << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
  7482. << AT.getRepresentativeTypeName(S.Context) << CSR
  7483. << E->getSourceRange(),
  7484. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7485. else
  7486. // FIXME: If this is an initializer list, suggest removing the braces
  7487. // or inserting a cast to the target type.
  7488. S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
  7489. << isa<InitListExpr>(E) << ExprTy << CallType
  7490. << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
  7491. break;
  7492. }
  7493. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  7494. "format string specifier index out of range");
  7495. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  7496. }
  7497. return true;
  7498. }
  7499. //===--- CHECK: Scanf format string checking ------------------------------===//
  7500. namespace {
  7501. class CheckScanfHandler : public CheckFormatHandler {
  7502. public:
  7503. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  7504. const Expr *origFormatExpr, Sema::FormatStringType type,
  7505. unsigned firstDataArg, unsigned numDataArgs,
  7506. const char *beg, bool hasVAListArg,
  7507. ArrayRef<const Expr *> Args, unsigned formatIdx,
  7508. bool inFunctionCall, Sema::VariadicCallType CallType,
  7509. llvm::SmallBitVector &CheckedVarArgs,
  7510. UncoveredArgHandler &UncoveredArg)
  7511. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  7512. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  7513. inFunctionCall, CallType, CheckedVarArgs,
  7514. UncoveredArg) {}
  7515. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  7516. const char *startSpecifier,
  7517. unsigned specifierLen) override;
  7518. bool HandleInvalidScanfConversionSpecifier(
  7519. const analyze_scanf::ScanfSpecifier &FS,
  7520. const char *startSpecifier,
  7521. unsigned specifierLen) override;
  7522. void HandleIncompleteScanList(const char *start, const char *end) override;
  7523. };
  7524. } // namespace
  7525. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  7526. const char *end) {
  7527. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  7528. getLocationOfByte(end), /*IsStringLocation*/true,
  7529. getSpecifierRange(start, end - start));
  7530. }
  7531. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  7532. const analyze_scanf::ScanfSpecifier &FS,
  7533. const char *startSpecifier,
  7534. unsigned specifierLen) {
  7535. const analyze_scanf::ScanfConversionSpecifier &CS =
  7536. FS.getConversionSpecifier();
  7537. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  7538. getLocationOfByte(CS.getStart()),
  7539. startSpecifier, specifierLen,
  7540. CS.getStart(), CS.getLength());
  7541. }
  7542. bool CheckScanfHandler::HandleScanfSpecifier(
  7543. const analyze_scanf::ScanfSpecifier &FS,
  7544. const char *startSpecifier,
  7545. unsigned specifierLen) {
  7546. using namespace analyze_scanf;
  7547. using namespace analyze_format_string;
  7548. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  7549. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  7550. // be used to decide if we are using positional arguments consistently.
  7551. if (FS.consumesDataArgument()) {
  7552. if (atFirstArg) {
  7553. atFirstArg = false;
  7554. usesPositionalArgs = FS.usesPositionalArg();
  7555. }
  7556. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7557. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7558. startSpecifier, specifierLen);
  7559. return false;
  7560. }
  7561. }
  7562. // Check if the field with is non-zero.
  7563. const OptionalAmount &Amt = FS.getFieldWidth();
  7564. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  7565. if (Amt.getConstantAmount() == 0) {
  7566. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  7567. Amt.getConstantLength());
  7568. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  7569. getLocationOfByte(Amt.getStart()),
  7570. /*IsStringLocation*/true, R,
  7571. FixItHint::CreateRemoval(R));
  7572. }
  7573. }
  7574. if (!FS.consumesDataArgument()) {
  7575. // FIXME: Technically specifying a precision or field width here
  7576. // makes no sense. Worth issuing a warning at some point.
  7577. return true;
  7578. }
  7579. // Consume the argument.
  7580. unsigned argIndex = FS.getArgIndex();
  7581. if (argIndex < NumDataArgs) {
  7582. // The check to see if the argIndex is valid will come later.
  7583. // We set the bit here because we may exit early from this
  7584. // function if we encounter some other error.
  7585. CoveredArgs.set(argIndex);
  7586. }
  7587. // Check the length modifier is valid with the given conversion specifier.
  7588. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7589. S.getLangOpts()))
  7590. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7591. diag::warn_format_nonsensical_length);
  7592. else if (!FS.hasStandardLengthModifier())
  7593. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7594. else if (!FS.hasStandardLengthConversionCombination())
  7595. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7596. diag::warn_format_non_standard_conversion_spec);
  7597. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7598. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7599. // The remaining checks depend on the data arguments.
  7600. if (HasVAListArg)
  7601. return true;
  7602. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7603. return false;
  7604. // Check that the argument type matches the format specifier.
  7605. const Expr *Ex = getDataArg(argIndex);
  7606. if (!Ex)
  7607. return true;
  7608. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  7609. if (!AT.isValid()) {
  7610. return true;
  7611. }
  7612. analyze_format_string::ArgType::MatchKind Match =
  7613. AT.matchesType(S.Context, Ex->getType());
  7614. bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
  7615. if (Match == analyze_format_string::ArgType::Match)
  7616. return true;
  7617. ScanfSpecifier fixedFS = FS;
  7618. bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  7619. S.getLangOpts(), S.Context);
  7620. unsigned Diag =
  7621. Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7622. : diag::warn_format_conversion_argument_type_mismatch;
  7623. if (Success) {
  7624. // Get the fix string from the fixed format specifier.
  7625. SmallString<128> buf;
  7626. llvm::raw_svector_ostream os(buf);
  7627. fixedFS.toString(os);
  7628. EmitFormatDiagnostic(
  7629. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
  7630. << Ex->getType() << false << Ex->getSourceRange(),
  7631. Ex->getBeginLoc(),
  7632. /*IsStringLocation*/ false,
  7633. getSpecifierRange(startSpecifier, specifierLen),
  7634. FixItHint::CreateReplacement(
  7635. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  7636. } else {
  7637. EmitFormatDiagnostic(S.PDiag(Diag)
  7638. << AT.getRepresentativeTypeName(S.Context)
  7639. << Ex->getType() << false << Ex->getSourceRange(),
  7640. Ex->getBeginLoc(),
  7641. /*IsStringLocation*/ false,
  7642. getSpecifierRange(startSpecifier, specifierLen));
  7643. }
  7644. return true;
  7645. }
  7646. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  7647. const Expr *OrigFormatExpr,
  7648. ArrayRef<const Expr *> Args,
  7649. bool HasVAListArg, unsigned format_idx,
  7650. unsigned firstDataArg,
  7651. Sema::FormatStringType Type,
  7652. bool inFunctionCall,
  7653. Sema::VariadicCallType CallType,
  7654. llvm::SmallBitVector &CheckedVarArgs,
  7655. UncoveredArgHandler &UncoveredArg) {
  7656. // CHECK: is the format string a wide literal?
  7657. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  7658. CheckFormatHandler::EmitFormatDiagnostic(
  7659. S, inFunctionCall, Args[format_idx],
  7660. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
  7661. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7662. return;
  7663. }
  7664. // Str - The format string. NOTE: this is NOT null-terminated!
  7665. StringRef StrRef = FExpr->getString();
  7666. const char *Str = StrRef.data();
  7667. // Account for cases where the string literal is truncated in a declaration.
  7668. const ConstantArrayType *T =
  7669. S.Context.getAsConstantArrayType(FExpr->getType());
  7670. assert(T && "String literal not of constant array type!");
  7671. size_t TypeSize = T->getSize().getZExtValue();
  7672. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7673. const unsigned numDataArgs = Args.size() - firstDataArg;
  7674. // Emit a warning if the string literal is truncated and does not contain an
  7675. // embedded null character.
  7676. if (TypeSize <= StrRef.size() &&
  7677. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  7678. CheckFormatHandler::EmitFormatDiagnostic(
  7679. S, inFunctionCall, Args[format_idx],
  7680. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  7681. FExpr->getBeginLoc(),
  7682. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  7683. return;
  7684. }
  7685. // CHECK: empty format string?
  7686. if (StrLen == 0 && numDataArgs > 0) {
  7687. CheckFormatHandler::EmitFormatDiagnostic(
  7688. S, inFunctionCall, Args[format_idx],
  7689. S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
  7690. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7691. return;
  7692. }
  7693. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  7694. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  7695. Type == Sema::FST_OSTrace) {
  7696. CheckPrintfHandler H(
  7697. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  7698. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  7699. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  7700. CheckedVarArgs, UncoveredArg);
  7701. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  7702. S.getLangOpts(),
  7703. S.Context.getTargetInfo(),
  7704. Type == Sema::FST_FreeBSDKPrintf))
  7705. H.DoneProcessing();
  7706. } else if (Type == Sema::FST_Scanf) {
  7707. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  7708. numDataArgs, Str, HasVAListArg, Args, format_idx,
  7709. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  7710. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  7711. S.getLangOpts(),
  7712. S.Context.getTargetInfo()))
  7713. H.DoneProcessing();
  7714. } // TODO: handle other formats
  7715. }
  7716. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  7717. // Str - The format string. NOTE: this is NOT null-terminated!
  7718. StringRef StrRef = FExpr->getString();
  7719. const char *Str = StrRef.data();
  7720. // Account for cases where the string literal is truncated in a declaration.
  7721. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  7722. assert(T && "String literal not of constant array type!");
  7723. size_t TypeSize = T->getSize().getZExtValue();
  7724. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7725. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  7726. getLangOpts(),
  7727. Context.getTargetInfo());
  7728. }
  7729. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  7730. // Returns the related absolute value function that is larger, of 0 if one
  7731. // does not exist.
  7732. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  7733. switch (AbsFunction) {
  7734. default:
  7735. return 0;
  7736. case Builtin::BI__builtin_abs:
  7737. return Builtin::BI__builtin_labs;
  7738. case Builtin::BI__builtin_labs:
  7739. return Builtin::BI__builtin_llabs;
  7740. case Builtin::BI__builtin_llabs:
  7741. return 0;
  7742. case Builtin::BI__builtin_fabsf:
  7743. return Builtin::BI__builtin_fabs;
  7744. case Builtin::BI__builtin_fabs:
  7745. return Builtin::BI__builtin_fabsl;
  7746. case Builtin::BI__builtin_fabsl:
  7747. return 0;
  7748. case Builtin::BI__builtin_cabsf:
  7749. return Builtin::BI__builtin_cabs;
  7750. case Builtin::BI__builtin_cabs:
  7751. return Builtin::BI__builtin_cabsl;
  7752. case Builtin::BI__builtin_cabsl:
  7753. return 0;
  7754. case Builtin::BIabs:
  7755. return Builtin::BIlabs;
  7756. case Builtin::BIlabs:
  7757. return Builtin::BIllabs;
  7758. case Builtin::BIllabs:
  7759. return 0;
  7760. case Builtin::BIfabsf:
  7761. return Builtin::BIfabs;
  7762. case Builtin::BIfabs:
  7763. return Builtin::BIfabsl;
  7764. case Builtin::BIfabsl:
  7765. return 0;
  7766. case Builtin::BIcabsf:
  7767. return Builtin::BIcabs;
  7768. case Builtin::BIcabs:
  7769. return Builtin::BIcabsl;
  7770. case Builtin::BIcabsl:
  7771. return 0;
  7772. }
  7773. }
  7774. // Returns the argument type of the absolute value function.
  7775. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  7776. unsigned AbsType) {
  7777. if (AbsType == 0)
  7778. return QualType();
  7779. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  7780. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  7781. if (Error != ASTContext::GE_None)
  7782. return QualType();
  7783. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  7784. if (!FT)
  7785. return QualType();
  7786. if (FT->getNumParams() != 1)
  7787. return QualType();
  7788. return FT->getParamType(0);
  7789. }
  7790. // Returns the best absolute value function, or zero, based on type and
  7791. // current absolute value function.
  7792. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  7793. unsigned AbsFunctionKind) {
  7794. unsigned BestKind = 0;
  7795. uint64_t ArgSize = Context.getTypeSize(ArgType);
  7796. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  7797. Kind = getLargerAbsoluteValueFunction(Kind)) {
  7798. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  7799. if (Context.getTypeSize(ParamType) >= ArgSize) {
  7800. if (BestKind == 0)
  7801. BestKind = Kind;
  7802. else if (Context.hasSameType(ParamType, ArgType)) {
  7803. BestKind = Kind;
  7804. break;
  7805. }
  7806. }
  7807. }
  7808. return BestKind;
  7809. }
  7810. enum AbsoluteValueKind {
  7811. AVK_Integer,
  7812. AVK_Floating,
  7813. AVK_Complex
  7814. };
  7815. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  7816. if (T->isIntegralOrEnumerationType())
  7817. return AVK_Integer;
  7818. if (T->isRealFloatingType())
  7819. return AVK_Floating;
  7820. if (T->isAnyComplexType())
  7821. return AVK_Complex;
  7822. llvm_unreachable("Type not integer, floating, or complex");
  7823. }
  7824. // Changes the absolute value function to a different type. Preserves whether
  7825. // the function is a builtin.
  7826. static unsigned changeAbsFunction(unsigned AbsKind,
  7827. AbsoluteValueKind ValueKind) {
  7828. switch (ValueKind) {
  7829. case AVK_Integer:
  7830. switch (AbsKind) {
  7831. default:
  7832. return 0;
  7833. case Builtin::BI__builtin_fabsf:
  7834. case Builtin::BI__builtin_fabs:
  7835. case Builtin::BI__builtin_fabsl:
  7836. case Builtin::BI__builtin_cabsf:
  7837. case Builtin::BI__builtin_cabs:
  7838. case Builtin::BI__builtin_cabsl:
  7839. return Builtin::BI__builtin_abs;
  7840. case Builtin::BIfabsf:
  7841. case Builtin::BIfabs:
  7842. case Builtin::BIfabsl:
  7843. case Builtin::BIcabsf:
  7844. case Builtin::BIcabs:
  7845. case Builtin::BIcabsl:
  7846. return Builtin::BIabs;
  7847. }
  7848. case AVK_Floating:
  7849. switch (AbsKind) {
  7850. default:
  7851. return 0;
  7852. case Builtin::BI__builtin_abs:
  7853. case Builtin::BI__builtin_labs:
  7854. case Builtin::BI__builtin_llabs:
  7855. case Builtin::BI__builtin_cabsf:
  7856. case Builtin::BI__builtin_cabs:
  7857. case Builtin::BI__builtin_cabsl:
  7858. return Builtin::BI__builtin_fabsf;
  7859. case Builtin::BIabs:
  7860. case Builtin::BIlabs:
  7861. case Builtin::BIllabs:
  7862. case Builtin::BIcabsf:
  7863. case Builtin::BIcabs:
  7864. case Builtin::BIcabsl:
  7865. return Builtin::BIfabsf;
  7866. }
  7867. case AVK_Complex:
  7868. switch (AbsKind) {
  7869. default:
  7870. return 0;
  7871. case Builtin::BI__builtin_abs:
  7872. case Builtin::BI__builtin_labs:
  7873. case Builtin::BI__builtin_llabs:
  7874. case Builtin::BI__builtin_fabsf:
  7875. case Builtin::BI__builtin_fabs:
  7876. case Builtin::BI__builtin_fabsl:
  7877. return Builtin::BI__builtin_cabsf;
  7878. case Builtin::BIabs:
  7879. case Builtin::BIlabs:
  7880. case Builtin::BIllabs:
  7881. case Builtin::BIfabsf:
  7882. case Builtin::BIfabs:
  7883. case Builtin::BIfabsl:
  7884. return Builtin::BIcabsf;
  7885. }
  7886. }
  7887. llvm_unreachable("Unable to convert function");
  7888. }
  7889. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  7890. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  7891. if (!FnInfo)
  7892. return 0;
  7893. switch (FDecl->getBuiltinID()) {
  7894. default:
  7895. return 0;
  7896. case Builtin::BI__builtin_abs:
  7897. case Builtin::BI__builtin_fabs:
  7898. case Builtin::BI__builtin_fabsf:
  7899. case Builtin::BI__builtin_fabsl:
  7900. case Builtin::BI__builtin_labs:
  7901. case Builtin::BI__builtin_llabs:
  7902. case Builtin::BI__builtin_cabs:
  7903. case Builtin::BI__builtin_cabsf:
  7904. case Builtin::BI__builtin_cabsl:
  7905. case Builtin::BIabs:
  7906. case Builtin::BIlabs:
  7907. case Builtin::BIllabs:
  7908. case Builtin::BIfabs:
  7909. case Builtin::BIfabsf:
  7910. case Builtin::BIfabsl:
  7911. case Builtin::BIcabs:
  7912. case Builtin::BIcabsf:
  7913. case Builtin::BIcabsl:
  7914. return FDecl->getBuiltinID();
  7915. }
  7916. llvm_unreachable("Unknown Builtin type");
  7917. }
  7918. // If the replacement is valid, emit a note with replacement function.
  7919. // Additionally, suggest including the proper header if not already included.
  7920. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  7921. unsigned AbsKind, QualType ArgType) {
  7922. bool EmitHeaderHint = true;
  7923. const char *HeaderName = nullptr;
  7924. const char *FunctionName = nullptr;
  7925. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  7926. FunctionName = "std::abs";
  7927. if (ArgType->isIntegralOrEnumerationType()) {
  7928. HeaderName = "cstdlib";
  7929. } else if (ArgType->isRealFloatingType()) {
  7930. HeaderName = "cmath";
  7931. } else {
  7932. llvm_unreachable("Invalid Type");
  7933. }
  7934. // Lookup all std::abs
  7935. if (NamespaceDecl *Std = S.getStdNamespace()) {
  7936. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  7937. R.suppressDiagnostics();
  7938. S.LookupQualifiedName(R, Std);
  7939. for (const auto *I : R) {
  7940. const FunctionDecl *FDecl = nullptr;
  7941. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  7942. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  7943. } else {
  7944. FDecl = dyn_cast<FunctionDecl>(I);
  7945. }
  7946. if (!FDecl)
  7947. continue;
  7948. // Found std::abs(), check that they are the right ones.
  7949. if (FDecl->getNumParams() != 1)
  7950. continue;
  7951. // Check that the parameter type can handle the argument.
  7952. QualType ParamType = FDecl->getParamDecl(0)->getType();
  7953. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  7954. S.Context.getTypeSize(ArgType) <=
  7955. S.Context.getTypeSize(ParamType)) {
  7956. // Found a function, don't need the header hint.
  7957. EmitHeaderHint = false;
  7958. break;
  7959. }
  7960. }
  7961. }
  7962. } else {
  7963. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  7964. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  7965. if (HeaderName) {
  7966. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  7967. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  7968. R.suppressDiagnostics();
  7969. S.LookupName(R, S.getCurScope());
  7970. if (R.isSingleResult()) {
  7971. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  7972. if (FD && FD->getBuiltinID() == AbsKind) {
  7973. EmitHeaderHint = false;
  7974. } else {
  7975. return;
  7976. }
  7977. } else if (!R.empty()) {
  7978. return;
  7979. }
  7980. }
  7981. }
  7982. S.Diag(Loc, diag::note_replace_abs_function)
  7983. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  7984. if (!HeaderName)
  7985. return;
  7986. if (!EmitHeaderHint)
  7987. return;
  7988. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  7989. << FunctionName;
  7990. }
  7991. template <std::size_t StrLen>
  7992. static bool IsStdFunction(const FunctionDecl *FDecl,
  7993. const char (&Str)[StrLen]) {
  7994. if (!FDecl)
  7995. return false;
  7996. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  7997. return false;
  7998. if (!FDecl->isInStdNamespace())
  7999. return false;
  8000. return true;
  8001. }
  8002. // Warn when using the wrong abs() function.
  8003. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  8004. const FunctionDecl *FDecl) {
  8005. if (Call->getNumArgs() != 1)
  8006. return;
  8007. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  8008. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  8009. if (AbsKind == 0 && !IsStdAbs)
  8010. return;
  8011. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8012. QualType ParamType = Call->getArg(0)->getType();
  8013. // Unsigned types cannot be negative. Suggest removing the absolute value
  8014. // function call.
  8015. if (ArgType->isUnsignedIntegerType()) {
  8016. const char *FunctionName =
  8017. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  8018. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  8019. Diag(Call->getExprLoc(), diag::note_remove_abs)
  8020. << FunctionName
  8021. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  8022. return;
  8023. }
  8024. // Taking the absolute value of a pointer is very suspicious, they probably
  8025. // wanted to index into an array, dereference a pointer, call a function, etc.
  8026. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  8027. unsigned DiagType = 0;
  8028. if (ArgType->isFunctionType())
  8029. DiagType = 1;
  8030. else if (ArgType->isArrayType())
  8031. DiagType = 2;
  8032. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  8033. return;
  8034. }
  8035. // std::abs has overloads which prevent most of the absolute value problems
  8036. // from occurring.
  8037. if (IsStdAbs)
  8038. return;
  8039. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  8040. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  8041. // The argument and parameter are the same kind. Check if they are the right
  8042. // size.
  8043. if (ArgValueKind == ParamValueKind) {
  8044. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  8045. return;
  8046. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  8047. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  8048. << FDecl << ArgType << ParamType;
  8049. if (NewAbsKind == 0)
  8050. return;
  8051. emitReplacement(*this, Call->getExprLoc(),
  8052. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8053. return;
  8054. }
  8055. // ArgValueKind != ParamValueKind
  8056. // The wrong type of absolute value function was used. Attempt to find the
  8057. // proper one.
  8058. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  8059. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  8060. if (NewAbsKind == 0)
  8061. return;
  8062. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  8063. << FDecl << ParamValueKind << ArgValueKind;
  8064. emitReplacement(*this, Call->getExprLoc(),
  8065. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8066. }
  8067. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  8068. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  8069. const FunctionDecl *FDecl) {
  8070. if (!Call || !FDecl) return;
  8071. // Ignore template specializations and macros.
  8072. if (inTemplateInstantiation()) return;
  8073. if (Call->getExprLoc().isMacroID()) return;
  8074. // Only care about the one template argument, two function parameter std::max
  8075. if (Call->getNumArgs() != 2) return;
  8076. if (!IsStdFunction(FDecl, "max")) return;
  8077. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  8078. if (!ArgList) return;
  8079. if (ArgList->size() != 1) return;
  8080. // Check that template type argument is unsigned integer.
  8081. const auto& TA = ArgList->get(0);
  8082. if (TA.getKind() != TemplateArgument::Type) return;
  8083. QualType ArgType = TA.getAsType();
  8084. if (!ArgType->isUnsignedIntegerType()) return;
  8085. // See if either argument is a literal zero.
  8086. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  8087. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  8088. if (!MTE) return false;
  8089. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  8090. if (!Num) return false;
  8091. if (Num->getValue() != 0) return false;
  8092. return true;
  8093. };
  8094. const Expr *FirstArg = Call->getArg(0);
  8095. const Expr *SecondArg = Call->getArg(1);
  8096. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  8097. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  8098. // Only warn when exactly one argument is zero.
  8099. if (IsFirstArgZero == IsSecondArgZero) return;
  8100. SourceRange FirstRange = FirstArg->getSourceRange();
  8101. SourceRange SecondRange = SecondArg->getSourceRange();
  8102. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  8103. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  8104. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  8105. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  8106. SourceRange RemovalRange;
  8107. if (IsFirstArgZero) {
  8108. RemovalRange = SourceRange(FirstRange.getBegin(),
  8109. SecondRange.getBegin().getLocWithOffset(-1));
  8110. } else {
  8111. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  8112. SecondRange.getEnd());
  8113. }
  8114. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  8115. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  8116. << FixItHint::CreateRemoval(RemovalRange);
  8117. }
  8118. //===--- CHECK: Standard memory functions ---------------------------------===//
  8119. /// Takes the expression passed to the size_t parameter of functions
  8120. /// such as memcmp, strncat, etc and warns if it's a comparison.
  8121. ///
  8122. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  8123. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  8124. IdentifierInfo *FnName,
  8125. SourceLocation FnLoc,
  8126. SourceLocation RParenLoc) {
  8127. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  8128. if (!Size)
  8129. return false;
  8130. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  8131. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  8132. return false;
  8133. SourceRange SizeRange = Size->getSourceRange();
  8134. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  8135. << SizeRange << FnName;
  8136. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  8137. << FnName
  8138. << FixItHint::CreateInsertion(
  8139. S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
  8140. << FixItHint::CreateRemoval(RParenLoc);
  8141. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  8142. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  8143. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  8144. ")");
  8145. return true;
  8146. }
  8147. /// Determine whether the given type is or contains a dynamic class type
  8148. /// (e.g., whether it has a vtable).
  8149. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  8150. bool &IsContained) {
  8151. // Look through array types while ignoring qualifiers.
  8152. const Type *Ty = T->getBaseElementTypeUnsafe();
  8153. IsContained = false;
  8154. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  8155. RD = RD ? RD->getDefinition() : nullptr;
  8156. if (!RD || RD->isInvalidDecl())
  8157. return nullptr;
  8158. if (RD->isDynamicClass())
  8159. return RD;
  8160. // Check all the fields. If any bases were dynamic, the class is dynamic.
  8161. // It's impossible for a class to transitively contain itself by value, so
  8162. // infinite recursion is impossible.
  8163. for (auto *FD : RD->fields()) {
  8164. bool SubContained;
  8165. if (const CXXRecordDecl *ContainedRD =
  8166. getContainedDynamicClass(FD->getType(), SubContained)) {
  8167. IsContained = true;
  8168. return ContainedRD;
  8169. }
  8170. }
  8171. return nullptr;
  8172. }
  8173. static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
  8174. if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  8175. if (Unary->getKind() == UETT_SizeOf)
  8176. return Unary;
  8177. return nullptr;
  8178. }
  8179. /// If E is a sizeof expression, returns its argument expression,
  8180. /// otherwise returns NULL.
  8181. static const Expr *getSizeOfExprArg(const Expr *E) {
  8182. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8183. if (!SizeOf->isArgumentType())
  8184. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  8185. return nullptr;
  8186. }
  8187. /// If E is a sizeof expression, returns its argument type.
  8188. static QualType getSizeOfArgType(const Expr *E) {
  8189. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8190. return SizeOf->getTypeOfArgument();
  8191. return QualType();
  8192. }
  8193. namespace {
  8194. struct SearchNonTrivialToInitializeField
  8195. : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
  8196. using Super =
  8197. DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
  8198. SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
  8199. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
  8200. SourceLocation SL) {
  8201. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8202. asDerived().visitArray(PDIK, AT, SL);
  8203. return;
  8204. }
  8205. Super::visitWithKind(PDIK, FT, SL);
  8206. }
  8207. void visitARCStrong(QualType FT, SourceLocation SL) {
  8208. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8209. }
  8210. void visitARCWeak(QualType FT, SourceLocation SL) {
  8211. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8212. }
  8213. void visitStruct(QualType FT, SourceLocation SL) {
  8214. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8215. visit(FD->getType(), FD->getLocation());
  8216. }
  8217. void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
  8218. const ArrayType *AT, SourceLocation SL) {
  8219. visit(getContext().getBaseElementType(AT), SL);
  8220. }
  8221. void visitTrivial(QualType FT, SourceLocation SL) {}
  8222. static void diag(QualType RT, const Expr *E, Sema &S) {
  8223. SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
  8224. }
  8225. ASTContext &getContext() { return S.getASTContext(); }
  8226. const Expr *E;
  8227. Sema &S;
  8228. };
  8229. struct SearchNonTrivialToCopyField
  8230. : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
  8231. using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
  8232. SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
  8233. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
  8234. SourceLocation SL) {
  8235. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8236. asDerived().visitArray(PCK, AT, SL);
  8237. return;
  8238. }
  8239. Super::visitWithKind(PCK, FT, SL);
  8240. }
  8241. void visitARCStrong(QualType FT, SourceLocation SL) {
  8242. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8243. }
  8244. void visitARCWeak(QualType FT, SourceLocation SL) {
  8245. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8246. }
  8247. void visitStruct(QualType FT, SourceLocation SL) {
  8248. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8249. visit(FD->getType(), FD->getLocation());
  8250. }
  8251. void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
  8252. SourceLocation SL) {
  8253. visit(getContext().getBaseElementType(AT), SL);
  8254. }
  8255. void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
  8256. SourceLocation SL) {}
  8257. void visitTrivial(QualType FT, SourceLocation SL) {}
  8258. void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
  8259. static void diag(QualType RT, const Expr *E, Sema &S) {
  8260. SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
  8261. }
  8262. ASTContext &getContext() { return S.getASTContext(); }
  8263. const Expr *E;
  8264. Sema &S;
  8265. };
  8266. }
  8267. /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
  8268. static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
  8269. SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
  8270. if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
  8271. if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
  8272. return false;
  8273. return doesExprLikelyComputeSize(BO->getLHS()) ||
  8274. doesExprLikelyComputeSize(BO->getRHS());
  8275. }
  8276. return getAsSizeOfExpr(SizeofExpr) != nullptr;
  8277. }
  8278. /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
  8279. ///
  8280. /// \code
  8281. /// #define MACRO 0
  8282. /// foo(MACRO);
  8283. /// foo(0);
  8284. /// \endcode
  8285. ///
  8286. /// This should return true for the first call to foo, but not for the second
  8287. /// (regardless of whether foo is a macro or function).
  8288. static bool isArgumentExpandedFromMacro(SourceManager &SM,
  8289. SourceLocation CallLoc,
  8290. SourceLocation ArgLoc) {
  8291. if (!CallLoc.isMacroID())
  8292. return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
  8293. return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
  8294. SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
  8295. }
  8296. /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
  8297. /// last two arguments transposed.
  8298. static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
  8299. if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
  8300. return;
  8301. const Expr *SizeArg =
  8302. Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
  8303. auto isLiteralZero = [](const Expr *E) {
  8304. return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
  8305. };
  8306. // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
  8307. SourceLocation CallLoc = Call->getRParenLoc();
  8308. SourceManager &SM = S.getSourceManager();
  8309. if (isLiteralZero(SizeArg) &&
  8310. !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
  8311. SourceLocation DiagLoc = SizeArg->getExprLoc();
  8312. // Some platforms #define bzero to __builtin_memset. See if this is the
  8313. // case, and if so, emit a better diagnostic.
  8314. if (BId == Builtin::BIbzero ||
  8315. (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
  8316. CallLoc, SM, S.getLangOpts()) == "bzero")) {
  8317. S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
  8318. S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
  8319. } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
  8320. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
  8321. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
  8322. }
  8323. return;
  8324. }
  8325. // If the second argument to a memset is a sizeof expression and the third
  8326. // isn't, this is also likely an error. This should catch
  8327. // 'memset(buf, sizeof(buf), 0xff)'.
  8328. if (BId == Builtin::BImemset &&
  8329. doesExprLikelyComputeSize(Call->getArg(1)) &&
  8330. !doesExprLikelyComputeSize(Call->getArg(2))) {
  8331. SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
  8332. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
  8333. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
  8334. return;
  8335. }
  8336. }
  8337. /// Check for dangerous or invalid arguments to memset().
  8338. ///
  8339. /// This issues warnings on known problematic, dangerous or unspecified
  8340. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  8341. /// function calls.
  8342. ///
  8343. /// \param Call The call expression to diagnose.
  8344. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  8345. unsigned BId,
  8346. IdentifierInfo *FnName) {
  8347. assert(BId != 0);
  8348. // It is possible to have a non-standard definition of memset. Validate
  8349. // we have enough arguments, and if not, abort further checking.
  8350. unsigned ExpectedNumArgs =
  8351. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  8352. if (Call->getNumArgs() < ExpectedNumArgs)
  8353. return;
  8354. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  8355. BId == Builtin::BIstrndup ? 1 : 2);
  8356. unsigned LenArg =
  8357. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  8358. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  8359. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  8360. Call->getBeginLoc(), Call->getRParenLoc()))
  8361. return;
  8362. // Catch cases like 'memset(buf, sizeof(buf), 0)'.
  8363. CheckMemaccessSize(*this, BId, Call);
  8364. // We have special checking when the length is a sizeof expression.
  8365. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  8366. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  8367. llvm::FoldingSetNodeID SizeOfArgID;
  8368. // Although widely used, 'bzero' is not a standard function. Be more strict
  8369. // with the argument types before allowing diagnostics and only allow the
  8370. // form bzero(ptr, sizeof(...)).
  8371. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8372. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  8373. return;
  8374. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  8375. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  8376. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  8377. QualType DestTy = Dest->getType();
  8378. QualType PointeeTy;
  8379. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  8380. PointeeTy = DestPtrTy->getPointeeType();
  8381. // Never warn about void type pointers. This can be used to suppress
  8382. // false positives.
  8383. if (PointeeTy->isVoidType())
  8384. continue;
  8385. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  8386. // actually comparing the expressions for equality. Because computing the
  8387. // expression IDs can be expensive, we only do this if the diagnostic is
  8388. // enabled.
  8389. if (SizeOfArg &&
  8390. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  8391. SizeOfArg->getExprLoc())) {
  8392. // We only compute IDs for expressions if the warning is enabled, and
  8393. // cache the sizeof arg's ID.
  8394. if (SizeOfArgID == llvm::FoldingSetNodeID())
  8395. SizeOfArg->Profile(SizeOfArgID, Context, true);
  8396. llvm::FoldingSetNodeID DestID;
  8397. Dest->Profile(DestID, Context, true);
  8398. if (DestID == SizeOfArgID) {
  8399. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  8400. // over sizeof(src) as well.
  8401. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  8402. StringRef ReadableName = FnName->getName();
  8403. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  8404. if (UnaryOp->getOpcode() == UO_AddrOf)
  8405. ActionIdx = 1; // If its an address-of operator, just remove it.
  8406. if (!PointeeTy->isIncompleteType() &&
  8407. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  8408. ActionIdx = 2; // If the pointee's size is sizeof(char),
  8409. // suggest an explicit length.
  8410. // If the function is defined as a builtin macro, do not show macro
  8411. // expansion.
  8412. SourceLocation SL = SizeOfArg->getExprLoc();
  8413. SourceRange DSR = Dest->getSourceRange();
  8414. SourceRange SSR = SizeOfArg->getSourceRange();
  8415. SourceManager &SM = getSourceManager();
  8416. if (SM.isMacroArgExpansion(SL)) {
  8417. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  8418. SL = SM.getSpellingLoc(SL);
  8419. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  8420. SM.getSpellingLoc(DSR.getEnd()));
  8421. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  8422. SM.getSpellingLoc(SSR.getEnd()));
  8423. }
  8424. DiagRuntimeBehavior(SL, SizeOfArg,
  8425. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  8426. << ReadableName
  8427. << PointeeTy
  8428. << DestTy
  8429. << DSR
  8430. << SSR);
  8431. DiagRuntimeBehavior(SL, SizeOfArg,
  8432. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  8433. << ActionIdx
  8434. << SSR);
  8435. break;
  8436. }
  8437. }
  8438. // Also check for cases where the sizeof argument is the exact same
  8439. // type as the memory argument, and where it points to a user-defined
  8440. // record type.
  8441. if (SizeOfArgTy != QualType()) {
  8442. if (PointeeTy->isRecordType() &&
  8443. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  8444. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  8445. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  8446. << FnName << SizeOfArgTy << ArgIdx
  8447. << PointeeTy << Dest->getSourceRange()
  8448. << LenExpr->getSourceRange());
  8449. break;
  8450. }
  8451. }
  8452. } else if (DestTy->isArrayType()) {
  8453. PointeeTy = DestTy;
  8454. }
  8455. if (PointeeTy == QualType())
  8456. continue;
  8457. // Always complain about dynamic classes.
  8458. bool IsContained;
  8459. if (const CXXRecordDecl *ContainedRD =
  8460. getContainedDynamicClass(PointeeTy, IsContained)) {
  8461. unsigned OperationType = 0;
  8462. const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
  8463. // "overwritten" if we're warning about the destination for any call
  8464. // but memcmp; otherwise a verb appropriate to the call.
  8465. if (ArgIdx != 0 || IsCmp) {
  8466. if (BId == Builtin::BImemcpy)
  8467. OperationType = 1;
  8468. else if(BId == Builtin::BImemmove)
  8469. OperationType = 2;
  8470. else if (IsCmp)
  8471. OperationType = 3;
  8472. }
  8473. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8474. PDiag(diag::warn_dyn_class_memaccess)
  8475. << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
  8476. << IsContained << ContainedRD << OperationType
  8477. << Call->getCallee()->getSourceRange());
  8478. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  8479. BId != Builtin::BImemset)
  8480. DiagRuntimeBehavior(
  8481. Dest->getExprLoc(), Dest,
  8482. PDiag(diag::warn_arc_object_memaccess)
  8483. << ArgIdx << FnName << PointeeTy
  8484. << Call->getCallee()->getSourceRange());
  8485. else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
  8486. if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
  8487. RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
  8488. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8489. PDiag(diag::warn_cstruct_memaccess)
  8490. << ArgIdx << FnName << PointeeTy << 0);
  8491. SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
  8492. } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  8493. RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
  8494. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8495. PDiag(diag::warn_cstruct_memaccess)
  8496. << ArgIdx << FnName << PointeeTy << 1);
  8497. SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
  8498. } else {
  8499. continue;
  8500. }
  8501. } else
  8502. continue;
  8503. DiagRuntimeBehavior(
  8504. Dest->getExprLoc(), Dest,
  8505. PDiag(diag::note_bad_memaccess_silence)
  8506. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  8507. break;
  8508. }
  8509. }
  8510. // A little helper routine: ignore addition and subtraction of integer literals.
  8511. // This intentionally does not ignore all integer constant expressions because
  8512. // we don't want to remove sizeof().
  8513. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  8514. Ex = Ex->IgnoreParenCasts();
  8515. while (true) {
  8516. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  8517. if (!BO || !BO->isAdditiveOp())
  8518. break;
  8519. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  8520. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  8521. if (isa<IntegerLiteral>(RHS))
  8522. Ex = LHS;
  8523. else if (isa<IntegerLiteral>(LHS))
  8524. Ex = RHS;
  8525. else
  8526. break;
  8527. }
  8528. return Ex;
  8529. }
  8530. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  8531. ASTContext &Context) {
  8532. // Only handle constant-sized or VLAs, but not flexible members.
  8533. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  8534. // Only issue the FIXIT for arrays of size > 1.
  8535. if (CAT->getSize().getSExtValue() <= 1)
  8536. return false;
  8537. } else if (!Ty->isVariableArrayType()) {
  8538. return false;
  8539. }
  8540. return true;
  8541. }
  8542. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  8543. // be the size of the source, instead of the destination.
  8544. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  8545. IdentifierInfo *FnName) {
  8546. // Don't crash if the user has the wrong number of arguments
  8547. unsigned NumArgs = Call->getNumArgs();
  8548. if ((NumArgs != 3) && (NumArgs != 4))
  8549. return;
  8550. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  8551. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  8552. const Expr *CompareWithSrc = nullptr;
  8553. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  8554. Call->getBeginLoc(), Call->getRParenLoc()))
  8555. return;
  8556. // Look for 'strlcpy(dst, x, sizeof(x))'
  8557. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  8558. CompareWithSrc = Ex;
  8559. else {
  8560. // Look for 'strlcpy(dst, x, strlen(x))'
  8561. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  8562. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  8563. SizeCall->getNumArgs() == 1)
  8564. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  8565. }
  8566. }
  8567. if (!CompareWithSrc)
  8568. return;
  8569. // Determine if the argument to sizeof/strlen is equal to the source
  8570. // argument. In principle there's all kinds of things you could do
  8571. // here, for instance creating an == expression and evaluating it with
  8572. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  8573. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  8574. if (!SrcArgDRE)
  8575. return;
  8576. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  8577. if (!CompareWithSrcDRE ||
  8578. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  8579. return;
  8580. const Expr *OriginalSizeArg = Call->getArg(2);
  8581. Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
  8582. << OriginalSizeArg->getSourceRange() << FnName;
  8583. // Output a FIXIT hint if the destination is an array (rather than a
  8584. // pointer to an array). This could be enhanced to handle some
  8585. // pointers if we know the actual size, like if DstArg is 'array+2'
  8586. // we could say 'sizeof(array)-2'.
  8587. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  8588. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  8589. return;
  8590. SmallString<128> sizeString;
  8591. llvm::raw_svector_ostream OS(sizeString);
  8592. OS << "sizeof(";
  8593. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8594. OS << ")";
  8595. Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
  8596. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  8597. OS.str());
  8598. }
  8599. /// Check if two expressions refer to the same declaration.
  8600. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  8601. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  8602. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  8603. return D1->getDecl() == D2->getDecl();
  8604. return false;
  8605. }
  8606. static const Expr *getStrlenExprArg(const Expr *E) {
  8607. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8608. const FunctionDecl *FD = CE->getDirectCallee();
  8609. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  8610. return nullptr;
  8611. return CE->getArg(0)->IgnoreParenCasts();
  8612. }
  8613. return nullptr;
  8614. }
  8615. // Warn on anti-patterns as the 'size' argument to strncat.
  8616. // The correct size argument should look like following:
  8617. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  8618. void Sema::CheckStrncatArguments(const CallExpr *CE,
  8619. IdentifierInfo *FnName) {
  8620. // Don't crash if the user has the wrong number of arguments.
  8621. if (CE->getNumArgs() < 3)
  8622. return;
  8623. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  8624. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  8625. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  8626. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
  8627. CE->getRParenLoc()))
  8628. return;
  8629. // Identify common expressions, which are wrongly used as the size argument
  8630. // to strncat and may lead to buffer overflows.
  8631. unsigned PatternType = 0;
  8632. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  8633. // - sizeof(dst)
  8634. if (referToTheSameDecl(SizeOfArg, DstArg))
  8635. PatternType = 1;
  8636. // - sizeof(src)
  8637. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  8638. PatternType = 2;
  8639. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  8640. if (BE->getOpcode() == BO_Sub) {
  8641. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  8642. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  8643. // - sizeof(dst) - strlen(dst)
  8644. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  8645. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  8646. PatternType = 1;
  8647. // - sizeof(src) - (anything)
  8648. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  8649. PatternType = 2;
  8650. }
  8651. }
  8652. if (PatternType == 0)
  8653. return;
  8654. // Generate the diagnostic.
  8655. SourceLocation SL = LenArg->getBeginLoc();
  8656. SourceRange SR = LenArg->getSourceRange();
  8657. SourceManager &SM = getSourceManager();
  8658. // If the function is defined as a builtin macro, do not show macro expansion.
  8659. if (SM.isMacroArgExpansion(SL)) {
  8660. SL = SM.getSpellingLoc(SL);
  8661. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  8662. SM.getSpellingLoc(SR.getEnd()));
  8663. }
  8664. // Check if the destination is an array (rather than a pointer to an array).
  8665. QualType DstTy = DstArg->getType();
  8666. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  8667. Context);
  8668. if (!isKnownSizeArray) {
  8669. if (PatternType == 1)
  8670. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  8671. else
  8672. Diag(SL, diag::warn_strncat_src_size) << SR;
  8673. return;
  8674. }
  8675. if (PatternType == 1)
  8676. Diag(SL, diag::warn_strncat_large_size) << SR;
  8677. else
  8678. Diag(SL, diag::warn_strncat_src_size) << SR;
  8679. SmallString<128> sizeString;
  8680. llvm::raw_svector_ostream OS(sizeString);
  8681. OS << "sizeof(";
  8682. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8683. OS << ") - ";
  8684. OS << "strlen(";
  8685. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8686. OS << ") - 1";
  8687. Diag(SL, diag::note_strncat_wrong_size)
  8688. << FixItHint::CreateReplacement(SR, OS.str());
  8689. }
  8690. void
  8691. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  8692. SourceLocation ReturnLoc,
  8693. bool isObjCMethod,
  8694. const AttrVec *Attrs,
  8695. const FunctionDecl *FD) {
  8696. // Check if the return value is null but should not be.
  8697. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  8698. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  8699. CheckNonNullExpr(*this, RetValExp))
  8700. Diag(ReturnLoc, diag::warn_null_ret)
  8701. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  8702. // C++11 [basic.stc.dynamic.allocation]p4:
  8703. // If an allocation function declared with a non-throwing
  8704. // exception-specification fails to allocate storage, it shall return
  8705. // a null pointer. Any other allocation function that fails to allocate
  8706. // storage shall indicate failure only by throwing an exception [...]
  8707. if (FD) {
  8708. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  8709. if (Op == OO_New || Op == OO_Array_New) {
  8710. const FunctionProtoType *Proto
  8711. = FD->getType()->castAs<FunctionProtoType>();
  8712. if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
  8713. CheckNonNullExpr(*this, RetValExp))
  8714. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  8715. << FD << getLangOpts().CPlusPlus11;
  8716. }
  8717. }
  8718. }
  8719. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  8720. /// Check for comparisons of floating point operands using != and ==.
  8721. /// Issue a warning if these are no self-comparisons, as they are not likely
  8722. /// to do what the programmer intended.
  8723. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  8724. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  8725. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  8726. // Special case: check for x == x (which is OK).
  8727. // Do not emit warnings for such cases.
  8728. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  8729. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  8730. if (DRL->getDecl() == DRR->getDecl())
  8731. return;
  8732. // Special case: check for comparisons against literals that can be exactly
  8733. // represented by APFloat. In such cases, do not emit a warning. This
  8734. // is a heuristic: often comparison against such literals are used to
  8735. // detect if a value in a variable has not changed. This clearly can
  8736. // lead to false negatives.
  8737. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  8738. if (FLL->isExact())
  8739. return;
  8740. } else
  8741. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  8742. if (FLR->isExact())
  8743. return;
  8744. // Check for comparisons with builtin types.
  8745. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  8746. if (CL->getBuiltinCallee())
  8747. return;
  8748. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  8749. if (CR->getBuiltinCallee())
  8750. return;
  8751. // Emit the diagnostic.
  8752. Diag(Loc, diag::warn_floatingpoint_eq)
  8753. << LHS->getSourceRange() << RHS->getSourceRange();
  8754. }
  8755. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  8756. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  8757. namespace {
  8758. /// Structure recording the 'active' range of an integer-valued
  8759. /// expression.
  8760. struct IntRange {
  8761. /// The number of bits active in the int.
  8762. unsigned Width;
  8763. /// True if the int is known not to have negative values.
  8764. bool NonNegative;
  8765. IntRange(unsigned Width, bool NonNegative)
  8766. : Width(Width), NonNegative(NonNegative) {}
  8767. /// Returns the range of the bool type.
  8768. static IntRange forBoolType() {
  8769. return IntRange(1, true);
  8770. }
  8771. /// Returns the range of an opaque value of the given integral type.
  8772. static IntRange forValueOfType(ASTContext &C, QualType T) {
  8773. return forValueOfCanonicalType(C,
  8774. T->getCanonicalTypeInternal().getTypePtr());
  8775. }
  8776. /// Returns the range of an opaque value of a canonical integral type.
  8777. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  8778. assert(T->isCanonicalUnqualified());
  8779. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8780. T = VT->getElementType().getTypePtr();
  8781. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8782. T = CT->getElementType().getTypePtr();
  8783. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8784. T = AT->getValueType().getTypePtr();
  8785. if (!C.getLangOpts().CPlusPlus) {
  8786. // For enum types in C code, use the underlying datatype.
  8787. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8788. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  8789. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  8790. // For enum types in C++, use the known bit width of the enumerators.
  8791. EnumDecl *Enum = ET->getDecl();
  8792. // In C++11, enums can have a fixed underlying type. Use this type to
  8793. // compute the range.
  8794. if (Enum->isFixed()) {
  8795. return IntRange(C.getIntWidth(QualType(T, 0)),
  8796. !ET->isSignedIntegerOrEnumerationType());
  8797. }
  8798. unsigned NumPositive = Enum->getNumPositiveBits();
  8799. unsigned NumNegative = Enum->getNumNegativeBits();
  8800. if (NumNegative == 0)
  8801. return IntRange(NumPositive, true/*NonNegative*/);
  8802. else
  8803. return IntRange(std::max(NumPositive + 1, NumNegative),
  8804. false/*NonNegative*/);
  8805. }
  8806. const BuiltinType *BT = cast<BuiltinType>(T);
  8807. assert(BT->isInteger());
  8808. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8809. }
  8810. /// Returns the "target" range of a canonical integral type, i.e.
  8811. /// the range of values expressible in the type.
  8812. ///
  8813. /// This matches forValueOfCanonicalType except that enums have the
  8814. /// full range of their type, not the range of their enumerators.
  8815. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  8816. assert(T->isCanonicalUnqualified());
  8817. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8818. T = VT->getElementType().getTypePtr();
  8819. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8820. T = CT->getElementType().getTypePtr();
  8821. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8822. T = AT->getValueType().getTypePtr();
  8823. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8824. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  8825. const BuiltinType *BT = cast<BuiltinType>(T);
  8826. assert(BT->isInteger());
  8827. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8828. }
  8829. /// Returns the supremum of two ranges: i.e. their conservative merge.
  8830. static IntRange join(IntRange L, IntRange R) {
  8831. return IntRange(std::max(L.Width, R.Width),
  8832. L.NonNegative && R.NonNegative);
  8833. }
  8834. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  8835. static IntRange meet(IntRange L, IntRange R) {
  8836. return IntRange(std::min(L.Width, R.Width),
  8837. L.NonNegative || R.NonNegative);
  8838. }
  8839. };
  8840. } // namespace
  8841. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  8842. unsigned MaxWidth) {
  8843. if (value.isSigned() && value.isNegative())
  8844. return IntRange(value.getMinSignedBits(), false);
  8845. if (value.getBitWidth() > MaxWidth)
  8846. value = value.trunc(MaxWidth);
  8847. // isNonNegative() just checks the sign bit without considering
  8848. // signedness.
  8849. return IntRange(value.getActiveBits(), true);
  8850. }
  8851. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  8852. unsigned MaxWidth) {
  8853. if (result.isInt())
  8854. return GetValueRange(C, result.getInt(), MaxWidth);
  8855. if (result.isVector()) {
  8856. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  8857. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  8858. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  8859. R = IntRange::join(R, El);
  8860. }
  8861. return R;
  8862. }
  8863. if (result.isComplexInt()) {
  8864. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  8865. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  8866. return IntRange::join(R, I);
  8867. }
  8868. // This can happen with lossless casts to intptr_t of "based" lvalues.
  8869. // Assume it might use arbitrary bits.
  8870. // FIXME: The only reason we need to pass the type in here is to get
  8871. // the sign right on this one case. It would be nice if APValue
  8872. // preserved this.
  8873. assert(result.isLValue() || result.isAddrLabelDiff());
  8874. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  8875. }
  8876. static QualType GetExprType(const Expr *E) {
  8877. QualType Ty = E->getType();
  8878. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  8879. Ty = AtomicRHS->getValueType();
  8880. return Ty;
  8881. }
  8882. /// Pseudo-evaluate the given integer expression, estimating the
  8883. /// range of values it might take.
  8884. ///
  8885. /// \param MaxWidth - the width to which the value will be truncated
  8886. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
  8887. E = E->IgnoreParens();
  8888. // Try a full evaluation first.
  8889. Expr::EvalResult result;
  8890. if (E->EvaluateAsRValue(result, C))
  8891. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  8892. // I think we only want to look through implicit casts here; if the
  8893. // user has an explicit widening cast, we should treat the value as
  8894. // being of the new, wider type.
  8895. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  8896. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  8897. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  8898. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  8899. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  8900. CE->getCastKind() == CK_BooleanToSignedIntegral;
  8901. // Assume that non-integer casts can span the full range of the type.
  8902. if (!isIntegerCast)
  8903. return OutputTypeRange;
  8904. IntRange SubRange
  8905. = GetExprRange(C, CE->getSubExpr(),
  8906. std::min(MaxWidth, OutputTypeRange.Width));
  8907. // Bail out if the subexpr's range is as wide as the cast type.
  8908. if (SubRange.Width >= OutputTypeRange.Width)
  8909. return OutputTypeRange;
  8910. // Otherwise, we take the smaller width, and we're non-negative if
  8911. // either the output type or the subexpr is.
  8912. return IntRange(SubRange.Width,
  8913. SubRange.NonNegative || OutputTypeRange.NonNegative);
  8914. }
  8915. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  8916. // If we can fold the condition, just take that operand.
  8917. bool CondResult;
  8918. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  8919. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  8920. : CO->getFalseExpr(),
  8921. MaxWidth);
  8922. // Otherwise, conservatively merge.
  8923. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  8924. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  8925. return IntRange::join(L, R);
  8926. }
  8927. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  8928. switch (BO->getOpcode()) {
  8929. case BO_Cmp:
  8930. llvm_unreachable("builtin <=> should have class type");
  8931. // Boolean-valued operations are single-bit and positive.
  8932. case BO_LAnd:
  8933. case BO_LOr:
  8934. case BO_LT:
  8935. case BO_GT:
  8936. case BO_LE:
  8937. case BO_GE:
  8938. case BO_EQ:
  8939. case BO_NE:
  8940. return IntRange::forBoolType();
  8941. // The type of the assignments is the type of the LHS, so the RHS
  8942. // is not necessarily the same type.
  8943. case BO_MulAssign:
  8944. case BO_DivAssign:
  8945. case BO_RemAssign:
  8946. case BO_AddAssign:
  8947. case BO_SubAssign:
  8948. case BO_XorAssign:
  8949. case BO_OrAssign:
  8950. // TODO: bitfields?
  8951. return IntRange::forValueOfType(C, GetExprType(E));
  8952. // Simple assignments just pass through the RHS, which will have
  8953. // been coerced to the LHS type.
  8954. case BO_Assign:
  8955. // TODO: bitfields?
  8956. return GetExprRange(C, BO->getRHS(), MaxWidth);
  8957. // Operations with opaque sources are black-listed.
  8958. case BO_PtrMemD:
  8959. case BO_PtrMemI:
  8960. return IntRange::forValueOfType(C, GetExprType(E));
  8961. // Bitwise-and uses the *infinum* of the two source ranges.
  8962. case BO_And:
  8963. case BO_AndAssign:
  8964. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  8965. GetExprRange(C, BO->getRHS(), MaxWidth));
  8966. // Left shift gets black-listed based on a judgement call.
  8967. case BO_Shl:
  8968. // ...except that we want to treat '1 << (blah)' as logically
  8969. // positive. It's an important idiom.
  8970. if (IntegerLiteral *I
  8971. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  8972. if (I->getValue() == 1) {
  8973. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  8974. return IntRange(R.Width, /*NonNegative*/ true);
  8975. }
  8976. }
  8977. LLVM_FALLTHROUGH;
  8978. case BO_ShlAssign:
  8979. return IntRange::forValueOfType(C, GetExprType(E));
  8980. // Right shift by a constant can narrow its left argument.
  8981. case BO_Shr:
  8982. case BO_ShrAssign: {
  8983. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  8984. // If the shift amount is a positive constant, drop the width by
  8985. // that much.
  8986. llvm::APSInt shift;
  8987. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  8988. shift.isNonNegative()) {
  8989. unsigned zext = shift.getZExtValue();
  8990. if (zext >= L.Width)
  8991. L.Width = (L.NonNegative ? 0 : 1);
  8992. else
  8993. L.Width -= zext;
  8994. }
  8995. return L;
  8996. }
  8997. // Comma acts as its right operand.
  8998. case BO_Comma:
  8999. return GetExprRange(C, BO->getRHS(), MaxWidth);
  9000. // Black-list pointer subtractions.
  9001. case BO_Sub:
  9002. if (BO->getLHS()->getType()->isPointerType())
  9003. return IntRange::forValueOfType(C, GetExprType(E));
  9004. break;
  9005. // The width of a division result is mostly determined by the size
  9006. // of the LHS.
  9007. case BO_Div: {
  9008. // Don't 'pre-truncate' the operands.
  9009. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9010. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  9011. // If the divisor is constant, use that.
  9012. llvm::APSInt divisor;
  9013. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  9014. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  9015. if (log2 >= L.Width)
  9016. L.Width = (L.NonNegative ? 0 : 1);
  9017. else
  9018. L.Width = std::min(L.Width - log2, MaxWidth);
  9019. return L;
  9020. }
  9021. // Otherwise, just use the LHS's width.
  9022. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  9023. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  9024. }
  9025. // The result of a remainder can't be larger than the result of
  9026. // either side.
  9027. case BO_Rem: {
  9028. // Don't 'pre-truncate' the operands.
  9029. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9030. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  9031. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  9032. IntRange meet = IntRange::meet(L, R);
  9033. meet.Width = std::min(meet.Width, MaxWidth);
  9034. return meet;
  9035. }
  9036. // The default behavior is okay for these.
  9037. case BO_Mul:
  9038. case BO_Add:
  9039. case BO_Xor:
  9040. case BO_Or:
  9041. break;
  9042. }
  9043. // The default case is to treat the operation as if it were closed
  9044. // on the narrowest type that encompasses both operands.
  9045. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  9046. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  9047. return IntRange::join(L, R);
  9048. }
  9049. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  9050. switch (UO->getOpcode()) {
  9051. // Boolean-valued operations are white-listed.
  9052. case UO_LNot:
  9053. return IntRange::forBoolType();
  9054. // Operations with opaque sources are black-listed.
  9055. case UO_Deref:
  9056. case UO_AddrOf: // should be impossible
  9057. return IntRange::forValueOfType(C, GetExprType(E));
  9058. default:
  9059. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  9060. }
  9061. }
  9062. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  9063. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
  9064. if (const auto *BitField = E->getSourceBitField())
  9065. return IntRange(BitField->getBitWidthValue(C),
  9066. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  9067. return IntRange::forValueOfType(C, GetExprType(E));
  9068. }
  9069. static IntRange GetExprRange(ASTContext &C, const Expr *E) {
  9070. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
  9071. }
  9072. /// Checks whether the given value, which currently has the given
  9073. /// source semantics, has the same value when coerced through the
  9074. /// target semantics.
  9075. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  9076. const llvm::fltSemantics &Src,
  9077. const llvm::fltSemantics &Tgt) {
  9078. llvm::APFloat truncated = value;
  9079. bool ignored;
  9080. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9081. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9082. return truncated.bitwiseIsEqual(value);
  9083. }
  9084. /// Checks whether the given value, which currently has the given
  9085. /// source semantics, has the same value when coerced through the
  9086. /// target semantics.
  9087. ///
  9088. /// The value might be a vector of floats (or a complex number).
  9089. static bool IsSameFloatAfterCast(const APValue &value,
  9090. const llvm::fltSemantics &Src,
  9091. const llvm::fltSemantics &Tgt) {
  9092. if (value.isFloat())
  9093. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  9094. if (value.isVector()) {
  9095. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  9096. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  9097. return false;
  9098. return true;
  9099. }
  9100. assert(value.isComplexFloat());
  9101. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  9102. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  9103. }
  9104. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  9105. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  9106. // Suppress cases where we are comparing against an enum constant.
  9107. if (const DeclRefExpr *DR =
  9108. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  9109. if (isa<EnumConstantDecl>(DR->getDecl()))
  9110. return true;
  9111. // Suppress cases where the '0' value is expanded from a macro.
  9112. if (E->getBeginLoc().isMacroID())
  9113. return true;
  9114. return false;
  9115. }
  9116. static bool isKnownToHaveUnsignedValue(Expr *E) {
  9117. return E->getType()->isIntegerType() &&
  9118. (!E->getType()->isSignedIntegerType() ||
  9119. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  9120. }
  9121. namespace {
  9122. /// The promoted range of values of a type. In general this has the
  9123. /// following structure:
  9124. ///
  9125. /// |-----------| . . . |-----------|
  9126. /// ^ ^ ^ ^
  9127. /// Min HoleMin HoleMax Max
  9128. ///
  9129. /// ... where there is only a hole if a signed type is promoted to unsigned
  9130. /// (in which case Min and Max are the smallest and largest representable
  9131. /// values).
  9132. struct PromotedRange {
  9133. // Min, or HoleMax if there is a hole.
  9134. llvm::APSInt PromotedMin;
  9135. // Max, or HoleMin if there is a hole.
  9136. llvm::APSInt PromotedMax;
  9137. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  9138. if (R.Width == 0)
  9139. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  9140. else if (R.Width >= BitWidth && !Unsigned) {
  9141. // Promotion made the type *narrower*. This happens when promoting
  9142. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  9143. // Treat all values of 'signed int' as being in range for now.
  9144. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  9145. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  9146. } else {
  9147. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  9148. .extOrTrunc(BitWidth);
  9149. PromotedMin.setIsUnsigned(Unsigned);
  9150. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  9151. .extOrTrunc(BitWidth);
  9152. PromotedMax.setIsUnsigned(Unsigned);
  9153. }
  9154. }
  9155. // Determine whether this range is contiguous (has no hole).
  9156. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  9157. // Where a constant value is within the range.
  9158. enum ComparisonResult {
  9159. LT = 0x1,
  9160. LE = 0x2,
  9161. GT = 0x4,
  9162. GE = 0x8,
  9163. EQ = 0x10,
  9164. NE = 0x20,
  9165. InRangeFlag = 0x40,
  9166. Less = LE | LT | NE,
  9167. Min = LE | InRangeFlag,
  9168. InRange = InRangeFlag,
  9169. Max = GE | InRangeFlag,
  9170. Greater = GE | GT | NE,
  9171. OnlyValue = LE | GE | EQ | InRangeFlag,
  9172. InHole = NE
  9173. };
  9174. ComparisonResult compare(const llvm::APSInt &Value) const {
  9175. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  9176. Value.isUnsigned() == PromotedMin.isUnsigned());
  9177. if (!isContiguous()) {
  9178. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  9179. if (Value.isMinValue()) return Min;
  9180. if (Value.isMaxValue()) return Max;
  9181. if (Value >= PromotedMin) return InRange;
  9182. if (Value <= PromotedMax) return InRange;
  9183. return InHole;
  9184. }
  9185. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  9186. case -1: return Less;
  9187. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  9188. case 1:
  9189. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  9190. case -1: return InRange;
  9191. case 0: return Max;
  9192. case 1: return Greater;
  9193. }
  9194. }
  9195. llvm_unreachable("impossible compare result");
  9196. }
  9197. static llvm::Optional<StringRef>
  9198. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  9199. if (Op == BO_Cmp) {
  9200. ComparisonResult LTFlag = LT, GTFlag = GT;
  9201. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  9202. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  9203. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  9204. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  9205. return llvm::None;
  9206. }
  9207. ComparisonResult TrueFlag, FalseFlag;
  9208. if (Op == BO_EQ) {
  9209. TrueFlag = EQ;
  9210. FalseFlag = NE;
  9211. } else if (Op == BO_NE) {
  9212. TrueFlag = NE;
  9213. FalseFlag = EQ;
  9214. } else {
  9215. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  9216. TrueFlag = LT;
  9217. FalseFlag = GE;
  9218. } else {
  9219. TrueFlag = GT;
  9220. FalseFlag = LE;
  9221. }
  9222. if (Op == BO_GE || Op == BO_LE)
  9223. std::swap(TrueFlag, FalseFlag);
  9224. }
  9225. if (R & TrueFlag)
  9226. return StringRef("true");
  9227. if (R & FalseFlag)
  9228. return StringRef("false");
  9229. return llvm::None;
  9230. }
  9231. };
  9232. }
  9233. static bool HasEnumType(Expr *E) {
  9234. // Strip off implicit integral promotions.
  9235. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  9236. if (ICE->getCastKind() != CK_IntegralCast &&
  9237. ICE->getCastKind() != CK_NoOp)
  9238. break;
  9239. E = ICE->getSubExpr();
  9240. }
  9241. return E->getType()->isEnumeralType();
  9242. }
  9243. static int classifyConstantValue(Expr *Constant) {
  9244. // The values of this enumeration are used in the diagnostics
  9245. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  9246. enum ConstantValueKind {
  9247. Miscellaneous = 0,
  9248. LiteralTrue,
  9249. LiteralFalse
  9250. };
  9251. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  9252. return BL->getValue() ? ConstantValueKind::LiteralTrue
  9253. : ConstantValueKind::LiteralFalse;
  9254. return ConstantValueKind::Miscellaneous;
  9255. }
  9256. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  9257. Expr *Constant, Expr *Other,
  9258. const llvm::APSInt &Value,
  9259. bool RhsConstant) {
  9260. if (S.inTemplateInstantiation())
  9261. return false;
  9262. Expr *OriginalOther = Other;
  9263. Constant = Constant->IgnoreParenImpCasts();
  9264. Other = Other->IgnoreParenImpCasts();
  9265. // Suppress warnings on tautological comparisons between values of the same
  9266. // enumeration type. There are only two ways we could warn on this:
  9267. // - If the constant is outside the range of representable values of
  9268. // the enumeration. In such a case, we should warn about the cast
  9269. // to enumeration type, not about the comparison.
  9270. // - If the constant is the maximum / minimum in-range value. For an
  9271. // enumeratin type, such comparisons can be meaningful and useful.
  9272. if (Constant->getType()->isEnumeralType() &&
  9273. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  9274. return false;
  9275. // TODO: Investigate using GetExprRange() to get tighter bounds
  9276. // on the bit ranges.
  9277. QualType OtherT = Other->getType();
  9278. if (const auto *AT = OtherT->getAs<AtomicType>())
  9279. OtherT = AT->getValueType();
  9280. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  9281. // Whether we're treating Other as being a bool because of the form of
  9282. // expression despite it having another type (typically 'int' in C).
  9283. bool OtherIsBooleanDespiteType =
  9284. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  9285. if (OtherIsBooleanDespiteType)
  9286. OtherRange = IntRange::forBoolType();
  9287. // Determine the promoted range of the other type and see if a comparison of
  9288. // the constant against that range is tautological.
  9289. PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
  9290. Value.isUnsigned());
  9291. auto Cmp = OtherPromotedRange.compare(Value);
  9292. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  9293. if (!Result)
  9294. return false;
  9295. // Suppress the diagnostic for an in-range comparison if the constant comes
  9296. // from a macro or enumerator. We don't want to diagnose
  9297. //
  9298. // some_long_value <= INT_MAX
  9299. //
  9300. // when sizeof(int) == sizeof(long).
  9301. bool InRange = Cmp & PromotedRange::InRangeFlag;
  9302. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  9303. return false;
  9304. // If this is a comparison to an enum constant, include that
  9305. // constant in the diagnostic.
  9306. const EnumConstantDecl *ED = nullptr;
  9307. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  9308. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  9309. // Should be enough for uint128 (39 decimal digits)
  9310. SmallString<64> PrettySourceValue;
  9311. llvm::raw_svector_ostream OS(PrettySourceValue);
  9312. if (ED)
  9313. OS << '\'' << *ED << "' (" << Value << ")";
  9314. else
  9315. OS << Value;
  9316. // FIXME: We use a somewhat different formatting for the in-range cases and
  9317. // cases involving boolean values for historical reasons. We should pick a
  9318. // consistent way of presenting these diagnostics.
  9319. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  9320. S.DiagRuntimeBehavior(
  9321. E->getOperatorLoc(), E,
  9322. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  9323. : diag::warn_tautological_bool_compare)
  9324. << OS.str() << classifyConstantValue(Constant)
  9325. << OtherT << OtherIsBooleanDespiteType << *Result
  9326. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  9327. } else {
  9328. unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  9329. ? (HasEnumType(OriginalOther)
  9330. ? diag::warn_unsigned_enum_always_true_comparison
  9331. : diag::warn_unsigned_always_true_comparison)
  9332. : diag::warn_tautological_constant_compare;
  9333. S.Diag(E->getOperatorLoc(), Diag)
  9334. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  9335. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  9336. }
  9337. return true;
  9338. }
  9339. /// Analyze the operands of the given comparison. Implements the
  9340. /// fallback case from AnalyzeComparison.
  9341. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  9342. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9343. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9344. }
  9345. /// Implements -Wsign-compare.
  9346. ///
  9347. /// \param E the binary operator to check for warnings
  9348. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  9349. // The type the comparison is being performed in.
  9350. QualType T = E->getLHS()->getType();
  9351. // Only analyze comparison operators where both sides have been converted to
  9352. // the same type.
  9353. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  9354. return AnalyzeImpConvsInComparison(S, E);
  9355. // Don't analyze value-dependent comparisons directly.
  9356. if (E->isValueDependent())
  9357. return AnalyzeImpConvsInComparison(S, E);
  9358. Expr *LHS = E->getLHS();
  9359. Expr *RHS = E->getRHS();
  9360. if (T->isIntegralType(S.Context)) {
  9361. llvm::APSInt RHSValue;
  9362. llvm::APSInt LHSValue;
  9363. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  9364. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  9365. // We don't care about expressions whose result is a constant.
  9366. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  9367. return AnalyzeImpConvsInComparison(S, E);
  9368. // We only care about expressions where just one side is literal
  9369. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  9370. // Is the constant on the RHS or LHS?
  9371. const bool RhsConstant = IsRHSIntegralLiteral;
  9372. Expr *Const = RhsConstant ? RHS : LHS;
  9373. Expr *Other = RhsConstant ? LHS : RHS;
  9374. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  9375. // Check whether an integer constant comparison results in a value
  9376. // of 'true' or 'false'.
  9377. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  9378. return AnalyzeImpConvsInComparison(S, E);
  9379. }
  9380. }
  9381. if (!T->hasUnsignedIntegerRepresentation()) {
  9382. // We don't do anything special if this isn't an unsigned integral
  9383. // comparison: we're only interested in integral comparisons, and
  9384. // signed comparisons only happen in cases we don't care to warn about.
  9385. return AnalyzeImpConvsInComparison(S, E);
  9386. }
  9387. LHS = LHS->IgnoreParenImpCasts();
  9388. RHS = RHS->IgnoreParenImpCasts();
  9389. if (!S.getLangOpts().CPlusPlus) {
  9390. // Avoid warning about comparison of integers with different signs when
  9391. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  9392. // the type of `E`.
  9393. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  9394. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9395. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  9396. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9397. }
  9398. // Check to see if one of the (unmodified) operands is of different
  9399. // signedness.
  9400. Expr *signedOperand, *unsignedOperand;
  9401. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  9402. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  9403. "unsigned comparison between two signed integer expressions?");
  9404. signedOperand = LHS;
  9405. unsignedOperand = RHS;
  9406. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  9407. signedOperand = RHS;
  9408. unsignedOperand = LHS;
  9409. } else {
  9410. return AnalyzeImpConvsInComparison(S, E);
  9411. }
  9412. // Otherwise, calculate the effective range of the signed operand.
  9413. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  9414. // Go ahead and analyze implicit conversions in the operands. Note
  9415. // that we skip the implicit conversions on both sides.
  9416. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  9417. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  9418. // If the signed range is non-negative, -Wsign-compare won't fire.
  9419. if (signedRange.NonNegative)
  9420. return;
  9421. // For (in)equality comparisons, if the unsigned operand is a
  9422. // constant which cannot collide with a overflowed signed operand,
  9423. // then reinterpreting the signed operand as unsigned will not
  9424. // change the result of the comparison.
  9425. if (E->isEqualityOp()) {
  9426. unsigned comparisonWidth = S.Context.getIntWidth(T);
  9427. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  9428. // We should never be unable to prove that the unsigned operand is
  9429. // non-negative.
  9430. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  9431. if (unsignedRange.Width < comparisonWidth)
  9432. return;
  9433. }
  9434. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9435. S.PDiag(diag::warn_mixed_sign_comparison)
  9436. << LHS->getType() << RHS->getType()
  9437. << LHS->getSourceRange() << RHS->getSourceRange());
  9438. }
  9439. /// Analyzes an attempt to assign the given value to a bitfield.
  9440. ///
  9441. /// Returns true if there was something fishy about the attempt.
  9442. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  9443. SourceLocation InitLoc) {
  9444. assert(Bitfield->isBitField());
  9445. if (Bitfield->isInvalidDecl())
  9446. return false;
  9447. // White-list bool bitfields.
  9448. QualType BitfieldType = Bitfield->getType();
  9449. if (BitfieldType->isBooleanType())
  9450. return false;
  9451. if (BitfieldType->isEnumeralType()) {
  9452. EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
  9453. // If the underlying enum type was not explicitly specified as an unsigned
  9454. // type and the enum contain only positive values, MSVC++ will cause an
  9455. // inconsistency by storing this as a signed type.
  9456. if (S.getLangOpts().CPlusPlus11 &&
  9457. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  9458. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  9459. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  9460. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  9461. << BitfieldEnumDecl->getNameAsString();
  9462. }
  9463. }
  9464. if (Bitfield->getType()->isBooleanType())
  9465. return false;
  9466. // Ignore value- or type-dependent expressions.
  9467. if (Bitfield->getBitWidth()->isValueDependent() ||
  9468. Bitfield->getBitWidth()->isTypeDependent() ||
  9469. Init->isValueDependent() ||
  9470. Init->isTypeDependent())
  9471. return false;
  9472. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  9473. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  9474. Expr::EvalResult Result;
  9475. if (!OriginalInit->EvaluateAsInt(Result, S.Context,
  9476. Expr::SE_AllowSideEffects)) {
  9477. // The RHS is not constant. If the RHS has an enum type, make sure the
  9478. // bitfield is wide enough to hold all the values of the enum without
  9479. // truncation.
  9480. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  9481. EnumDecl *ED = EnumTy->getDecl();
  9482. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  9483. // Enum types are implicitly signed on Windows, so check if there are any
  9484. // negative enumerators to see if the enum was intended to be signed or
  9485. // not.
  9486. bool SignedEnum = ED->getNumNegativeBits() > 0;
  9487. // Check for surprising sign changes when assigning enum values to a
  9488. // bitfield of different signedness. If the bitfield is signed and we
  9489. // have exactly the right number of bits to store this unsigned enum,
  9490. // suggest changing the enum to an unsigned type. This typically happens
  9491. // on Windows where unfixed enums always use an underlying type of 'int'.
  9492. unsigned DiagID = 0;
  9493. if (SignedEnum && !SignedBitfield) {
  9494. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  9495. } else if (SignedBitfield && !SignedEnum &&
  9496. ED->getNumPositiveBits() == FieldWidth) {
  9497. DiagID = diag::warn_signed_bitfield_enum_conversion;
  9498. }
  9499. if (DiagID) {
  9500. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  9501. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  9502. SourceRange TypeRange =
  9503. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  9504. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  9505. << SignedEnum << TypeRange;
  9506. }
  9507. // Compute the required bitwidth. If the enum has negative values, we need
  9508. // one more bit than the normal number of positive bits to represent the
  9509. // sign bit.
  9510. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  9511. ED->getNumNegativeBits())
  9512. : ED->getNumPositiveBits();
  9513. // Check the bitwidth.
  9514. if (BitsNeeded > FieldWidth) {
  9515. Expr *WidthExpr = Bitfield->getBitWidth();
  9516. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  9517. << Bitfield << ED;
  9518. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  9519. << BitsNeeded << ED << WidthExpr->getSourceRange();
  9520. }
  9521. }
  9522. return false;
  9523. }
  9524. llvm::APSInt Value = Result.Val.getInt();
  9525. unsigned OriginalWidth = Value.getBitWidth();
  9526. if (!Value.isSigned() || Value.isNegative())
  9527. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  9528. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  9529. OriginalWidth = Value.getMinSignedBits();
  9530. if (OriginalWidth <= FieldWidth)
  9531. return false;
  9532. // Compute the value which the bitfield will contain.
  9533. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  9534. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  9535. // Check whether the stored value is equal to the original value.
  9536. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  9537. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  9538. return false;
  9539. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  9540. // therefore don't strictly fit into a signed bitfield of width 1.
  9541. if (FieldWidth == 1 && Value == 1)
  9542. return false;
  9543. std::string PrettyValue = Value.toString(10);
  9544. std::string PrettyTrunc = TruncatedValue.toString(10);
  9545. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  9546. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  9547. << Init->getSourceRange();
  9548. return true;
  9549. }
  9550. /// Analyze the given simple or compound assignment for warning-worthy
  9551. /// operations.
  9552. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  9553. // Just recurse on the LHS.
  9554. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9555. // We want to recurse on the RHS as normal unless we're assigning to
  9556. // a bitfield.
  9557. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  9558. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  9559. E->getOperatorLoc())) {
  9560. // Recurse, ignoring any implicit conversions on the RHS.
  9561. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  9562. E->getOperatorLoc());
  9563. }
  9564. }
  9565. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9566. // Diagnose implicitly sequentially-consistent atomic assignment.
  9567. if (E->getLHS()->getType()->isAtomicType())
  9568. S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  9569. }
  9570. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9571. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  9572. SourceLocation CContext, unsigned diag,
  9573. bool pruneControlFlow = false) {
  9574. if (pruneControlFlow) {
  9575. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9576. S.PDiag(diag)
  9577. << SourceType << T << E->getSourceRange()
  9578. << SourceRange(CContext));
  9579. return;
  9580. }
  9581. S.Diag(E->getExprLoc(), diag)
  9582. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  9583. }
  9584. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9585. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  9586. SourceLocation CContext,
  9587. unsigned diag, bool pruneControlFlow = false) {
  9588. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  9589. }
  9590. /// Diagnose an implicit cast from a floating point value to an integer value.
  9591. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  9592. SourceLocation CContext) {
  9593. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  9594. const bool PruneWarnings = S.inTemplateInstantiation();
  9595. Expr *InnerE = E->IgnoreParenImpCasts();
  9596. // We also want to warn on, e.g., "int i = -1.234"
  9597. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  9598. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  9599. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  9600. const bool IsLiteral =
  9601. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  9602. llvm::APFloat Value(0.0);
  9603. bool IsConstant =
  9604. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  9605. if (!IsConstant) {
  9606. return DiagnoseImpCast(S, E, T, CContext,
  9607. diag::warn_impcast_float_integer, PruneWarnings);
  9608. }
  9609. bool isExact = false;
  9610. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  9611. T->hasUnsignedIntegerRepresentation());
  9612. llvm::APFloat::opStatus Result = Value.convertToInteger(
  9613. IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
  9614. if (Result == llvm::APFloat::opOK && isExact) {
  9615. if (IsLiteral) return;
  9616. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  9617. PruneWarnings);
  9618. }
  9619. // Conversion of a floating-point value to a non-bool integer where the
  9620. // integral part cannot be represented by the integer type is undefined.
  9621. if (!IsBool && Result == llvm::APFloat::opInvalidOp)
  9622. return DiagnoseImpCast(
  9623. S, E, T, CContext,
  9624. IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
  9625. : diag::warn_impcast_float_to_integer_out_of_range,
  9626. PruneWarnings);
  9627. unsigned DiagID = 0;
  9628. if (IsLiteral) {
  9629. // Warn on floating point literal to integer.
  9630. DiagID = diag::warn_impcast_literal_float_to_integer;
  9631. } else if (IntegerValue == 0) {
  9632. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  9633. return DiagnoseImpCast(S, E, T, CContext,
  9634. diag::warn_impcast_float_integer, PruneWarnings);
  9635. }
  9636. // Warn on non-zero to zero conversion.
  9637. DiagID = diag::warn_impcast_float_to_integer_zero;
  9638. } else {
  9639. if (IntegerValue.isUnsigned()) {
  9640. if (!IntegerValue.isMaxValue()) {
  9641. return DiagnoseImpCast(S, E, T, CContext,
  9642. diag::warn_impcast_float_integer, PruneWarnings);
  9643. }
  9644. } else { // IntegerValue.isSigned()
  9645. if (!IntegerValue.isMaxSignedValue() &&
  9646. !IntegerValue.isMinSignedValue()) {
  9647. return DiagnoseImpCast(S, E, T, CContext,
  9648. diag::warn_impcast_float_integer, PruneWarnings);
  9649. }
  9650. }
  9651. // Warn on evaluatable floating point expression to integer conversion.
  9652. DiagID = diag::warn_impcast_float_to_integer;
  9653. }
  9654. // FIXME: Force the precision of the source value down so we don't print
  9655. // digits which are usually useless (we don't really care here if we
  9656. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  9657. // would automatically print the shortest representation, but it's a bit
  9658. // tricky to implement.
  9659. SmallString<16> PrettySourceValue;
  9660. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  9661. precision = (precision * 59 + 195) / 196;
  9662. Value.toString(PrettySourceValue, precision);
  9663. SmallString<16> PrettyTargetValue;
  9664. if (IsBool)
  9665. PrettyTargetValue = Value.isZero() ? "false" : "true";
  9666. else
  9667. IntegerValue.toString(PrettyTargetValue);
  9668. if (PruneWarnings) {
  9669. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9670. S.PDiag(DiagID)
  9671. << E->getType() << T.getUnqualifiedType()
  9672. << PrettySourceValue << PrettyTargetValue
  9673. << E->getSourceRange() << SourceRange(CContext));
  9674. } else {
  9675. S.Diag(E->getExprLoc(), DiagID)
  9676. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  9677. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  9678. }
  9679. }
  9680. /// Analyze the given compound assignment for the possible losing of
  9681. /// floating-point precision.
  9682. static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
  9683. assert(isa<CompoundAssignOperator>(E) &&
  9684. "Must be compound assignment operation");
  9685. // Recurse on the LHS and RHS in here
  9686. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9687. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9688. if (E->getLHS()->getType()->isAtomicType())
  9689. S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
  9690. // Now check the outermost expression
  9691. const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
  9692. const auto *RBT = cast<CompoundAssignOperator>(E)
  9693. ->getComputationResultType()
  9694. ->getAs<BuiltinType>();
  9695. // The below checks assume source is floating point.
  9696. if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
  9697. // If source is floating point but target is an integer.
  9698. if (ResultBT->isInteger())
  9699. return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
  9700. E->getExprLoc(), diag::warn_impcast_float_integer);
  9701. if (!ResultBT->isFloatingPoint())
  9702. return;
  9703. // If both source and target are floating points, warn about losing precision.
  9704. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  9705. QualType(ResultBT, 0), QualType(RBT, 0));
  9706. if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
  9707. // warn about dropping FP rank.
  9708. DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
  9709. diag::warn_impcast_float_result_precision);
  9710. }
  9711. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  9712. IntRange Range) {
  9713. if (!Range.Width) return "0";
  9714. llvm::APSInt ValueInRange = Value;
  9715. ValueInRange.setIsSigned(!Range.NonNegative);
  9716. ValueInRange = ValueInRange.trunc(Range.Width);
  9717. return ValueInRange.toString(10);
  9718. }
  9719. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  9720. if (!isa<ImplicitCastExpr>(Ex))
  9721. return false;
  9722. Expr *InnerE = Ex->IgnoreParenImpCasts();
  9723. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  9724. const Type *Source =
  9725. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  9726. if (Target->isDependentType())
  9727. return false;
  9728. const BuiltinType *FloatCandidateBT =
  9729. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  9730. const Type *BoolCandidateType = ToBool ? Target : Source;
  9731. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  9732. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  9733. }
  9734. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  9735. SourceLocation CC) {
  9736. unsigned NumArgs = TheCall->getNumArgs();
  9737. for (unsigned i = 0; i < NumArgs; ++i) {
  9738. Expr *CurrA = TheCall->getArg(i);
  9739. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  9740. continue;
  9741. bool IsSwapped = ((i > 0) &&
  9742. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  9743. IsSwapped |= ((i < (NumArgs - 1)) &&
  9744. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  9745. if (IsSwapped) {
  9746. // Warn on this floating-point to bool conversion.
  9747. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  9748. CurrA->getType(), CC,
  9749. diag::warn_impcast_floating_point_to_bool);
  9750. }
  9751. }
  9752. }
  9753. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  9754. SourceLocation CC) {
  9755. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  9756. E->getExprLoc()))
  9757. return;
  9758. // Don't warn on functions which have return type nullptr_t.
  9759. if (isa<CallExpr>(E))
  9760. return;
  9761. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  9762. const Expr::NullPointerConstantKind NullKind =
  9763. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  9764. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  9765. return;
  9766. // Return if target type is a safe conversion.
  9767. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  9768. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  9769. return;
  9770. SourceLocation Loc = E->getSourceRange().getBegin();
  9771. // Venture through the macro stacks to get to the source of macro arguments.
  9772. // The new location is a better location than the complete location that was
  9773. // passed in.
  9774. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  9775. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  9776. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  9777. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  9778. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  9779. Loc, S.SourceMgr, S.getLangOpts());
  9780. if (MacroName == "NULL")
  9781. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
  9782. }
  9783. // Only warn if the null and context location are in the same macro expansion.
  9784. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  9785. return;
  9786. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  9787. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  9788. << FixItHint::CreateReplacement(Loc,
  9789. S.getFixItZeroLiteralForType(T, Loc));
  9790. }
  9791. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9792. ObjCArrayLiteral *ArrayLiteral);
  9793. static void
  9794. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9795. ObjCDictionaryLiteral *DictionaryLiteral);
  9796. /// Check a single element within a collection literal against the
  9797. /// target element type.
  9798. static void checkObjCCollectionLiteralElement(Sema &S,
  9799. QualType TargetElementType,
  9800. Expr *Element,
  9801. unsigned ElementKind) {
  9802. // Skip a bitcast to 'id' or qualified 'id'.
  9803. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  9804. if (ICE->getCastKind() == CK_BitCast &&
  9805. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  9806. Element = ICE->getSubExpr();
  9807. }
  9808. QualType ElementType = Element->getType();
  9809. ExprResult ElementResult(Element);
  9810. if (ElementType->getAs<ObjCObjectPointerType>() &&
  9811. S.CheckSingleAssignmentConstraints(TargetElementType,
  9812. ElementResult,
  9813. false, false)
  9814. != Sema::Compatible) {
  9815. S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
  9816. << ElementType << ElementKind << TargetElementType
  9817. << Element->getSourceRange();
  9818. }
  9819. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  9820. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  9821. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  9822. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  9823. }
  9824. /// Check an Objective-C array literal being converted to the given
  9825. /// target type.
  9826. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9827. ObjCArrayLiteral *ArrayLiteral) {
  9828. if (!S.NSArrayDecl)
  9829. return;
  9830. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9831. if (!TargetObjCPtr)
  9832. return;
  9833. if (TargetObjCPtr->isUnspecialized() ||
  9834. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9835. != S.NSArrayDecl->getCanonicalDecl())
  9836. return;
  9837. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9838. if (TypeArgs.size() != 1)
  9839. return;
  9840. QualType TargetElementType = TypeArgs[0];
  9841. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  9842. checkObjCCollectionLiteralElement(S, TargetElementType,
  9843. ArrayLiteral->getElement(I),
  9844. 0);
  9845. }
  9846. }
  9847. /// Check an Objective-C dictionary literal being converted to the given
  9848. /// target type.
  9849. static void
  9850. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9851. ObjCDictionaryLiteral *DictionaryLiteral) {
  9852. if (!S.NSDictionaryDecl)
  9853. return;
  9854. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9855. if (!TargetObjCPtr)
  9856. return;
  9857. if (TargetObjCPtr->isUnspecialized() ||
  9858. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9859. != S.NSDictionaryDecl->getCanonicalDecl())
  9860. return;
  9861. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9862. if (TypeArgs.size() != 2)
  9863. return;
  9864. QualType TargetKeyType = TypeArgs[0];
  9865. QualType TargetObjectType = TypeArgs[1];
  9866. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  9867. auto Element = DictionaryLiteral->getKeyValueElement(I);
  9868. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  9869. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  9870. }
  9871. }
  9872. // Helper function to filter out cases for constant width constant conversion.
  9873. // Don't warn on char array initialization or for non-decimal values.
  9874. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  9875. SourceLocation CC) {
  9876. // If initializing from a constant, and the constant starts with '0',
  9877. // then it is a binary, octal, or hexadecimal. Allow these constants
  9878. // to fill all the bits, even if there is a sign change.
  9879. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  9880. const char FirstLiteralCharacter =
  9881. S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
  9882. if (FirstLiteralCharacter == '0')
  9883. return false;
  9884. }
  9885. // If the CC location points to a '{', and the type is char, then assume
  9886. // assume it is an array initialization.
  9887. if (CC.isValid() && T->isCharType()) {
  9888. const char FirstContextCharacter =
  9889. S.getSourceManager().getCharacterData(CC)[0];
  9890. if (FirstContextCharacter == '{')
  9891. return false;
  9892. }
  9893. return true;
  9894. }
  9895. static void
  9896. CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
  9897. bool *ICContext = nullptr) {
  9898. if (E->isTypeDependent() || E->isValueDependent()) return;
  9899. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  9900. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  9901. if (Source == Target) return;
  9902. if (Target->isDependentType()) return;
  9903. // If the conversion context location is invalid don't complain. We also
  9904. // don't want to emit a warning if the issue occurs from the expansion of
  9905. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  9906. // delay this check as long as possible. Once we detect we are in that
  9907. // scenario, we just return.
  9908. if (CC.isInvalid())
  9909. return;
  9910. if (Source->isAtomicType())
  9911. S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
  9912. // Diagnose implicit casts to bool.
  9913. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  9914. if (isa<StringLiteral>(E))
  9915. // Warn on string literal to bool. Checks for string literals in logical
  9916. // and expressions, for instance, assert(0 && "error here"), are
  9917. // prevented by a check in AnalyzeImplicitConversions().
  9918. return DiagnoseImpCast(S, E, T, CC,
  9919. diag::warn_impcast_string_literal_to_bool);
  9920. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  9921. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  9922. // This covers the literal expressions that evaluate to Objective-C
  9923. // objects.
  9924. return DiagnoseImpCast(S, E, T, CC,
  9925. diag::warn_impcast_objective_c_literal_to_bool);
  9926. }
  9927. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  9928. // Warn on pointer to bool conversion that is always true.
  9929. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  9930. SourceRange(CC));
  9931. }
  9932. }
  9933. // Check implicit casts from Objective-C collection literals to specialized
  9934. // collection types, e.g., NSArray<NSString *> *.
  9935. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  9936. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  9937. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  9938. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  9939. // Strip vector types.
  9940. if (isa<VectorType>(Source)) {
  9941. if (!isa<VectorType>(Target)) {
  9942. if (S.SourceMgr.isInSystemMacro(CC))
  9943. return;
  9944. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  9945. }
  9946. // If the vector cast is cast between two vectors of the same size, it is
  9947. // a bitcast, not a conversion.
  9948. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  9949. return;
  9950. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  9951. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  9952. }
  9953. if (auto VecTy = dyn_cast<VectorType>(Target))
  9954. Target = VecTy->getElementType().getTypePtr();
  9955. // Strip complex types.
  9956. if (isa<ComplexType>(Source)) {
  9957. if (!isa<ComplexType>(Target)) {
  9958. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  9959. return;
  9960. return DiagnoseImpCast(S, E, T, CC,
  9961. S.getLangOpts().CPlusPlus
  9962. ? diag::err_impcast_complex_scalar
  9963. : diag::warn_impcast_complex_scalar);
  9964. }
  9965. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  9966. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  9967. }
  9968. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  9969. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  9970. // If the source is floating point...
  9971. if (SourceBT && SourceBT->isFloatingPoint()) {
  9972. // ...and the target is floating point...
  9973. if (TargetBT && TargetBT->isFloatingPoint()) {
  9974. // ...then warn if we're dropping FP rank.
  9975. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  9976. QualType(SourceBT, 0), QualType(TargetBT, 0));
  9977. if (Order > 0) {
  9978. // Don't warn about float constants that are precisely
  9979. // representable in the target type.
  9980. Expr::EvalResult result;
  9981. if (E->EvaluateAsRValue(result, S.Context)) {
  9982. // Value might be a float, a float vector, or a float complex.
  9983. if (IsSameFloatAfterCast(result.Val,
  9984. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  9985. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  9986. return;
  9987. }
  9988. if (S.SourceMgr.isInSystemMacro(CC))
  9989. return;
  9990. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  9991. }
  9992. // ... or possibly if we're increasing rank, too
  9993. else if (Order < 0) {
  9994. if (S.SourceMgr.isInSystemMacro(CC))
  9995. return;
  9996. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  9997. }
  9998. return;
  9999. }
  10000. // If the target is integral, always warn.
  10001. if (TargetBT && TargetBT->isInteger()) {
  10002. if (S.SourceMgr.isInSystemMacro(CC))
  10003. return;
  10004. DiagnoseFloatingImpCast(S, E, T, CC);
  10005. }
  10006. // Detect the case where a call result is converted from floating-point to
  10007. // to bool, and the final argument to the call is converted from bool, to
  10008. // discover this typo:
  10009. //
  10010. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  10011. //
  10012. // FIXME: This is an incredibly special case; is there some more general
  10013. // way to detect this class of misplaced-parentheses bug?
  10014. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  10015. // Check last argument of function call to see if it is an
  10016. // implicit cast from a type matching the type the result
  10017. // is being cast to.
  10018. CallExpr *CEx = cast<CallExpr>(E);
  10019. if (unsigned NumArgs = CEx->getNumArgs()) {
  10020. Expr *LastA = CEx->getArg(NumArgs - 1);
  10021. Expr *InnerE = LastA->IgnoreParenImpCasts();
  10022. if (isa<ImplicitCastExpr>(LastA) &&
  10023. InnerE->getType()->isBooleanType()) {
  10024. // Warn on this floating-point to bool conversion
  10025. DiagnoseImpCast(S, E, T, CC,
  10026. diag::warn_impcast_floating_point_to_bool);
  10027. }
  10028. }
  10029. }
  10030. return;
  10031. }
  10032. // Valid casts involving fixed point types should be accounted for here.
  10033. if (Source->isFixedPointType()) {
  10034. if (Target->isUnsaturatedFixedPointType()) {
  10035. Expr::EvalResult Result;
  10036. if (E->EvaluateAsFixedPoint(Result, S.Context,
  10037. Expr::SE_AllowSideEffects)) {
  10038. APFixedPoint Value = Result.Val.getFixedPoint();
  10039. APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
  10040. APFixedPoint MinVal = S.Context.getFixedPointMin(T);
  10041. if (Value > MaxVal || Value < MinVal) {
  10042. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10043. S.PDiag(diag::warn_impcast_fixed_point_range)
  10044. << Value.toString() << T
  10045. << E->getSourceRange()
  10046. << clang::SourceRange(CC));
  10047. return;
  10048. }
  10049. }
  10050. } else if (Target->isIntegerType()) {
  10051. Expr::EvalResult Result;
  10052. if (E->EvaluateAsFixedPoint(Result, S.Context,
  10053. Expr::SE_AllowSideEffects)) {
  10054. APFixedPoint FXResult = Result.Val.getFixedPoint();
  10055. bool Overflowed;
  10056. llvm::APSInt IntResult = FXResult.convertToInt(
  10057. S.Context.getIntWidth(T),
  10058. Target->isSignedIntegerOrEnumerationType(), &Overflowed);
  10059. if (Overflowed) {
  10060. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10061. S.PDiag(diag::warn_impcast_fixed_point_range)
  10062. << FXResult.toString() << T
  10063. << E->getSourceRange()
  10064. << clang::SourceRange(CC));
  10065. return;
  10066. }
  10067. }
  10068. }
  10069. } else if (Target->isUnsaturatedFixedPointType()) {
  10070. if (Source->isIntegerType()) {
  10071. Expr::EvalResult Result;
  10072. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
  10073. llvm::APSInt Value = Result.Val.getInt();
  10074. bool Overflowed;
  10075. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  10076. Value, S.Context.getFixedPointSemantics(T), &Overflowed);
  10077. if (Overflowed) {
  10078. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10079. S.PDiag(diag::warn_impcast_fixed_point_range)
  10080. << Value.toString(/*radix=*/10) << T
  10081. << E->getSourceRange()
  10082. << clang::SourceRange(CC));
  10083. return;
  10084. }
  10085. }
  10086. }
  10087. }
  10088. DiagnoseNullConversion(S, E, T, CC);
  10089. S.DiscardMisalignedMemberAddress(Target, E);
  10090. if (!Source->isIntegerType() || !Target->isIntegerType())
  10091. return;
  10092. // TODO: remove this early return once the false positives for constant->bool
  10093. // in templates, macros, etc, are reduced or removed.
  10094. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  10095. return;
  10096. IntRange SourceRange = GetExprRange(S.Context, E);
  10097. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  10098. if (SourceRange.Width > TargetRange.Width) {
  10099. // If the source is a constant, use a default-on diagnostic.
  10100. // TODO: this should happen for bitfield stores, too.
  10101. Expr::EvalResult Result;
  10102. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
  10103. llvm::APSInt Value(32);
  10104. Value = Result.Val.getInt();
  10105. if (S.SourceMgr.isInSystemMacro(CC))
  10106. return;
  10107. std::string PrettySourceValue = Value.toString(10);
  10108. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10109. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10110. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10111. << PrettySourceValue << PrettyTargetValue
  10112. << E->getType() << T << E->getSourceRange()
  10113. << clang::SourceRange(CC));
  10114. return;
  10115. }
  10116. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  10117. if (S.SourceMgr.isInSystemMacro(CC))
  10118. return;
  10119. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  10120. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  10121. /* pruneControlFlow */ true);
  10122. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  10123. }
  10124. if (TargetRange.Width > SourceRange.Width) {
  10125. if (auto *UO = dyn_cast<UnaryOperator>(E))
  10126. if (UO->getOpcode() == UO_Minus)
  10127. if (Source->isUnsignedIntegerType()) {
  10128. if (Target->isUnsignedIntegerType())
  10129. return DiagnoseImpCast(S, E, T, CC,
  10130. diag::warn_impcast_high_order_zero_bits);
  10131. if (Target->isSignedIntegerType())
  10132. return DiagnoseImpCast(S, E, T, CC,
  10133. diag::warn_impcast_nonnegative_result);
  10134. }
  10135. }
  10136. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  10137. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  10138. // Warn when doing a signed to signed conversion, warn if the positive
  10139. // source value is exactly the width of the target type, which will
  10140. // cause a negative value to be stored.
  10141. Expr::EvalResult Result;
  10142. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
  10143. !S.SourceMgr.isInSystemMacro(CC)) {
  10144. llvm::APSInt Value = Result.Val.getInt();
  10145. if (isSameWidthConstantConversion(S, E, T, CC)) {
  10146. std::string PrettySourceValue = Value.toString(10);
  10147. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10148. S.DiagRuntimeBehavior(
  10149. E->getExprLoc(), E,
  10150. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10151. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10152. << E->getSourceRange() << clang::SourceRange(CC));
  10153. return;
  10154. }
  10155. }
  10156. // Fall through for non-constants to give a sign conversion warning.
  10157. }
  10158. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  10159. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  10160. SourceRange.Width == TargetRange.Width)) {
  10161. if (S.SourceMgr.isInSystemMacro(CC))
  10162. return;
  10163. unsigned DiagID = diag::warn_impcast_integer_sign;
  10164. // Traditionally, gcc has warned about this under -Wsign-compare.
  10165. // We also want to warn about it in -Wconversion.
  10166. // So if -Wconversion is off, use a completely identical diagnostic
  10167. // in the sign-compare group.
  10168. // The conditional-checking code will
  10169. if (ICContext) {
  10170. DiagID = diag::warn_impcast_integer_sign_conditional;
  10171. *ICContext = true;
  10172. }
  10173. return DiagnoseImpCast(S, E, T, CC, DiagID);
  10174. }
  10175. // Diagnose conversions between different enumeration types.
  10176. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  10177. // type, to give us better diagnostics.
  10178. QualType SourceType = E->getType();
  10179. if (!S.getLangOpts().CPlusPlus) {
  10180. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10181. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  10182. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  10183. SourceType = S.Context.getTypeDeclType(Enum);
  10184. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  10185. }
  10186. }
  10187. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  10188. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  10189. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  10190. TargetEnum->getDecl()->hasNameForLinkage() &&
  10191. SourceEnum != TargetEnum) {
  10192. if (S.SourceMgr.isInSystemMacro(CC))
  10193. return;
  10194. return DiagnoseImpCast(S, E, SourceType, T, CC,
  10195. diag::warn_impcast_different_enum_types);
  10196. }
  10197. }
  10198. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10199. SourceLocation CC, QualType T);
  10200. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  10201. SourceLocation CC, bool &ICContext) {
  10202. E = E->IgnoreParenImpCasts();
  10203. if (isa<ConditionalOperator>(E))
  10204. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  10205. AnalyzeImplicitConversions(S, E, CC);
  10206. if (E->getType() != T)
  10207. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  10208. }
  10209. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10210. SourceLocation CC, QualType T) {
  10211. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  10212. bool Suspicious = false;
  10213. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  10214. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  10215. // If -Wconversion would have warned about either of the candidates
  10216. // for a signedness conversion to the context type...
  10217. if (!Suspicious) return;
  10218. // ...but it's currently ignored...
  10219. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  10220. return;
  10221. // ...then check whether it would have warned about either of the
  10222. // candidates for a signedness conversion to the condition type.
  10223. if (E->getType() == T) return;
  10224. Suspicious = false;
  10225. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  10226. E->getType(), CC, &Suspicious);
  10227. if (!Suspicious)
  10228. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  10229. E->getType(), CC, &Suspicious);
  10230. }
  10231. /// Check conversion of given expression to boolean.
  10232. /// Input argument E is a logical expression.
  10233. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  10234. if (S.getLangOpts().Bool)
  10235. return;
  10236. if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
  10237. return;
  10238. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  10239. }
  10240. /// AnalyzeImplicitConversions - Find and report any interesting
  10241. /// implicit conversions in the given expression. There are a couple
  10242. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  10243. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
  10244. SourceLocation CC) {
  10245. QualType T = OrigE->getType();
  10246. Expr *E = OrigE->IgnoreParenImpCasts();
  10247. if (E->isTypeDependent() || E->isValueDependent())
  10248. return;
  10249. // For conditional operators, we analyze the arguments as if they
  10250. // were being fed directly into the output.
  10251. if (isa<ConditionalOperator>(E)) {
  10252. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  10253. CheckConditionalOperator(S, CO, CC, T);
  10254. return;
  10255. }
  10256. // Check implicit argument conversions for function calls.
  10257. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  10258. CheckImplicitArgumentConversions(S, Call, CC);
  10259. // Go ahead and check any implicit conversions we might have skipped.
  10260. // The non-canonical typecheck is just an optimization;
  10261. // CheckImplicitConversion will filter out dead implicit conversions.
  10262. if (E->getType() != T)
  10263. CheckImplicitConversion(S, E, T, CC);
  10264. // Now continue drilling into this expression.
  10265. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  10266. // The bound subexpressions in a PseudoObjectExpr are not reachable
  10267. // as transitive children.
  10268. // FIXME: Use a more uniform representation for this.
  10269. for (auto *SE : POE->semantics())
  10270. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  10271. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  10272. }
  10273. // Skip past explicit casts.
  10274. if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
  10275. E = CE->getSubExpr()->IgnoreParenImpCasts();
  10276. if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
  10277. S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  10278. return AnalyzeImplicitConversions(S, E, CC);
  10279. }
  10280. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10281. // Do a somewhat different check with comparison operators.
  10282. if (BO->isComparisonOp())
  10283. return AnalyzeComparison(S, BO);
  10284. // And with simple assignments.
  10285. if (BO->getOpcode() == BO_Assign)
  10286. return AnalyzeAssignment(S, BO);
  10287. // And with compound assignments.
  10288. if (BO->isAssignmentOp())
  10289. return AnalyzeCompoundAssignment(S, BO);
  10290. }
  10291. // These break the otherwise-useful invariant below. Fortunately,
  10292. // we don't really need to recurse into them, because any internal
  10293. // expressions should have been analyzed already when they were
  10294. // built into statements.
  10295. if (isa<StmtExpr>(E)) return;
  10296. // Don't descend into unevaluated contexts.
  10297. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  10298. // Now just recurse over the expression's children.
  10299. CC = E->getExprLoc();
  10300. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  10301. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  10302. for (Stmt *SubStmt : E->children()) {
  10303. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  10304. if (!ChildExpr)
  10305. continue;
  10306. if (IsLogicalAndOperator &&
  10307. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  10308. // Ignore checking string literals that are in logical and operators.
  10309. // This is a common pattern for asserts.
  10310. continue;
  10311. AnalyzeImplicitConversions(S, ChildExpr, CC);
  10312. }
  10313. if (BO && BO->isLogicalOp()) {
  10314. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  10315. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10316. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10317. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  10318. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10319. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10320. }
  10321. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  10322. if (U->getOpcode() == UO_LNot) {
  10323. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  10324. } else if (U->getOpcode() != UO_AddrOf) {
  10325. if (U->getSubExpr()->getType()->isAtomicType())
  10326. S.Diag(U->getSubExpr()->getBeginLoc(),
  10327. diag::warn_atomic_implicit_seq_cst);
  10328. }
  10329. }
  10330. }
  10331. /// Diagnose integer type and any valid implicit conversion to it.
  10332. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  10333. // Taking into account implicit conversions,
  10334. // allow any integer.
  10335. if (!E->getType()->isIntegerType()) {
  10336. S.Diag(E->getBeginLoc(),
  10337. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  10338. return true;
  10339. }
  10340. // Potentially emit standard warnings for implicit conversions if enabled
  10341. // using -Wconversion.
  10342. CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
  10343. return false;
  10344. }
  10345. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  10346. // Returns true when emitting a warning about taking the address of a reference.
  10347. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  10348. const PartialDiagnostic &PD) {
  10349. E = E->IgnoreParenImpCasts();
  10350. const FunctionDecl *FD = nullptr;
  10351. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  10352. if (!DRE->getDecl()->getType()->isReferenceType())
  10353. return false;
  10354. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10355. if (!M->getMemberDecl()->getType()->isReferenceType())
  10356. return false;
  10357. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  10358. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  10359. return false;
  10360. FD = Call->getDirectCallee();
  10361. } else {
  10362. return false;
  10363. }
  10364. SemaRef.Diag(E->getExprLoc(), PD);
  10365. // If possible, point to location of function.
  10366. if (FD) {
  10367. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  10368. }
  10369. return true;
  10370. }
  10371. // Returns true if the SourceLocation is expanded from any macro body.
  10372. // Returns false if the SourceLocation is invalid, is from not in a macro
  10373. // expansion, or is from expanded from a top-level macro argument.
  10374. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  10375. if (Loc.isInvalid())
  10376. return false;
  10377. while (Loc.isMacroID()) {
  10378. if (SM.isMacroBodyExpansion(Loc))
  10379. return true;
  10380. Loc = SM.getImmediateMacroCallerLoc(Loc);
  10381. }
  10382. return false;
  10383. }
  10384. /// Diagnose pointers that are always non-null.
  10385. /// \param E the expression containing the pointer
  10386. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  10387. /// compared to a null pointer
  10388. /// \param IsEqual True when the comparison is equal to a null pointer
  10389. /// \param Range Extra SourceRange to highlight in the diagnostic
  10390. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  10391. Expr::NullPointerConstantKind NullKind,
  10392. bool IsEqual, SourceRange Range) {
  10393. if (!E)
  10394. return;
  10395. // Don't warn inside macros.
  10396. if (E->getExprLoc().isMacroID()) {
  10397. const SourceManager &SM = getSourceManager();
  10398. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  10399. IsInAnyMacroBody(SM, Range.getBegin()))
  10400. return;
  10401. }
  10402. E = E->IgnoreImpCasts();
  10403. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  10404. if (isa<CXXThisExpr>(E)) {
  10405. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  10406. : diag::warn_this_bool_conversion;
  10407. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  10408. return;
  10409. }
  10410. bool IsAddressOf = false;
  10411. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10412. if (UO->getOpcode() != UO_AddrOf)
  10413. return;
  10414. IsAddressOf = true;
  10415. E = UO->getSubExpr();
  10416. }
  10417. if (IsAddressOf) {
  10418. unsigned DiagID = IsCompare
  10419. ? diag::warn_address_of_reference_null_compare
  10420. : diag::warn_address_of_reference_bool_conversion;
  10421. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  10422. << IsEqual;
  10423. if (CheckForReference(*this, E, PD)) {
  10424. return;
  10425. }
  10426. }
  10427. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  10428. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  10429. std::string Str;
  10430. llvm::raw_string_ostream S(Str);
  10431. E->printPretty(S, nullptr, getPrintingPolicy());
  10432. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  10433. : diag::warn_cast_nonnull_to_bool;
  10434. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  10435. << E->getSourceRange() << Range << IsEqual;
  10436. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  10437. };
  10438. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  10439. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  10440. if (auto *Callee = Call->getDirectCallee()) {
  10441. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  10442. ComplainAboutNonnullParamOrCall(A);
  10443. return;
  10444. }
  10445. }
  10446. }
  10447. // Expect to find a single Decl. Skip anything more complicated.
  10448. ValueDecl *D = nullptr;
  10449. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  10450. D = R->getDecl();
  10451. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10452. D = M->getMemberDecl();
  10453. }
  10454. // Weak Decls can be null.
  10455. if (!D || D->isWeak())
  10456. return;
  10457. // Check for parameter decl with nonnull attribute
  10458. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  10459. if (getCurFunction() &&
  10460. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  10461. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  10462. ComplainAboutNonnullParamOrCall(A);
  10463. return;
  10464. }
  10465. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  10466. // Skip function template not specialized yet.
  10467. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  10468. return;
  10469. auto ParamIter = llvm::find(FD->parameters(), PV);
  10470. assert(ParamIter != FD->param_end());
  10471. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  10472. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  10473. if (!NonNull->args_size()) {
  10474. ComplainAboutNonnullParamOrCall(NonNull);
  10475. return;
  10476. }
  10477. for (const ParamIdx &ArgNo : NonNull->args()) {
  10478. if (ArgNo.getASTIndex() == ParamNo) {
  10479. ComplainAboutNonnullParamOrCall(NonNull);
  10480. return;
  10481. }
  10482. }
  10483. }
  10484. }
  10485. }
  10486. }
  10487. QualType T = D->getType();
  10488. const bool IsArray = T->isArrayType();
  10489. const bool IsFunction = T->isFunctionType();
  10490. // Address of function is used to silence the function warning.
  10491. if (IsAddressOf && IsFunction) {
  10492. return;
  10493. }
  10494. // Found nothing.
  10495. if (!IsAddressOf && !IsFunction && !IsArray)
  10496. return;
  10497. // Pretty print the expression for the diagnostic.
  10498. std::string Str;
  10499. llvm::raw_string_ostream S(Str);
  10500. E->printPretty(S, nullptr, getPrintingPolicy());
  10501. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  10502. : diag::warn_impcast_pointer_to_bool;
  10503. enum {
  10504. AddressOf,
  10505. FunctionPointer,
  10506. ArrayPointer
  10507. } DiagType;
  10508. if (IsAddressOf)
  10509. DiagType = AddressOf;
  10510. else if (IsFunction)
  10511. DiagType = FunctionPointer;
  10512. else if (IsArray)
  10513. DiagType = ArrayPointer;
  10514. else
  10515. llvm_unreachable("Could not determine diagnostic.");
  10516. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  10517. << Range << IsEqual;
  10518. if (!IsFunction)
  10519. return;
  10520. // Suggest '&' to silence the function warning.
  10521. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  10522. << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
  10523. // Check to see if '()' fixit should be emitted.
  10524. QualType ReturnType;
  10525. UnresolvedSet<4> NonTemplateOverloads;
  10526. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  10527. if (ReturnType.isNull())
  10528. return;
  10529. if (IsCompare) {
  10530. // There are two cases here. If there is null constant, the only suggest
  10531. // for a pointer return type. If the null is 0, then suggest if the return
  10532. // type is a pointer or an integer type.
  10533. if (!ReturnType->isPointerType()) {
  10534. if (NullKind == Expr::NPCK_ZeroExpression ||
  10535. NullKind == Expr::NPCK_ZeroLiteral) {
  10536. if (!ReturnType->isIntegerType())
  10537. return;
  10538. } else {
  10539. return;
  10540. }
  10541. }
  10542. } else { // !IsCompare
  10543. // For function to bool, only suggest if the function pointer has bool
  10544. // return type.
  10545. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  10546. return;
  10547. }
  10548. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  10549. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
  10550. }
  10551. /// Diagnoses "dangerous" implicit conversions within the given
  10552. /// expression (which is a full expression). Implements -Wconversion
  10553. /// and -Wsign-compare.
  10554. ///
  10555. /// \param CC the "context" location of the implicit conversion, i.e.
  10556. /// the most location of the syntactic entity requiring the implicit
  10557. /// conversion
  10558. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  10559. // Don't diagnose in unevaluated contexts.
  10560. if (isUnevaluatedContext())
  10561. return;
  10562. // Don't diagnose for value- or type-dependent expressions.
  10563. if (E->isTypeDependent() || E->isValueDependent())
  10564. return;
  10565. // Check for array bounds violations in cases where the check isn't triggered
  10566. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  10567. // ArraySubscriptExpr is on the RHS of a variable initialization.
  10568. CheckArrayAccess(E);
  10569. // This is not the right CC for (e.g.) a variable initialization.
  10570. AnalyzeImplicitConversions(*this, E, CC);
  10571. }
  10572. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  10573. /// Input argument E is a logical expression.
  10574. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  10575. ::CheckBoolLikeConversion(*this, E, CC);
  10576. }
  10577. /// Diagnose when expression is an integer constant expression and its evaluation
  10578. /// results in integer overflow
  10579. void Sema::CheckForIntOverflow (Expr *E) {
  10580. // Use a work list to deal with nested struct initializers.
  10581. SmallVector<Expr *, 2> Exprs(1, E);
  10582. do {
  10583. Expr *OriginalE = Exprs.pop_back_val();
  10584. Expr *E = OriginalE->IgnoreParenCasts();
  10585. if (isa<BinaryOperator>(E)) {
  10586. E->EvaluateForOverflow(Context);
  10587. continue;
  10588. }
  10589. if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
  10590. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  10591. else if (isa<ObjCBoxedExpr>(OriginalE))
  10592. E->EvaluateForOverflow(Context);
  10593. else if (auto Call = dyn_cast<CallExpr>(E))
  10594. Exprs.append(Call->arg_begin(), Call->arg_end());
  10595. else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
  10596. Exprs.append(Message->arg_begin(), Message->arg_end());
  10597. } while (!Exprs.empty());
  10598. }
  10599. namespace {
  10600. /// Visitor for expressions which looks for unsequenced operations on the
  10601. /// same object.
  10602. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  10603. using Base = EvaluatedExprVisitor<SequenceChecker>;
  10604. /// A tree of sequenced regions within an expression. Two regions are
  10605. /// unsequenced if one is an ancestor or a descendent of the other. When we
  10606. /// finish processing an expression with sequencing, such as a comma
  10607. /// expression, we fold its tree nodes into its parent, since they are
  10608. /// unsequenced with respect to nodes we will visit later.
  10609. class SequenceTree {
  10610. struct Value {
  10611. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  10612. unsigned Parent : 31;
  10613. unsigned Merged : 1;
  10614. };
  10615. SmallVector<Value, 8> Values;
  10616. public:
  10617. /// A region within an expression which may be sequenced with respect
  10618. /// to some other region.
  10619. class Seq {
  10620. friend class SequenceTree;
  10621. unsigned Index;
  10622. explicit Seq(unsigned N) : Index(N) {}
  10623. public:
  10624. Seq() : Index(0) {}
  10625. };
  10626. SequenceTree() { Values.push_back(Value(0)); }
  10627. Seq root() const { return Seq(0); }
  10628. /// Create a new sequence of operations, which is an unsequenced
  10629. /// subset of \p Parent. This sequence of operations is sequenced with
  10630. /// respect to other children of \p Parent.
  10631. Seq allocate(Seq Parent) {
  10632. Values.push_back(Value(Parent.Index));
  10633. return Seq(Values.size() - 1);
  10634. }
  10635. /// Merge a sequence of operations into its parent.
  10636. void merge(Seq S) {
  10637. Values[S.Index].Merged = true;
  10638. }
  10639. /// Determine whether two operations are unsequenced. This operation
  10640. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  10641. /// should have been merged into its parent as appropriate.
  10642. bool isUnsequenced(Seq Cur, Seq Old) {
  10643. unsigned C = representative(Cur.Index);
  10644. unsigned Target = representative(Old.Index);
  10645. while (C >= Target) {
  10646. if (C == Target)
  10647. return true;
  10648. C = Values[C].Parent;
  10649. }
  10650. return false;
  10651. }
  10652. private:
  10653. /// Pick a representative for a sequence.
  10654. unsigned representative(unsigned K) {
  10655. if (Values[K].Merged)
  10656. // Perform path compression as we go.
  10657. return Values[K].Parent = representative(Values[K].Parent);
  10658. return K;
  10659. }
  10660. };
  10661. /// An object for which we can track unsequenced uses.
  10662. using Object = NamedDecl *;
  10663. /// Different flavors of object usage which we track. We only track the
  10664. /// least-sequenced usage of each kind.
  10665. enum UsageKind {
  10666. /// A read of an object. Multiple unsequenced reads are OK.
  10667. UK_Use,
  10668. /// A modification of an object which is sequenced before the value
  10669. /// computation of the expression, such as ++n in C++.
  10670. UK_ModAsValue,
  10671. /// A modification of an object which is not sequenced before the value
  10672. /// computation of the expression, such as n++.
  10673. UK_ModAsSideEffect,
  10674. UK_Count = UK_ModAsSideEffect + 1
  10675. };
  10676. struct Usage {
  10677. Expr *Use;
  10678. SequenceTree::Seq Seq;
  10679. Usage() : Use(nullptr), Seq() {}
  10680. };
  10681. struct UsageInfo {
  10682. Usage Uses[UK_Count];
  10683. /// Have we issued a diagnostic for this variable already?
  10684. bool Diagnosed;
  10685. UsageInfo() : Uses(), Diagnosed(false) {}
  10686. };
  10687. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  10688. Sema &SemaRef;
  10689. /// Sequenced regions within the expression.
  10690. SequenceTree Tree;
  10691. /// Declaration modifications and references which we have seen.
  10692. UsageInfoMap UsageMap;
  10693. /// The region we are currently within.
  10694. SequenceTree::Seq Region;
  10695. /// Filled in with declarations which were modified as a side-effect
  10696. /// (that is, post-increment operations).
  10697. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  10698. /// Expressions to check later. We defer checking these to reduce
  10699. /// stack usage.
  10700. SmallVectorImpl<Expr *> &WorkList;
  10701. /// RAII object wrapping the visitation of a sequenced subexpression of an
  10702. /// expression. At the end of this process, the side-effects of the evaluation
  10703. /// become sequenced with respect to the value computation of the result, so
  10704. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  10705. /// UK_ModAsValue.
  10706. struct SequencedSubexpression {
  10707. SequencedSubexpression(SequenceChecker &Self)
  10708. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  10709. Self.ModAsSideEffect = &ModAsSideEffect;
  10710. }
  10711. ~SequencedSubexpression() {
  10712. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  10713. UsageInfo &U = Self.UsageMap[M.first];
  10714. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  10715. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  10716. SideEffectUsage = M.second;
  10717. }
  10718. Self.ModAsSideEffect = OldModAsSideEffect;
  10719. }
  10720. SequenceChecker &Self;
  10721. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  10722. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  10723. };
  10724. /// RAII object wrapping the visitation of a subexpression which we might
  10725. /// choose to evaluate as a constant. If any subexpression is evaluated and
  10726. /// found to be non-constant, this allows us to suppress the evaluation of
  10727. /// the outer expression.
  10728. class EvaluationTracker {
  10729. public:
  10730. EvaluationTracker(SequenceChecker &Self)
  10731. : Self(Self), Prev(Self.EvalTracker) {
  10732. Self.EvalTracker = this;
  10733. }
  10734. ~EvaluationTracker() {
  10735. Self.EvalTracker = Prev;
  10736. if (Prev)
  10737. Prev->EvalOK &= EvalOK;
  10738. }
  10739. bool evaluate(const Expr *E, bool &Result) {
  10740. if (!EvalOK || E->isValueDependent())
  10741. return false;
  10742. EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
  10743. return EvalOK;
  10744. }
  10745. private:
  10746. SequenceChecker &Self;
  10747. EvaluationTracker *Prev;
  10748. bool EvalOK = true;
  10749. } *EvalTracker = nullptr;
  10750. /// Find the object which is produced by the specified expression,
  10751. /// if any.
  10752. Object getObject(Expr *E, bool Mod) const {
  10753. E = E->IgnoreParenCasts();
  10754. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10755. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  10756. return getObject(UO->getSubExpr(), Mod);
  10757. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10758. if (BO->getOpcode() == BO_Comma)
  10759. return getObject(BO->getRHS(), Mod);
  10760. if (Mod && BO->isAssignmentOp())
  10761. return getObject(BO->getLHS(), Mod);
  10762. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  10763. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  10764. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  10765. return ME->getMemberDecl();
  10766. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10767. // FIXME: If this is a reference, map through to its value.
  10768. return DRE->getDecl();
  10769. return nullptr;
  10770. }
  10771. /// Note that an object was modified or used by an expression.
  10772. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  10773. Usage &U = UI.Uses[UK];
  10774. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  10775. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  10776. ModAsSideEffect->push_back(std::make_pair(O, U));
  10777. U.Use = Ref;
  10778. U.Seq = Region;
  10779. }
  10780. }
  10781. /// Check whether a modification or use conflicts with a prior usage.
  10782. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  10783. bool IsModMod) {
  10784. if (UI.Diagnosed)
  10785. return;
  10786. const Usage &U = UI.Uses[OtherKind];
  10787. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  10788. return;
  10789. Expr *Mod = U.Use;
  10790. Expr *ModOrUse = Ref;
  10791. if (OtherKind == UK_Use)
  10792. std::swap(Mod, ModOrUse);
  10793. SemaRef.DiagRuntimeBehavior(
  10794. Mod->getExprLoc(), {Mod, ModOrUse},
  10795. SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
  10796. : diag::warn_unsequenced_mod_use)
  10797. << O << SourceRange(ModOrUse->getExprLoc()));
  10798. UI.Diagnosed = true;
  10799. }
  10800. void notePreUse(Object O, Expr *Use) {
  10801. UsageInfo &U = UsageMap[O];
  10802. // Uses conflict with other modifications.
  10803. checkUsage(O, U, Use, UK_ModAsValue, false);
  10804. }
  10805. void notePostUse(Object O, Expr *Use) {
  10806. UsageInfo &U = UsageMap[O];
  10807. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  10808. addUsage(U, O, Use, UK_Use);
  10809. }
  10810. void notePreMod(Object O, Expr *Mod) {
  10811. UsageInfo &U = UsageMap[O];
  10812. // Modifications conflict with other modifications and with uses.
  10813. checkUsage(O, U, Mod, UK_ModAsValue, true);
  10814. checkUsage(O, U, Mod, UK_Use, false);
  10815. }
  10816. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  10817. UsageInfo &U = UsageMap[O];
  10818. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  10819. addUsage(U, O, Use, UK);
  10820. }
  10821. public:
  10822. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  10823. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  10824. Visit(E);
  10825. }
  10826. void VisitStmt(Stmt *S) {
  10827. // Skip all statements which aren't expressions for now.
  10828. }
  10829. void VisitExpr(Expr *E) {
  10830. // By default, just recurse to evaluated subexpressions.
  10831. Base::VisitStmt(E);
  10832. }
  10833. void VisitCastExpr(CastExpr *E) {
  10834. Object O = Object();
  10835. if (E->getCastKind() == CK_LValueToRValue)
  10836. O = getObject(E->getSubExpr(), false);
  10837. if (O)
  10838. notePreUse(O, E);
  10839. VisitExpr(E);
  10840. if (O)
  10841. notePostUse(O, E);
  10842. }
  10843. void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
  10844. SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
  10845. SequenceTree::Seq AfterRegion = Tree.allocate(Region);
  10846. SequenceTree::Seq OldRegion = Region;
  10847. {
  10848. SequencedSubexpression SeqBefore(*this);
  10849. Region = BeforeRegion;
  10850. Visit(SequencedBefore);
  10851. }
  10852. Region = AfterRegion;
  10853. Visit(SequencedAfter);
  10854. Region = OldRegion;
  10855. Tree.merge(BeforeRegion);
  10856. Tree.merge(AfterRegion);
  10857. }
  10858. void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
  10859. // C++17 [expr.sub]p1:
  10860. // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
  10861. // expression E1 is sequenced before the expression E2.
  10862. if (SemaRef.getLangOpts().CPlusPlus17)
  10863. VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
  10864. else
  10865. Base::VisitStmt(ASE);
  10866. }
  10867. void VisitBinComma(BinaryOperator *BO) {
  10868. // C++11 [expr.comma]p1:
  10869. // Every value computation and side effect associated with the left
  10870. // expression is sequenced before every value computation and side
  10871. // effect associated with the right expression.
  10872. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  10873. }
  10874. void VisitBinAssign(BinaryOperator *BO) {
  10875. // The modification is sequenced after the value computation of the LHS
  10876. // and RHS, so check it before inspecting the operands and update the
  10877. // map afterwards.
  10878. Object O = getObject(BO->getLHS(), true);
  10879. if (!O)
  10880. return VisitExpr(BO);
  10881. notePreMod(O, BO);
  10882. // C++11 [expr.ass]p7:
  10883. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  10884. // only once.
  10885. //
  10886. // Therefore, for a compound assignment operator, O is considered used
  10887. // everywhere except within the evaluation of E1 itself.
  10888. if (isa<CompoundAssignOperator>(BO))
  10889. notePreUse(O, BO);
  10890. Visit(BO->getLHS());
  10891. if (isa<CompoundAssignOperator>(BO))
  10892. notePostUse(O, BO);
  10893. Visit(BO->getRHS());
  10894. // C++11 [expr.ass]p1:
  10895. // the assignment is sequenced [...] before the value computation of the
  10896. // assignment expression.
  10897. // C11 6.5.16/3 has no such rule.
  10898. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  10899. : UK_ModAsSideEffect);
  10900. }
  10901. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  10902. VisitBinAssign(CAO);
  10903. }
  10904. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10905. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10906. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  10907. Object O = getObject(UO->getSubExpr(), true);
  10908. if (!O)
  10909. return VisitExpr(UO);
  10910. notePreMod(O, UO);
  10911. Visit(UO->getSubExpr());
  10912. // C++11 [expr.pre.incr]p1:
  10913. // the expression ++x is equivalent to x+=1
  10914. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  10915. : UK_ModAsSideEffect);
  10916. }
  10917. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  10918. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  10919. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  10920. Object O = getObject(UO->getSubExpr(), true);
  10921. if (!O)
  10922. return VisitExpr(UO);
  10923. notePreMod(O, UO);
  10924. Visit(UO->getSubExpr());
  10925. notePostMod(O, UO, UK_ModAsSideEffect);
  10926. }
  10927. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  10928. void VisitBinLOr(BinaryOperator *BO) {
  10929. // The side-effects of the LHS of an '&&' are sequenced before the
  10930. // value computation of the RHS, and hence before the value computation
  10931. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  10932. // as if they were unconditionally sequenced.
  10933. EvaluationTracker Eval(*this);
  10934. {
  10935. SequencedSubexpression Sequenced(*this);
  10936. Visit(BO->getLHS());
  10937. }
  10938. bool Result;
  10939. if (Eval.evaluate(BO->getLHS(), Result)) {
  10940. if (!Result)
  10941. Visit(BO->getRHS());
  10942. } else {
  10943. // Check for unsequenced operations in the RHS, treating it as an
  10944. // entirely separate evaluation.
  10945. //
  10946. // FIXME: If there are operations in the RHS which are unsequenced
  10947. // with respect to operations outside the RHS, and those operations
  10948. // are unconditionally evaluated, diagnose them.
  10949. WorkList.push_back(BO->getRHS());
  10950. }
  10951. }
  10952. void VisitBinLAnd(BinaryOperator *BO) {
  10953. EvaluationTracker Eval(*this);
  10954. {
  10955. SequencedSubexpression Sequenced(*this);
  10956. Visit(BO->getLHS());
  10957. }
  10958. bool Result;
  10959. if (Eval.evaluate(BO->getLHS(), Result)) {
  10960. if (Result)
  10961. Visit(BO->getRHS());
  10962. } else {
  10963. WorkList.push_back(BO->getRHS());
  10964. }
  10965. }
  10966. // Only visit the condition, unless we can be sure which subexpression will
  10967. // be chosen.
  10968. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  10969. EvaluationTracker Eval(*this);
  10970. {
  10971. SequencedSubexpression Sequenced(*this);
  10972. Visit(CO->getCond());
  10973. }
  10974. bool Result;
  10975. if (Eval.evaluate(CO->getCond(), Result))
  10976. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  10977. else {
  10978. WorkList.push_back(CO->getTrueExpr());
  10979. WorkList.push_back(CO->getFalseExpr());
  10980. }
  10981. }
  10982. void VisitCallExpr(CallExpr *CE) {
  10983. // C++11 [intro.execution]p15:
  10984. // When calling a function [...], every value computation and side effect
  10985. // associated with any argument expression, or with the postfix expression
  10986. // designating the called function, is sequenced before execution of every
  10987. // expression or statement in the body of the function [and thus before
  10988. // the value computation of its result].
  10989. SequencedSubexpression Sequenced(*this);
  10990. Base::VisitCallExpr(CE);
  10991. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  10992. }
  10993. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  10994. // This is a call, so all subexpressions are sequenced before the result.
  10995. SequencedSubexpression Sequenced(*this);
  10996. if (!CCE->isListInitialization())
  10997. return VisitExpr(CCE);
  10998. // In C++11, list initializations are sequenced.
  10999. SmallVector<SequenceTree::Seq, 32> Elts;
  11000. SequenceTree::Seq Parent = Region;
  11001. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  11002. E = CCE->arg_end();
  11003. I != E; ++I) {
  11004. Region = Tree.allocate(Parent);
  11005. Elts.push_back(Region);
  11006. Visit(*I);
  11007. }
  11008. // Forget that the initializers are sequenced.
  11009. Region = Parent;
  11010. for (unsigned I = 0; I < Elts.size(); ++I)
  11011. Tree.merge(Elts[I]);
  11012. }
  11013. void VisitInitListExpr(InitListExpr *ILE) {
  11014. if (!SemaRef.getLangOpts().CPlusPlus11)
  11015. return VisitExpr(ILE);
  11016. // In C++11, list initializations are sequenced.
  11017. SmallVector<SequenceTree::Seq, 32> Elts;
  11018. SequenceTree::Seq Parent = Region;
  11019. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  11020. Expr *E = ILE->getInit(I);
  11021. if (!E) continue;
  11022. Region = Tree.allocate(Parent);
  11023. Elts.push_back(Region);
  11024. Visit(E);
  11025. }
  11026. // Forget that the initializers are sequenced.
  11027. Region = Parent;
  11028. for (unsigned I = 0; I < Elts.size(); ++I)
  11029. Tree.merge(Elts[I]);
  11030. }
  11031. };
  11032. } // namespace
  11033. void Sema::CheckUnsequencedOperations(Expr *E) {
  11034. SmallVector<Expr *, 8> WorkList;
  11035. WorkList.push_back(E);
  11036. while (!WorkList.empty()) {
  11037. Expr *Item = WorkList.pop_back_val();
  11038. SequenceChecker(*this, Item, WorkList);
  11039. }
  11040. }
  11041. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  11042. bool IsConstexpr) {
  11043. CheckImplicitConversions(E, CheckLoc);
  11044. if (!E->isInstantiationDependent())
  11045. CheckUnsequencedOperations(E);
  11046. if (!IsConstexpr && !E->isValueDependent())
  11047. CheckForIntOverflow(E);
  11048. DiagnoseMisalignedMembers();
  11049. }
  11050. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  11051. FieldDecl *BitField,
  11052. Expr *Init) {
  11053. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  11054. }
  11055. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  11056. SourceLocation Loc) {
  11057. if (!PType->isVariablyModifiedType())
  11058. return;
  11059. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  11060. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  11061. return;
  11062. }
  11063. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  11064. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  11065. return;
  11066. }
  11067. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  11068. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  11069. return;
  11070. }
  11071. const ArrayType *AT = S.Context.getAsArrayType(PType);
  11072. if (!AT)
  11073. return;
  11074. if (AT->getSizeModifier() != ArrayType::Star) {
  11075. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  11076. return;
  11077. }
  11078. S.Diag(Loc, diag::err_array_star_in_function_definition);
  11079. }
  11080. /// CheckParmsForFunctionDef - Check that the parameters of the given
  11081. /// function are appropriate for the definition of a function. This
  11082. /// takes care of any checks that cannot be performed on the
  11083. /// declaration itself, e.g., that the types of each of the function
  11084. /// parameters are complete.
  11085. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  11086. bool CheckParameterNames) {
  11087. bool HasInvalidParm = false;
  11088. for (ParmVarDecl *Param : Parameters) {
  11089. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  11090. // function declarator that is part of a function definition of
  11091. // that function shall not have incomplete type.
  11092. //
  11093. // This is also C++ [dcl.fct]p6.
  11094. if (!Param->isInvalidDecl() &&
  11095. RequireCompleteType(Param->getLocation(), Param->getType(),
  11096. diag::err_typecheck_decl_incomplete_type)) {
  11097. Param->setInvalidDecl();
  11098. HasInvalidParm = true;
  11099. }
  11100. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  11101. // declaration of each parameter shall include an identifier.
  11102. if (CheckParameterNames &&
  11103. Param->getIdentifier() == nullptr &&
  11104. !Param->isImplicit() &&
  11105. !getLangOpts().CPlusPlus)
  11106. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  11107. // C99 6.7.5.3p12:
  11108. // If the function declarator is not part of a definition of that
  11109. // function, parameters may have incomplete type and may use the [*]
  11110. // notation in their sequences of declarator specifiers to specify
  11111. // variable length array types.
  11112. QualType PType = Param->getOriginalType();
  11113. // FIXME: This diagnostic should point the '[*]' if source-location
  11114. // information is added for it.
  11115. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  11116. // If the parameter is a c++ class type and it has to be destructed in the
  11117. // callee function, declare the destructor so that it can be called by the
  11118. // callee function. Do not perform any direct access check on the dtor here.
  11119. if (!Param->isInvalidDecl()) {
  11120. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  11121. if (!ClassDecl->isInvalidDecl() &&
  11122. !ClassDecl->hasIrrelevantDestructor() &&
  11123. !ClassDecl->isDependentContext() &&
  11124. ClassDecl->isParamDestroyedInCallee()) {
  11125. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  11126. MarkFunctionReferenced(Param->getLocation(), Destructor);
  11127. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  11128. }
  11129. }
  11130. }
  11131. // Parameters with the pass_object_size attribute only need to be marked
  11132. // constant at function definitions. Because we lack information about
  11133. // whether we're on a declaration or definition when we're instantiating the
  11134. // attribute, we need to check for constness here.
  11135. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  11136. if (!Param->getType().isConstQualified())
  11137. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  11138. << Attr->getSpelling() << 1;
  11139. // Check for parameter names shadowing fields from the class.
  11140. if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
  11141. // The owning context for the parameter should be the function, but we
  11142. // want to see if this function's declaration context is a record.
  11143. DeclContext *DC = Param->getDeclContext();
  11144. if (DC && DC->isFunctionOrMethod()) {
  11145. if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
  11146. CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
  11147. RD, /*DeclIsField*/ false);
  11148. }
  11149. }
  11150. }
  11151. return HasInvalidParm;
  11152. }
  11153. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  11154. /// or MemberExpr.
  11155. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  11156. ASTContext &Context) {
  11157. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  11158. return Context.getDeclAlign(DRE->getDecl());
  11159. if (const auto *ME = dyn_cast<MemberExpr>(E))
  11160. return Context.getDeclAlign(ME->getMemberDecl());
  11161. return TypeAlign;
  11162. }
  11163. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  11164. /// pointer cast increases the alignment requirements.
  11165. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  11166. // This is actually a lot of work to potentially be doing on every
  11167. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  11168. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  11169. return;
  11170. // Ignore dependent types.
  11171. if (T->isDependentType() || Op->getType()->isDependentType())
  11172. return;
  11173. // Require that the destination be a pointer type.
  11174. const PointerType *DestPtr = T->getAs<PointerType>();
  11175. if (!DestPtr) return;
  11176. // If the destination has alignment 1, we're done.
  11177. QualType DestPointee = DestPtr->getPointeeType();
  11178. if (DestPointee->isIncompleteType()) return;
  11179. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  11180. if (DestAlign.isOne()) return;
  11181. // Require that the source be a pointer type.
  11182. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  11183. if (!SrcPtr) return;
  11184. QualType SrcPointee = SrcPtr->getPointeeType();
  11185. // Whitelist casts from cv void*. We already implicitly
  11186. // whitelisted casts to cv void*, since they have alignment 1.
  11187. // Also whitelist casts involving incomplete types, which implicitly
  11188. // includes 'void'.
  11189. if (SrcPointee->isIncompleteType()) return;
  11190. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  11191. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  11192. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  11193. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  11194. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  11195. if (UO->getOpcode() == UO_AddrOf)
  11196. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  11197. }
  11198. if (SrcAlign >= DestAlign) return;
  11199. Diag(TRange.getBegin(), diag::warn_cast_align)
  11200. << Op->getType() << T
  11201. << static_cast<unsigned>(SrcAlign.getQuantity())
  11202. << static_cast<unsigned>(DestAlign.getQuantity())
  11203. << TRange << Op->getSourceRange();
  11204. }
  11205. /// Check whether this array fits the idiom of a size-one tail padded
  11206. /// array member of a struct.
  11207. ///
  11208. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  11209. /// commonly used to emulate flexible arrays in C89 code.
  11210. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  11211. const NamedDecl *ND) {
  11212. if (Size != 1 || !ND) return false;
  11213. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  11214. if (!FD) return false;
  11215. // Don't consider sizes resulting from macro expansions or template argument
  11216. // substitution to form C89 tail-padded arrays.
  11217. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  11218. while (TInfo) {
  11219. TypeLoc TL = TInfo->getTypeLoc();
  11220. // Look through typedefs.
  11221. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  11222. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  11223. TInfo = TDL->getTypeSourceInfo();
  11224. continue;
  11225. }
  11226. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  11227. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  11228. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  11229. return false;
  11230. }
  11231. break;
  11232. }
  11233. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  11234. if (!RD) return false;
  11235. if (RD->isUnion()) return false;
  11236. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  11237. if (!CRD->isStandardLayout()) return false;
  11238. }
  11239. // See if this is the last field decl in the record.
  11240. const Decl *D = FD;
  11241. while ((D = D->getNextDeclInContext()))
  11242. if (isa<FieldDecl>(D))
  11243. return false;
  11244. return true;
  11245. }
  11246. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  11247. const ArraySubscriptExpr *ASE,
  11248. bool AllowOnePastEnd, bool IndexNegated) {
  11249. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  11250. if (IndexExpr->isValueDependent())
  11251. return;
  11252. const Type *EffectiveType =
  11253. BaseExpr->getType()->getPointeeOrArrayElementType();
  11254. BaseExpr = BaseExpr->IgnoreParenCasts();
  11255. const ConstantArrayType *ArrayTy =
  11256. Context.getAsConstantArrayType(BaseExpr->getType());
  11257. if (!ArrayTy)
  11258. return;
  11259. const Type *BaseType = ArrayTy->getElementType().getTypePtr();
  11260. if (EffectiveType->isDependentType() || BaseType->isDependentType())
  11261. return;
  11262. Expr::EvalResult Result;
  11263. if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
  11264. return;
  11265. llvm::APSInt index = Result.Val.getInt();
  11266. if (IndexNegated)
  11267. index = -index;
  11268. const NamedDecl *ND = nullptr;
  11269. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11270. ND = DRE->getDecl();
  11271. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11272. ND = ME->getMemberDecl();
  11273. if (index.isUnsigned() || !index.isNegative()) {
  11274. // It is possible that the type of the base expression after
  11275. // IgnoreParenCasts is incomplete, even though the type of the base
  11276. // expression before IgnoreParenCasts is complete (see PR39746 for an
  11277. // example). In this case we have no information about whether the array
  11278. // access exceeds the array bounds. However we can still diagnose an array
  11279. // access which precedes the array bounds.
  11280. if (BaseType->isIncompleteType())
  11281. return;
  11282. llvm::APInt size = ArrayTy->getSize();
  11283. if (!size.isStrictlyPositive())
  11284. return;
  11285. if (BaseType != EffectiveType) {
  11286. // Make sure we're comparing apples to apples when comparing index to size
  11287. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  11288. uint64_t array_typesize = Context.getTypeSize(BaseType);
  11289. // Handle ptrarith_typesize being zero, such as when casting to void*
  11290. if (!ptrarith_typesize) ptrarith_typesize = 1;
  11291. if (ptrarith_typesize != array_typesize) {
  11292. // There's a cast to a different size type involved
  11293. uint64_t ratio = array_typesize / ptrarith_typesize;
  11294. // TODO: Be smarter about handling cases where array_typesize is not a
  11295. // multiple of ptrarith_typesize
  11296. if (ptrarith_typesize * ratio == array_typesize)
  11297. size *= llvm::APInt(size.getBitWidth(), ratio);
  11298. }
  11299. }
  11300. if (size.getBitWidth() > index.getBitWidth())
  11301. index = index.zext(size.getBitWidth());
  11302. else if (size.getBitWidth() < index.getBitWidth())
  11303. size = size.zext(index.getBitWidth());
  11304. // For array subscripting the index must be less than size, but for pointer
  11305. // arithmetic also allow the index (offset) to be equal to size since
  11306. // computing the next address after the end of the array is legal and
  11307. // commonly done e.g. in C++ iterators and range-based for loops.
  11308. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  11309. return;
  11310. // Also don't warn for arrays of size 1 which are members of some
  11311. // structure. These are often used to approximate flexible arrays in C89
  11312. // code.
  11313. if (IsTailPaddedMemberArray(*this, size, ND))
  11314. return;
  11315. // Suppress the warning if the subscript expression (as identified by the
  11316. // ']' location) and the index expression are both from macro expansions
  11317. // within a system header.
  11318. if (ASE) {
  11319. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  11320. ASE->getRBracketLoc());
  11321. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  11322. SourceLocation IndexLoc =
  11323. SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
  11324. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  11325. return;
  11326. }
  11327. }
  11328. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  11329. if (ASE)
  11330. DiagID = diag::warn_array_index_exceeds_bounds;
  11331. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11332. PDiag(DiagID) << index.toString(10, true)
  11333. << size.toString(10, true)
  11334. << (unsigned)size.getLimitedValue(~0U)
  11335. << IndexExpr->getSourceRange());
  11336. } else {
  11337. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  11338. if (!ASE) {
  11339. DiagID = diag::warn_ptr_arith_precedes_bounds;
  11340. if (index.isNegative()) index = -index;
  11341. }
  11342. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11343. PDiag(DiagID) << index.toString(10, true)
  11344. << IndexExpr->getSourceRange());
  11345. }
  11346. if (!ND) {
  11347. // Try harder to find a NamedDecl to point at in the note.
  11348. while (const ArraySubscriptExpr *ASE =
  11349. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  11350. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  11351. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11352. ND = DRE->getDecl();
  11353. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11354. ND = ME->getMemberDecl();
  11355. }
  11356. if (ND)
  11357. DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
  11358. PDiag(diag::note_array_index_out_of_bounds)
  11359. << ND->getDeclName());
  11360. }
  11361. void Sema::CheckArrayAccess(const Expr *expr) {
  11362. int AllowOnePastEnd = 0;
  11363. while (expr) {
  11364. expr = expr->IgnoreParenImpCasts();
  11365. switch (expr->getStmtClass()) {
  11366. case Stmt::ArraySubscriptExprClass: {
  11367. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  11368. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  11369. AllowOnePastEnd > 0);
  11370. expr = ASE->getBase();
  11371. break;
  11372. }
  11373. case Stmt::MemberExprClass: {
  11374. expr = cast<MemberExpr>(expr)->getBase();
  11375. break;
  11376. }
  11377. case Stmt::OMPArraySectionExprClass: {
  11378. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  11379. if (ASE->getLowerBound())
  11380. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  11381. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  11382. return;
  11383. }
  11384. case Stmt::UnaryOperatorClass: {
  11385. // Only unwrap the * and & unary operators
  11386. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  11387. expr = UO->getSubExpr();
  11388. switch (UO->getOpcode()) {
  11389. case UO_AddrOf:
  11390. AllowOnePastEnd++;
  11391. break;
  11392. case UO_Deref:
  11393. AllowOnePastEnd--;
  11394. break;
  11395. default:
  11396. return;
  11397. }
  11398. break;
  11399. }
  11400. case Stmt::ConditionalOperatorClass: {
  11401. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  11402. if (const Expr *lhs = cond->getLHS())
  11403. CheckArrayAccess(lhs);
  11404. if (const Expr *rhs = cond->getRHS())
  11405. CheckArrayAccess(rhs);
  11406. return;
  11407. }
  11408. case Stmt::CXXOperatorCallExprClass: {
  11409. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  11410. for (const auto *Arg : OCE->arguments())
  11411. CheckArrayAccess(Arg);
  11412. return;
  11413. }
  11414. default:
  11415. return;
  11416. }
  11417. }
  11418. }
  11419. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  11420. namespace {
  11421. struct RetainCycleOwner {
  11422. VarDecl *Variable = nullptr;
  11423. SourceRange Range;
  11424. SourceLocation Loc;
  11425. bool Indirect = false;
  11426. RetainCycleOwner() = default;
  11427. void setLocsFrom(Expr *e) {
  11428. Loc = e->getExprLoc();
  11429. Range = e->getSourceRange();
  11430. }
  11431. };
  11432. } // namespace
  11433. /// Consider whether capturing the given variable can possibly lead to
  11434. /// a retain cycle.
  11435. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  11436. // In ARC, it's captured strongly iff the variable has __strong
  11437. // lifetime. In MRR, it's captured strongly if the variable is
  11438. // __block and has an appropriate type.
  11439. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11440. return false;
  11441. owner.Variable = var;
  11442. if (ref)
  11443. owner.setLocsFrom(ref);
  11444. return true;
  11445. }
  11446. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11447. while (true) {
  11448. e = e->IgnoreParens();
  11449. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  11450. switch (cast->getCastKind()) {
  11451. case CK_BitCast:
  11452. case CK_LValueBitCast:
  11453. case CK_LValueToRValue:
  11454. case CK_ARCReclaimReturnedObject:
  11455. e = cast->getSubExpr();
  11456. continue;
  11457. default:
  11458. return false;
  11459. }
  11460. }
  11461. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  11462. ObjCIvarDecl *ivar = ref->getDecl();
  11463. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11464. return false;
  11465. // Try to find a retain cycle in the base.
  11466. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  11467. return false;
  11468. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  11469. owner.Indirect = true;
  11470. return true;
  11471. }
  11472. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  11473. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  11474. if (!var) return false;
  11475. return considerVariable(var, ref, owner);
  11476. }
  11477. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  11478. if (member->isArrow()) return false;
  11479. // Don't count this as an indirect ownership.
  11480. e = member->getBase();
  11481. continue;
  11482. }
  11483. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  11484. // Only pay attention to pseudo-objects on property references.
  11485. ObjCPropertyRefExpr *pre
  11486. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  11487. ->IgnoreParens());
  11488. if (!pre) return false;
  11489. if (pre->isImplicitProperty()) return false;
  11490. ObjCPropertyDecl *property = pre->getExplicitProperty();
  11491. if (!property->isRetaining() &&
  11492. !(property->getPropertyIvarDecl() &&
  11493. property->getPropertyIvarDecl()->getType()
  11494. .getObjCLifetime() == Qualifiers::OCL_Strong))
  11495. return false;
  11496. owner.Indirect = true;
  11497. if (pre->isSuperReceiver()) {
  11498. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  11499. if (!owner.Variable)
  11500. return false;
  11501. owner.Loc = pre->getLocation();
  11502. owner.Range = pre->getSourceRange();
  11503. return true;
  11504. }
  11505. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  11506. ->getSourceExpr());
  11507. continue;
  11508. }
  11509. // Array ivars?
  11510. return false;
  11511. }
  11512. }
  11513. namespace {
  11514. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  11515. ASTContext &Context;
  11516. VarDecl *Variable;
  11517. Expr *Capturer = nullptr;
  11518. bool VarWillBeReased = false;
  11519. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  11520. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  11521. Context(Context), Variable(variable) {}
  11522. void VisitDeclRefExpr(DeclRefExpr *ref) {
  11523. if (ref->getDecl() == Variable && !Capturer)
  11524. Capturer = ref;
  11525. }
  11526. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  11527. if (Capturer) return;
  11528. Visit(ref->getBase());
  11529. if (Capturer && ref->isFreeIvar())
  11530. Capturer = ref;
  11531. }
  11532. void VisitBlockExpr(BlockExpr *block) {
  11533. // Look inside nested blocks
  11534. if (block->getBlockDecl()->capturesVariable(Variable))
  11535. Visit(block->getBlockDecl()->getBody());
  11536. }
  11537. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  11538. if (Capturer) return;
  11539. if (OVE->getSourceExpr())
  11540. Visit(OVE->getSourceExpr());
  11541. }
  11542. void VisitBinaryOperator(BinaryOperator *BinOp) {
  11543. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  11544. return;
  11545. Expr *LHS = BinOp->getLHS();
  11546. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  11547. if (DRE->getDecl() != Variable)
  11548. return;
  11549. if (Expr *RHS = BinOp->getRHS()) {
  11550. RHS = RHS->IgnoreParenCasts();
  11551. llvm::APSInt Value;
  11552. VarWillBeReased =
  11553. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  11554. }
  11555. }
  11556. }
  11557. };
  11558. } // namespace
  11559. /// Check whether the given argument is a block which captures a
  11560. /// variable.
  11561. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11562. assert(owner.Variable && owner.Loc.isValid());
  11563. e = e->IgnoreParenCasts();
  11564. // Look through [^{...} copy] and Block_copy(^{...}).
  11565. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  11566. Selector Cmd = ME->getSelector();
  11567. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  11568. e = ME->getInstanceReceiver();
  11569. if (!e)
  11570. return nullptr;
  11571. e = e->IgnoreParenCasts();
  11572. }
  11573. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  11574. if (CE->getNumArgs() == 1) {
  11575. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  11576. if (Fn) {
  11577. const IdentifierInfo *FnI = Fn->getIdentifier();
  11578. if (FnI && FnI->isStr("_Block_copy")) {
  11579. e = CE->getArg(0)->IgnoreParenCasts();
  11580. }
  11581. }
  11582. }
  11583. }
  11584. BlockExpr *block = dyn_cast<BlockExpr>(e);
  11585. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  11586. return nullptr;
  11587. FindCaptureVisitor visitor(S.Context, owner.Variable);
  11588. visitor.Visit(block->getBlockDecl()->getBody());
  11589. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  11590. }
  11591. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  11592. RetainCycleOwner &owner) {
  11593. assert(capturer);
  11594. assert(owner.Variable && owner.Loc.isValid());
  11595. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  11596. << owner.Variable << capturer->getSourceRange();
  11597. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  11598. << owner.Indirect << owner.Range;
  11599. }
  11600. /// Check for a keyword selector that starts with the word 'add' or
  11601. /// 'set'.
  11602. static bool isSetterLikeSelector(Selector sel) {
  11603. if (sel.isUnarySelector()) return false;
  11604. StringRef str = sel.getNameForSlot(0);
  11605. while (!str.empty() && str.front() == '_') str = str.substr(1);
  11606. if (str.startswith("set"))
  11607. str = str.substr(3);
  11608. else if (str.startswith("add")) {
  11609. // Specially whitelist 'addOperationWithBlock:'.
  11610. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  11611. return false;
  11612. str = str.substr(3);
  11613. }
  11614. else
  11615. return false;
  11616. if (str.empty()) return true;
  11617. return !isLowercase(str.front());
  11618. }
  11619. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  11620. ObjCMessageExpr *Message) {
  11621. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  11622. Message->getReceiverInterface(),
  11623. NSAPI::ClassId_NSMutableArray);
  11624. if (!IsMutableArray) {
  11625. return None;
  11626. }
  11627. Selector Sel = Message->getSelector();
  11628. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  11629. S.NSAPIObj->getNSArrayMethodKind(Sel);
  11630. if (!MKOpt) {
  11631. return None;
  11632. }
  11633. NSAPI::NSArrayMethodKind MK = *MKOpt;
  11634. switch (MK) {
  11635. case NSAPI::NSMutableArr_addObject:
  11636. case NSAPI::NSMutableArr_insertObjectAtIndex:
  11637. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  11638. return 0;
  11639. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  11640. return 1;
  11641. default:
  11642. return None;
  11643. }
  11644. return None;
  11645. }
  11646. static
  11647. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  11648. ObjCMessageExpr *Message) {
  11649. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  11650. Message->getReceiverInterface(),
  11651. NSAPI::ClassId_NSMutableDictionary);
  11652. if (!IsMutableDictionary) {
  11653. return None;
  11654. }
  11655. Selector Sel = Message->getSelector();
  11656. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  11657. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  11658. if (!MKOpt) {
  11659. return None;
  11660. }
  11661. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  11662. switch (MK) {
  11663. case NSAPI::NSMutableDict_setObjectForKey:
  11664. case NSAPI::NSMutableDict_setValueForKey:
  11665. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  11666. return 0;
  11667. default:
  11668. return None;
  11669. }
  11670. return None;
  11671. }
  11672. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  11673. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  11674. Message->getReceiverInterface(),
  11675. NSAPI::ClassId_NSMutableSet);
  11676. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  11677. Message->getReceiverInterface(),
  11678. NSAPI::ClassId_NSMutableOrderedSet);
  11679. if (!IsMutableSet && !IsMutableOrderedSet) {
  11680. return None;
  11681. }
  11682. Selector Sel = Message->getSelector();
  11683. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  11684. if (!MKOpt) {
  11685. return None;
  11686. }
  11687. NSAPI::NSSetMethodKind MK = *MKOpt;
  11688. switch (MK) {
  11689. case NSAPI::NSMutableSet_addObject:
  11690. case NSAPI::NSOrderedSet_setObjectAtIndex:
  11691. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  11692. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  11693. return 0;
  11694. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  11695. return 1;
  11696. }
  11697. return None;
  11698. }
  11699. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  11700. if (!Message->isInstanceMessage()) {
  11701. return;
  11702. }
  11703. Optional<int> ArgOpt;
  11704. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  11705. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  11706. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  11707. return;
  11708. }
  11709. int ArgIndex = *ArgOpt;
  11710. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  11711. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  11712. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  11713. }
  11714. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  11715. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11716. if (ArgRE->isObjCSelfExpr()) {
  11717. Diag(Message->getSourceRange().getBegin(),
  11718. diag::warn_objc_circular_container)
  11719. << ArgRE->getDecl() << StringRef("'super'");
  11720. }
  11721. }
  11722. } else {
  11723. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  11724. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  11725. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  11726. }
  11727. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  11728. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11729. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  11730. ValueDecl *Decl = ReceiverRE->getDecl();
  11731. Diag(Message->getSourceRange().getBegin(),
  11732. diag::warn_objc_circular_container)
  11733. << Decl << Decl;
  11734. if (!ArgRE->isObjCSelfExpr()) {
  11735. Diag(Decl->getLocation(),
  11736. diag::note_objc_circular_container_declared_here)
  11737. << Decl;
  11738. }
  11739. }
  11740. }
  11741. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  11742. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  11743. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  11744. ObjCIvarDecl *Decl = IvarRE->getDecl();
  11745. Diag(Message->getSourceRange().getBegin(),
  11746. diag::warn_objc_circular_container)
  11747. << Decl << Decl;
  11748. Diag(Decl->getLocation(),
  11749. diag::note_objc_circular_container_declared_here)
  11750. << Decl;
  11751. }
  11752. }
  11753. }
  11754. }
  11755. }
  11756. /// Check a message send to see if it's likely to cause a retain cycle.
  11757. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  11758. // Only check instance methods whose selector looks like a setter.
  11759. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  11760. return;
  11761. // Try to find a variable that the receiver is strongly owned by.
  11762. RetainCycleOwner owner;
  11763. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  11764. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  11765. return;
  11766. } else {
  11767. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  11768. owner.Variable = getCurMethodDecl()->getSelfDecl();
  11769. owner.Loc = msg->getSuperLoc();
  11770. owner.Range = msg->getSuperLoc();
  11771. }
  11772. // Check whether the receiver is captured by any of the arguments.
  11773. const ObjCMethodDecl *MD = msg->getMethodDecl();
  11774. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  11775. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  11776. // noescape blocks should not be retained by the method.
  11777. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  11778. continue;
  11779. return diagnoseRetainCycle(*this, capturer, owner);
  11780. }
  11781. }
  11782. }
  11783. /// Check a property assign to see if it's likely to cause a retain cycle.
  11784. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  11785. RetainCycleOwner owner;
  11786. if (!findRetainCycleOwner(*this, receiver, owner))
  11787. return;
  11788. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  11789. diagnoseRetainCycle(*this, capturer, owner);
  11790. }
  11791. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  11792. RetainCycleOwner Owner;
  11793. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  11794. return;
  11795. // Because we don't have an expression for the variable, we have to set the
  11796. // location explicitly here.
  11797. Owner.Loc = Var->getLocation();
  11798. Owner.Range = Var->getSourceRange();
  11799. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  11800. diagnoseRetainCycle(*this, Capturer, Owner);
  11801. }
  11802. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  11803. Expr *RHS, bool isProperty) {
  11804. // Check if RHS is an Objective-C object literal, which also can get
  11805. // immediately zapped in a weak reference. Note that we explicitly
  11806. // allow ObjCStringLiterals, since those are designed to never really die.
  11807. RHS = RHS->IgnoreParenImpCasts();
  11808. // This enum needs to match with the 'select' in
  11809. // warn_objc_arc_literal_assign (off-by-1).
  11810. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  11811. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  11812. return false;
  11813. S.Diag(Loc, diag::warn_arc_literal_assign)
  11814. << (unsigned) Kind
  11815. << (isProperty ? 0 : 1)
  11816. << RHS->getSourceRange();
  11817. return true;
  11818. }
  11819. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  11820. Qualifiers::ObjCLifetime LT,
  11821. Expr *RHS, bool isProperty) {
  11822. // Strip off any implicit cast added to get to the one ARC-specific.
  11823. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11824. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11825. S.Diag(Loc, diag::warn_arc_retained_assign)
  11826. << (LT == Qualifiers::OCL_ExplicitNone)
  11827. << (isProperty ? 0 : 1)
  11828. << RHS->getSourceRange();
  11829. return true;
  11830. }
  11831. RHS = cast->getSubExpr();
  11832. }
  11833. if (LT == Qualifiers::OCL_Weak &&
  11834. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  11835. return true;
  11836. return false;
  11837. }
  11838. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  11839. QualType LHS, Expr *RHS) {
  11840. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  11841. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  11842. return false;
  11843. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  11844. return true;
  11845. return false;
  11846. }
  11847. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  11848. Expr *LHS, Expr *RHS) {
  11849. QualType LHSType;
  11850. // PropertyRef on LHS type need be directly obtained from
  11851. // its declaration as it has a PseudoType.
  11852. ObjCPropertyRefExpr *PRE
  11853. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  11854. if (PRE && !PRE->isImplicitProperty()) {
  11855. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11856. if (PD)
  11857. LHSType = PD->getType();
  11858. }
  11859. if (LHSType.isNull())
  11860. LHSType = LHS->getType();
  11861. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  11862. if (LT == Qualifiers::OCL_Weak) {
  11863. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  11864. getCurFunction()->markSafeWeakUse(LHS);
  11865. }
  11866. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  11867. return;
  11868. // FIXME. Check for other life times.
  11869. if (LT != Qualifiers::OCL_None)
  11870. return;
  11871. if (PRE) {
  11872. if (PRE->isImplicitProperty())
  11873. return;
  11874. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11875. if (!PD)
  11876. return;
  11877. unsigned Attributes = PD->getPropertyAttributes();
  11878. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  11879. // when 'assign' attribute was not explicitly specified
  11880. // by user, ignore it and rely on property type itself
  11881. // for lifetime info.
  11882. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  11883. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  11884. LHSType->isObjCRetainableType())
  11885. return;
  11886. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11887. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11888. Diag(Loc, diag::warn_arc_retained_property_assign)
  11889. << RHS->getSourceRange();
  11890. return;
  11891. }
  11892. RHS = cast->getSubExpr();
  11893. }
  11894. }
  11895. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  11896. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  11897. return;
  11898. }
  11899. }
  11900. }
  11901. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  11902. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  11903. SourceLocation StmtLoc,
  11904. const NullStmt *Body) {
  11905. // Do not warn if the body is a macro that expands to nothing, e.g:
  11906. //
  11907. // #define CALL(x)
  11908. // if (condition)
  11909. // CALL(0);
  11910. if (Body->hasLeadingEmptyMacro())
  11911. return false;
  11912. // Get line numbers of statement and body.
  11913. bool StmtLineInvalid;
  11914. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  11915. &StmtLineInvalid);
  11916. if (StmtLineInvalid)
  11917. return false;
  11918. bool BodyLineInvalid;
  11919. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  11920. &BodyLineInvalid);
  11921. if (BodyLineInvalid)
  11922. return false;
  11923. // Warn if null statement and body are on the same line.
  11924. if (StmtLine != BodyLine)
  11925. return false;
  11926. return true;
  11927. }
  11928. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  11929. const Stmt *Body,
  11930. unsigned DiagID) {
  11931. // Since this is a syntactic check, don't emit diagnostic for template
  11932. // instantiations, this just adds noise.
  11933. if (CurrentInstantiationScope)
  11934. return;
  11935. // The body should be a null statement.
  11936. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  11937. if (!NBody)
  11938. return;
  11939. // Do the usual checks.
  11940. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  11941. return;
  11942. Diag(NBody->getSemiLoc(), DiagID);
  11943. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  11944. }
  11945. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  11946. const Stmt *PossibleBody) {
  11947. assert(!CurrentInstantiationScope); // Ensured by caller
  11948. SourceLocation StmtLoc;
  11949. const Stmt *Body;
  11950. unsigned DiagID;
  11951. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  11952. StmtLoc = FS->getRParenLoc();
  11953. Body = FS->getBody();
  11954. DiagID = diag::warn_empty_for_body;
  11955. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  11956. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  11957. Body = WS->getBody();
  11958. DiagID = diag::warn_empty_while_body;
  11959. } else
  11960. return; // Neither `for' nor `while'.
  11961. // The body should be a null statement.
  11962. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  11963. if (!NBody)
  11964. return;
  11965. // Skip expensive checks if diagnostic is disabled.
  11966. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  11967. return;
  11968. // Do the usual checks.
  11969. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  11970. return;
  11971. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  11972. // noise level low, emit diagnostics only if for/while is followed by a
  11973. // CompoundStmt, e.g.:
  11974. // for (int i = 0; i < n; i++);
  11975. // {
  11976. // a(i);
  11977. // }
  11978. // or if for/while is followed by a statement with more indentation
  11979. // than for/while itself:
  11980. // for (int i = 0; i < n; i++);
  11981. // a(i);
  11982. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  11983. if (!ProbableTypo) {
  11984. bool BodyColInvalid;
  11985. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  11986. PossibleBody->getBeginLoc(), &BodyColInvalid);
  11987. if (BodyColInvalid)
  11988. return;
  11989. bool StmtColInvalid;
  11990. unsigned StmtCol =
  11991. SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
  11992. if (StmtColInvalid)
  11993. return;
  11994. if (BodyCol > StmtCol)
  11995. ProbableTypo = true;
  11996. }
  11997. if (ProbableTypo) {
  11998. Diag(NBody->getSemiLoc(), DiagID);
  11999. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  12000. }
  12001. }
  12002. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  12003. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  12004. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  12005. SourceLocation OpLoc) {
  12006. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  12007. return;
  12008. if (inTemplateInstantiation())
  12009. return;
  12010. // Strip parens and casts away.
  12011. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  12012. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  12013. // Check for a call expression
  12014. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  12015. if (!CE || CE->getNumArgs() != 1)
  12016. return;
  12017. // Check for a call to std::move
  12018. if (!CE->isCallToStdMove())
  12019. return;
  12020. // Get argument from std::move
  12021. RHSExpr = CE->getArg(0);
  12022. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  12023. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  12024. // Two DeclRefExpr's, check that the decls are the same.
  12025. if (LHSDeclRef && RHSDeclRef) {
  12026. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12027. return;
  12028. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12029. RHSDeclRef->getDecl()->getCanonicalDecl())
  12030. return;
  12031. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12032. << LHSExpr->getSourceRange()
  12033. << RHSExpr->getSourceRange();
  12034. return;
  12035. }
  12036. // Member variables require a different approach to check for self moves.
  12037. // MemberExpr's are the same if every nested MemberExpr refers to the same
  12038. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  12039. // the base Expr's are CXXThisExpr's.
  12040. const Expr *LHSBase = LHSExpr;
  12041. const Expr *RHSBase = RHSExpr;
  12042. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  12043. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  12044. if (!LHSME || !RHSME)
  12045. return;
  12046. while (LHSME && RHSME) {
  12047. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  12048. RHSME->getMemberDecl()->getCanonicalDecl())
  12049. return;
  12050. LHSBase = LHSME->getBase();
  12051. RHSBase = RHSME->getBase();
  12052. LHSME = dyn_cast<MemberExpr>(LHSBase);
  12053. RHSME = dyn_cast<MemberExpr>(RHSBase);
  12054. }
  12055. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  12056. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  12057. if (LHSDeclRef && RHSDeclRef) {
  12058. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12059. return;
  12060. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12061. RHSDeclRef->getDecl()->getCanonicalDecl())
  12062. return;
  12063. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12064. << LHSExpr->getSourceRange()
  12065. << RHSExpr->getSourceRange();
  12066. return;
  12067. }
  12068. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  12069. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12070. << LHSExpr->getSourceRange()
  12071. << RHSExpr->getSourceRange();
  12072. }
  12073. //===--- Layout compatibility ----------------------------------------------//
  12074. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  12075. /// Check if two enumeration types are layout-compatible.
  12076. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  12077. // C++11 [dcl.enum] p8:
  12078. // Two enumeration types are layout-compatible if they have the same
  12079. // underlying type.
  12080. return ED1->isComplete() && ED2->isComplete() &&
  12081. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  12082. }
  12083. /// Check if two fields are layout-compatible.
  12084. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  12085. FieldDecl *Field2) {
  12086. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  12087. return false;
  12088. if (Field1->isBitField() != Field2->isBitField())
  12089. return false;
  12090. if (Field1->isBitField()) {
  12091. // Make sure that the bit-fields are the same length.
  12092. unsigned Bits1 = Field1->getBitWidthValue(C);
  12093. unsigned Bits2 = Field2->getBitWidthValue(C);
  12094. if (Bits1 != Bits2)
  12095. return false;
  12096. }
  12097. return true;
  12098. }
  12099. /// Check if two standard-layout structs are layout-compatible.
  12100. /// (C++11 [class.mem] p17)
  12101. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  12102. RecordDecl *RD2) {
  12103. // If both records are C++ classes, check that base classes match.
  12104. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  12105. // If one of records is a CXXRecordDecl we are in C++ mode,
  12106. // thus the other one is a CXXRecordDecl, too.
  12107. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  12108. // Check number of base classes.
  12109. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  12110. return false;
  12111. // Check the base classes.
  12112. for (CXXRecordDecl::base_class_const_iterator
  12113. Base1 = D1CXX->bases_begin(),
  12114. BaseEnd1 = D1CXX->bases_end(),
  12115. Base2 = D2CXX->bases_begin();
  12116. Base1 != BaseEnd1;
  12117. ++Base1, ++Base2) {
  12118. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  12119. return false;
  12120. }
  12121. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  12122. // If only RD2 is a C++ class, it should have zero base classes.
  12123. if (D2CXX->getNumBases() > 0)
  12124. return false;
  12125. }
  12126. // Check the fields.
  12127. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  12128. Field2End = RD2->field_end(),
  12129. Field1 = RD1->field_begin(),
  12130. Field1End = RD1->field_end();
  12131. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  12132. if (!isLayoutCompatible(C, *Field1, *Field2))
  12133. return false;
  12134. }
  12135. if (Field1 != Field1End || Field2 != Field2End)
  12136. return false;
  12137. return true;
  12138. }
  12139. /// Check if two standard-layout unions are layout-compatible.
  12140. /// (C++11 [class.mem] p18)
  12141. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  12142. RecordDecl *RD2) {
  12143. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  12144. for (auto *Field2 : RD2->fields())
  12145. UnmatchedFields.insert(Field2);
  12146. for (auto *Field1 : RD1->fields()) {
  12147. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  12148. I = UnmatchedFields.begin(),
  12149. E = UnmatchedFields.end();
  12150. for ( ; I != E; ++I) {
  12151. if (isLayoutCompatible(C, Field1, *I)) {
  12152. bool Result = UnmatchedFields.erase(*I);
  12153. (void) Result;
  12154. assert(Result);
  12155. break;
  12156. }
  12157. }
  12158. if (I == E)
  12159. return false;
  12160. }
  12161. return UnmatchedFields.empty();
  12162. }
  12163. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  12164. RecordDecl *RD2) {
  12165. if (RD1->isUnion() != RD2->isUnion())
  12166. return false;
  12167. if (RD1->isUnion())
  12168. return isLayoutCompatibleUnion(C, RD1, RD2);
  12169. else
  12170. return isLayoutCompatibleStruct(C, RD1, RD2);
  12171. }
  12172. /// Check if two types are layout-compatible in C++11 sense.
  12173. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  12174. if (T1.isNull() || T2.isNull())
  12175. return false;
  12176. // C++11 [basic.types] p11:
  12177. // If two types T1 and T2 are the same type, then T1 and T2 are
  12178. // layout-compatible types.
  12179. if (C.hasSameType(T1, T2))
  12180. return true;
  12181. T1 = T1.getCanonicalType().getUnqualifiedType();
  12182. T2 = T2.getCanonicalType().getUnqualifiedType();
  12183. const Type::TypeClass TC1 = T1->getTypeClass();
  12184. const Type::TypeClass TC2 = T2->getTypeClass();
  12185. if (TC1 != TC2)
  12186. return false;
  12187. if (TC1 == Type::Enum) {
  12188. return isLayoutCompatible(C,
  12189. cast<EnumType>(T1)->getDecl(),
  12190. cast<EnumType>(T2)->getDecl());
  12191. } else if (TC1 == Type::Record) {
  12192. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  12193. return false;
  12194. return isLayoutCompatible(C,
  12195. cast<RecordType>(T1)->getDecl(),
  12196. cast<RecordType>(T2)->getDecl());
  12197. }
  12198. return false;
  12199. }
  12200. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  12201. /// Given a type tag expression find the type tag itself.
  12202. ///
  12203. /// \param TypeExpr Type tag expression, as it appears in user's code.
  12204. ///
  12205. /// \param VD Declaration of an identifier that appears in a type tag.
  12206. ///
  12207. /// \param MagicValue Type tag magic value.
  12208. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  12209. const ValueDecl **VD, uint64_t *MagicValue) {
  12210. while(true) {
  12211. if (!TypeExpr)
  12212. return false;
  12213. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  12214. switch (TypeExpr->getStmtClass()) {
  12215. case Stmt::UnaryOperatorClass: {
  12216. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  12217. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  12218. TypeExpr = UO->getSubExpr();
  12219. continue;
  12220. }
  12221. return false;
  12222. }
  12223. case Stmt::DeclRefExprClass: {
  12224. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  12225. *VD = DRE->getDecl();
  12226. return true;
  12227. }
  12228. case Stmt::IntegerLiteralClass: {
  12229. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  12230. llvm::APInt MagicValueAPInt = IL->getValue();
  12231. if (MagicValueAPInt.getActiveBits() <= 64) {
  12232. *MagicValue = MagicValueAPInt.getZExtValue();
  12233. return true;
  12234. } else
  12235. return false;
  12236. }
  12237. case Stmt::BinaryConditionalOperatorClass:
  12238. case Stmt::ConditionalOperatorClass: {
  12239. const AbstractConditionalOperator *ACO =
  12240. cast<AbstractConditionalOperator>(TypeExpr);
  12241. bool Result;
  12242. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  12243. if (Result)
  12244. TypeExpr = ACO->getTrueExpr();
  12245. else
  12246. TypeExpr = ACO->getFalseExpr();
  12247. continue;
  12248. }
  12249. return false;
  12250. }
  12251. case Stmt::BinaryOperatorClass: {
  12252. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  12253. if (BO->getOpcode() == BO_Comma) {
  12254. TypeExpr = BO->getRHS();
  12255. continue;
  12256. }
  12257. return false;
  12258. }
  12259. default:
  12260. return false;
  12261. }
  12262. }
  12263. }
  12264. /// Retrieve the C type corresponding to type tag TypeExpr.
  12265. ///
  12266. /// \param TypeExpr Expression that specifies a type tag.
  12267. ///
  12268. /// \param MagicValues Registered magic values.
  12269. ///
  12270. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  12271. /// kind.
  12272. ///
  12273. /// \param TypeInfo Information about the corresponding C type.
  12274. ///
  12275. /// \returns true if the corresponding C type was found.
  12276. static bool GetMatchingCType(
  12277. const IdentifierInfo *ArgumentKind,
  12278. const Expr *TypeExpr, const ASTContext &Ctx,
  12279. const llvm::DenseMap<Sema::TypeTagMagicValue,
  12280. Sema::TypeTagData> *MagicValues,
  12281. bool &FoundWrongKind,
  12282. Sema::TypeTagData &TypeInfo) {
  12283. FoundWrongKind = false;
  12284. // Variable declaration that has type_tag_for_datatype attribute.
  12285. const ValueDecl *VD = nullptr;
  12286. uint64_t MagicValue;
  12287. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  12288. return false;
  12289. if (VD) {
  12290. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  12291. if (I->getArgumentKind() != ArgumentKind) {
  12292. FoundWrongKind = true;
  12293. return false;
  12294. }
  12295. TypeInfo.Type = I->getMatchingCType();
  12296. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  12297. TypeInfo.MustBeNull = I->getMustBeNull();
  12298. return true;
  12299. }
  12300. return false;
  12301. }
  12302. if (!MagicValues)
  12303. return false;
  12304. llvm::DenseMap<Sema::TypeTagMagicValue,
  12305. Sema::TypeTagData>::const_iterator I =
  12306. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  12307. if (I == MagicValues->end())
  12308. return false;
  12309. TypeInfo = I->second;
  12310. return true;
  12311. }
  12312. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  12313. uint64_t MagicValue, QualType Type,
  12314. bool LayoutCompatible,
  12315. bool MustBeNull) {
  12316. if (!TypeTagForDatatypeMagicValues)
  12317. TypeTagForDatatypeMagicValues.reset(
  12318. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  12319. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  12320. (*TypeTagForDatatypeMagicValues)[Magic] =
  12321. TypeTagData(Type, LayoutCompatible, MustBeNull);
  12322. }
  12323. static bool IsSameCharType(QualType T1, QualType T2) {
  12324. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  12325. if (!BT1)
  12326. return false;
  12327. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  12328. if (!BT2)
  12329. return false;
  12330. BuiltinType::Kind T1Kind = BT1->getKind();
  12331. BuiltinType::Kind T2Kind = BT2->getKind();
  12332. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  12333. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  12334. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  12335. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  12336. }
  12337. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  12338. const ArrayRef<const Expr *> ExprArgs,
  12339. SourceLocation CallSiteLoc) {
  12340. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  12341. bool IsPointerAttr = Attr->getIsPointer();
  12342. // Retrieve the argument representing the 'type_tag'.
  12343. unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
  12344. if (TypeTagIdxAST >= ExprArgs.size()) {
  12345. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12346. << 0 << Attr->getTypeTagIdx().getSourceIndex();
  12347. return;
  12348. }
  12349. const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
  12350. bool FoundWrongKind;
  12351. TypeTagData TypeInfo;
  12352. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  12353. TypeTagForDatatypeMagicValues.get(),
  12354. FoundWrongKind, TypeInfo)) {
  12355. if (FoundWrongKind)
  12356. Diag(TypeTagExpr->getExprLoc(),
  12357. diag::warn_type_tag_for_datatype_wrong_kind)
  12358. << TypeTagExpr->getSourceRange();
  12359. return;
  12360. }
  12361. // Retrieve the argument representing the 'arg_idx'.
  12362. unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
  12363. if (ArgumentIdxAST >= ExprArgs.size()) {
  12364. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12365. << 1 << Attr->getArgumentIdx().getSourceIndex();
  12366. return;
  12367. }
  12368. const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
  12369. if (IsPointerAttr) {
  12370. // Skip implicit cast of pointer to `void *' (as a function argument).
  12371. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  12372. if (ICE->getType()->isVoidPointerType() &&
  12373. ICE->getCastKind() == CK_BitCast)
  12374. ArgumentExpr = ICE->getSubExpr();
  12375. }
  12376. QualType ArgumentType = ArgumentExpr->getType();
  12377. // Passing a `void*' pointer shouldn't trigger a warning.
  12378. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  12379. return;
  12380. if (TypeInfo.MustBeNull) {
  12381. // Type tag with matching void type requires a null pointer.
  12382. if (!ArgumentExpr->isNullPointerConstant(Context,
  12383. Expr::NPC_ValueDependentIsNotNull)) {
  12384. Diag(ArgumentExpr->getExprLoc(),
  12385. diag::warn_type_safety_null_pointer_required)
  12386. << ArgumentKind->getName()
  12387. << ArgumentExpr->getSourceRange()
  12388. << TypeTagExpr->getSourceRange();
  12389. }
  12390. return;
  12391. }
  12392. QualType RequiredType = TypeInfo.Type;
  12393. if (IsPointerAttr)
  12394. RequiredType = Context.getPointerType(RequiredType);
  12395. bool mismatch = false;
  12396. if (!TypeInfo.LayoutCompatible) {
  12397. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  12398. // C++11 [basic.fundamental] p1:
  12399. // Plain char, signed char, and unsigned char are three distinct types.
  12400. //
  12401. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  12402. // char' depending on the current char signedness mode.
  12403. if (mismatch)
  12404. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  12405. RequiredType->getPointeeType())) ||
  12406. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  12407. mismatch = false;
  12408. } else
  12409. if (IsPointerAttr)
  12410. mismatch = !isLayoutCompatible(Context,
  12411. ArgumentType->getPointeeType(),
  12412. RequiredType->getPointeeType());
  12413. else
  12414. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  12415. if (mismatch)
  12416. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  12417. << ArgumentType << ArgumentKind
  12418. << TypeInfo.LayoutCompatible << RequiredType
  12419. << ArgumentExpr->getSourceRange()
  12420. << TypeTagExpr->getSourceRange();
  12421. }
  12422. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  12423. CharUnits Alignment) {
  12424. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  12425. }
  12426. void Sema::DiagnoseMisalignedMembers() {
  12427. for (MisalignedMember &m : MisalignedMembers) {
  12428. const NamedDecl *ND = m.RD;
  12429. if (ND->getName().empty()) {
  12430. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  12431. ND = TD;
  12432. }
  12433. Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
  12434. << m.MD << ND << m.E->getSourceRange();
  12435. }
  12436. MisalignedMembers.clear();
  12437. }
  12438. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  12439. E = E->IgnoreParens();
  12440. if (!T->isPointerType() && !T->isIntegerType())
  12441. return;
  12442. if (isa<UnaryOperator>(E) &&
  12443. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  12444. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  12445. if (isa<MemberExpr>(Op)) {
  12446. auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
  12447. if (MA != MisalignedMembers.end() &&
  12448. (T->isIntegerType() ||
  12449. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  12450. Context.getTypeAlignInChars(
  12451. T->getPointeeType()) <= MA->Alignment))))
  12452. MisalignedMembers.erase(MA);
  12453. }
  12454. }
  12455. }
  12456. void Sema::RefersToMemberWithReducedAlignment(
  12457. Expr *E,
  12458. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  12459. Action) {
  12460. const auto *ME = dyn_cast<MemberExpr>(E);
  12461. if (!ME)
  12462. return;
  12463. // No need to check expressions with an __unaligned-qualified type.
  12464. if (E->getType().getQualifiers().hasUnaligned())
  12465. return;
  12466. // For a chain of MemberExpr like "a.b.c.d" this list
  12467. // will keep FieldDecl's like [d, c, b].
  12468. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  12469. const MemberExpr *TopME = nullptr;
  12470. bool AnyIsPacked = false;
  12471. do {
  12472. QualType BaseType = ME->getBase()->getType();
  12473. if (ME->isArrow())
  12474. BaseType = BaseType->getPointeeType();
  12475. RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
  12476. if (RD->isInvalidDecl())
  12477. return;
  12478. ValueDecl *MD = ME->getMemberDecl();
  12479. auto *FD = dyn_cast<FieldDecl>(MD);
  12480. // We do not care about non-data members.
  12481. if (!FD || FD->isInvalidDecl())
  12482. return;
  12483. AnyIsPacked =
  12484. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  12485. ReverseMemberChain.push_back(FD);
  12486. TopME = ME;
  12487. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  12488. } while (ME);
  12489. assert(TopME && "We did not compute a topmost MemberExpr!");
  12490. // Not the scope of this diagnostic.
  12491. if (!AnyIsPacked)
  12492. return;
  12493. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  12494. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  12495. // TODO: The innermost base of the member expression may be too complicated.
  12496. // For now, just disregard these cases. This is left for future
  12497. // improvement.
  12498. if (!DRE && !isa<CXXThisExpr>(TopBase))
  12499. return;
  12500. // Alignment expected by the whole expression.
  12501. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  12502. // No need to do anything else with this case.
  12503. if (ExpectedAlignment.isOne())
  12504. return;
  12505. // Synthesize offset of the whole access.
  12506. CharUnits Offset;
  12507. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  12508. I++) {
  12509. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  12510. }
  12511. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  12512. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  12513. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  12514. // The base expression of the innermost MemberExpr may give
  12515. // stronger guarantees than the class containing the member.
  12516. if (DRE && !TopME->isArrow()) {
  12517. const ValueDecl *VD = DRE->getDecl();
  12518. if (!VD->getType()->isReferenceType())
  12519. CompleteObjectAlignment =
  12520. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  12521. }
  12522. // Check if the synthesized offset fulfills the alignment.
  12523. if (Offset % ExpectedAlignment != 0 ||
  12524. // It may fulfill the offset it but the effective alignment may still be
  12525. // lower than the expected expression alignment.
  12526. CompleteObjectAlignment < ExpectedAlignment) {
  12527. // If this happens, we want to determine a sensible culprit of this.
  12528. // Intuitively, watching the chain of member expressions from right to
  12529. // left, we start with the required alignment (as required by the field
  12530. // type) but some packed attribute in that chain has reduced the alignment.
  12531. // It may happen that another packed structure increases it again. But if
  12532. // we are here such increase has not been enough. So pointing the first
  12533. // FieldDecl that either is packed or else its RecordDecl is,
  12534. // seems reasonable.
  12535. FieldDecl *FD = nullptr;
  12536. CharUnits Alignment;
  12537. for (FieldDecl *FDI : ReverseMemberChain) {
  12538. if (FDI->hasAttr<PackedAttr>() ||
  12539. FDI->getParent()->hasAttr<PackedAttr>()) {
  12540. FD = FDI;
  12541. Alignment = std::min(
  12542. Context.getTypeAlignInChars(FD->getType()),
  12543. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  12544. break;
  12545. }
  12546. }
  12547. assert(FD && "We did not find a packed FieldDecl!");
  12548. Action(E, FD->getParent(), FD, Alignment);
  12549. }
  12550. }
  12551. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  12552. using namespace std::placeholders;
  12553. RefersToMemberWithReducedAlignment(
  12554. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  12555. _2, _3, _4));
  12556. }