SemaChecking.cpp 556 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258
  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/SaveAndRestore.h"
  87. #include "llvm/Support/raw_ostream.h"
  88. #include <algorithm>
  89. #include <cassert>
  90. #include <cstddef>
  91. #include <cstdint>
  92. #include <functional>
  93. #include <limits>
  94. #include <string>
  95. #include <tuple>
  96. #include <utility>
  97. using namespace clang;
  98. using namespace sema;
  99. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  100. unsigned ByteNo) const {
  101. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  102. Context.getTargetInfo());
  103. }
  104. /// Checks that a call expression's argument count is the desired number.
  105. /// This is useful when doing custom type-checking. Returns true on error.
  106. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  107. unsigned argCount = call->getNumArgs();
  108. if (argCount == desiredArgCount) return false;
  109. if (argCount < desiredArgCount)
  110. return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
  111. << 0 /*function call*/ << desiredArgCount << argCount
  112. << call->getSourceRange();
  113. // Highlight all the excess arguments.
  114. SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
  115. call->getArg(argCount - 1)->getEndLoc());
  116. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  117. << 0 /*function call*/ << desiredArgCount << argCount
  118. << call->getArg(1)->getSourceRange();
  119. }
  120. /// Check that the first argument to __builtin_annotation is an integer
  121. /// and the second argument is a non-wide string literal.
  122. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  123. if (checkArgCount(S, TheCall, 2))
  124. return true;
  125. // First argument should be an integer.
  126. Expr *ValArg = TheCall->getArg(0);
  127. QualType Ty = ValArg->getType();
  128. if (!Ty->isIntegerType()) {
  129. S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
  130. << ValArg->getSourceRange();
  131. return true;
  132. }
  133. // Second argument should be a constant string.
  134. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  135. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  136. if (!Literal || !Literal->isAscii()) {
  137. S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
  138. << StrArg->getSourceRange();
  139. return true;
  140. }
  141. TheCall->setType(Ty);
  142. return false;
  143. }
  144. static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
  145. // We need at least one argument.
  146. if (TheCall->getNumArgs() < 1) {
  147. S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  148. << 0 << 1 << TheCall->getNumArgs()
  149. << TheCall->getCallee()->getSourceRange();
  150. return true;
  151. }
  152. // All arguments should be wide string literals.
  153. for (Expr *Arg : TheCall->arguments()) {
  154. auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  155. if (!Literal || !Literal->isWide()) {
  156. S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
  157. << Arg->getSourceRange();
  158. return true;
  159. }
  160. }
  161. return false;
  162. }
  163. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  164. /// result type to the corresponding pointer type.
  165. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  166. if (checkArgCount(S, TheCall, 1))
  167. return true;
  168. ExprResult Arg(TheCall->getArg(0));
  169. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
  170. if (ResultType.isNull())
  171. return true;
  172. TheCall->setArg(0, Arg.get());
  173. TheCall->setType(ResultType);
  174. return false;
  175. }
  176. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
  177. if (checkArgCount(S, TheCall, 3))
  178. return true;
  179. // First two arguments should be integers.
  180. for (unsigned I = 0; I < 2; ++I) {
  181. ExprResult Arg = TheCall->getArg(I);
  182. QualType Ty = Arg.get()->getType();
  183. if (!Ty->isIntegerType()) {
  184. S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
  185. << Ty << Arg.get()->getSourceRange();
  186. return true;
  187. }
  188. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  189. S.getASTContext(), Ty, /*consume*/ false);
  190. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  191. if (Arg.isInvalid())
  192. return true;
  193. TheCall->setArg(I, Arg.get());
  194. }
  195. // Third argument should be a pointer to a non-const integer.
  196. // IRGen correctly handles volatile, restrict, and address spaces, and
  197. // the other qualifiers aren't possible.
  198. {
  199. ExprResult Arg = TheCall->getArg(2);
  200. QualType Ty = Arg.get()->getType();
  201. const auto *PtrTy = Ty->getAs<PointerType>();
  202. if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
  203. !PtrTy->getPointeeType().isConstQualified())) {
  204. S.Diag(Arg.get()->getBeginLoc(),
  205. diag::err_overflow_builtin_must_be_ptr_int)
  206. << Ty << Arg.get()->getSourceRange();
  207. return true;
  208. }
  209. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  210. S.getASTContext(), Ty, /*consume*/ false);
  211. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  212. if (Arg.isInvalid())
  213. return true;
  214. TheCall->setArg(2, Arg.get());
  215. }
  216. return false;
  217. }
  218. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  219. if (checkArgCount(S, BuiltinCall, 2))
  220. return true;
  221. SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
  222. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  223. Expr *Call = BuiltinCall->getArg(0);
  224. Expr *Chain = BuiltinCall->getArg(1);
  225. if (Call->getStmtClass() != Stmt::CallExprClass) {
  226. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  227. << Call->getSourceRange();
  228. return true;
  229. }
  230. auto CE = cast<CallExpr>(Call);
  231. if (CE->getCallee()->getType()->isBlockPointerType()) {
  232. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  233. << Call->getSourceRange();
  234. return true;
  235. }
  236. const Decl *TargetDecl = CE->getCalleeDecl();
  237. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  238. if (FD->getBuiltinID()) {
  239. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  240. << Call->getSourceRange();
  241. return true;
  242. }
  243. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  244. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  245. << Call->getSourceRange();
  246. return true;
  247. }
  248. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  249. if (ChainResult.isInvalid())
  250. return true;
  251. if (!ChainResult.get()->getType()->isPointerType()) {
  252. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  253. << Chain->getSourceRange();
  254. return true;
  255. }
  256. QualType ReturnTy = CE->getCallReturnType(S.Context);
  257. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  258. QualType BuiltinTy = S.Context.getFunctionType(
  259. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  260. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  261. Builtin =
  262. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  263. BuiltinCall->setType(CE->getType());
  264. BuiltinCall->setValueKind(CE->getValueKind());
  265. BuiltinCall->setObjectKind(CE->getObjectKind());
  266. BuiltinCall->setCallee(Builtin);
  267. BuiltinCall->setArg(1, ChainResult.get());
  268. return false;
  269. }
  270. /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
  271. /// __builtin_*_chk function, then use the object size argument specified in the
  272. /// source. Otherwise, infer the object size using __builtin_object_size.
  273. void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
  274. CallExpr *TheCall) {
  275. // FIXME: There are some more useful checks we could be doing here:
  276. // - Analyze the format string of sprintf to see how much of buffer is used.
  277. // - Evaluate strlen of strcpy arguments, use as object size.
  278. if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
  279. isConstantEvaluated())
  280. return;
  281. unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
  282. if (!BuiltinID)
  283. return;
  284. unsigned DiagID = 0;
  285. bool IsChkVariant = false;
  286. unsigned SizeIndex, ObjectIndex;
  287. switch (BuiltinID) {
  288. default:
  289. return;
  290. case Builtin::BI__builtin___memcpy_chk:
  291. case Builtin::BI__builtin___memmove_chk:
  292. case Builtin::BI__builtin___memset_chk:
  293. case Builtin::BI__builtin___strlcat_chk:
  294. case Builtin::BI__builtin___strlcpy_chk:
  295. case Builtin::BI__builtin___strncat_chk:
  296. case Builtin::BI__builtin___strncpy_chk:
  297. case Builtin::BI__builtin___stpncpy_chk:
  298. case Builtin::BI__builtin___memccpy_chk: {
  299. DiagID = diag::warn_builtin_chk_overflow;
  300. IsChkVariant = true;
  301. SizeIndex = TheCall->getNumArgs() - 2;
  302. ObjectIndex = TheCall->getNumArgs() - 1;
  303. break;
  304. }
  305. case Builtin::BI__builtin___snprintf_chk:
  306. case Builtin::BI__builtin___vsnprintf_chk: {
  307. DiagID = diag::warn_builtin_chk_overflow;
  308. IsChkVariant = true;
  309. SizeIndex = 1;
  310. ObjectIndex = 3;
  311. break;
  312. }
  313. case Builtin::BIstrncat:
  314. case Builtin::BI__builtin_strncat:
  315. case Builtin::BIstrncpy:
  316. case Builtin::BI__builtin_strncpy:
  317. case Builtin::BIstpncpy:
  318. case Builtin::BI__builtin_stpncpy: {
  319. // Whether these functions overflow depends on the runtime strlen of the
  320. // string, not just the buffer size, so emitting the "always overflow"
  321. // diagnostic isn't quite right. We should still diagnose passing a buffer
  322. // size larger than the destination buffer though; this is a runtime abort
  323. // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
  324. DiagID = diag::warn_fortify_source_size_mismatch;
  325. SizeIndex = TheCall->getNumArgs() - 1;
  326. ObjectIndex = 0;
  327. break;
  328. }
  329. case Builtin::BImemcpy:
  330. case Builtin::BI__builtin_memcpy:
  331. case Builtin::BImemmove:
  332. case Builtin::BI__builtin_memmove:
  333. case Builtin::BImemset:
  334. case Builtin::BI__builtin_memset: {
  335. DiagID = diag::warn_fortify_source_overflow;
  336. SizeIndex = TheCall->getNumArgs() - 1;
  337. ObjectIndex = 0;
  338. break;
  339. }
  340. case Builtin::BIsnprintf:
  341. case Builtin::BI__builtin_snprintf:
  342. case Builtin::BIvsnprintf:
  343. case Builtin::BI__builtin_vsnprintf: {
  344. DiagID = diag::warn_fortify_source_size_mismatch;
  345. SizeIndex = 1;
  346. ObjectIndex = 0;
  347. break;
  348. }
  349. }
  350. llvm::APSInt ObjectSize;
  351. // For __builtin___*_chk, the object size is explicitly provided by the caller
  352. // (usually using __builtin_object_size). Use that value to check this call.
  353. if (IsChkVariant) {
  354. Expr::EvalResult Result;
  355. Expr *SizeArg = TheCall->getArg(ObjectIndex);
  356. if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
  357. return;
  358. ObjectSize = Result.Val.getInt();
  359. // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
  360. } else {
  361. // If the parameter has a pass_object_size attribute, then we should use its
  362. // (potentially) more strict checking mode. Otherwise, conservatively assume
  363. // type 0.
  364. int BOSType = 0;
  365. if (const auto *POS =
  366. FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
  367. BOSType = POS->getType();
  368. Expr *ObjArg = TheCall->getArg(ObjectIndex);
  369. uint64_t Result;
  370. if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
  371. return;
  372. // Get the object size in the target's size_t width.
  373. const TargetInfo &TI = getASTContext().getTargetInfo();
  374. unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
  375. ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
  376. }
  377. // Evaluate the number of bytes of the object that this call will use.
  378. Expr::EvalResult Result;
  379. Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
  380. if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
  381. return;
  382. llvm::APSInt UsedSize = Result.Val.getInt();
  383. if (UsedSize.ule(ObjectSize))
  384. return;
  385. StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
  386. // Skim off the details of whichever builtin was called to produce a better
  387. // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
  388. if (IsChkVariant) {
  389. FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
  390. FunctionName = FunctionName.drop_back(std::strlen("_chk"));
  391. } else if (FunctionName.startswith("__builtin_")) {
  392. FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
  393. }
  394. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  395. PDiag(DiagID)
  396. << FunctionName << ObjectSize.toString(/*Radix=*/10)
  397. << UsedSize.toString(/*Radix=*/10));
  398. }
  399. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  400. Scope::ScopeFlags NeededScopeFlags,
  401. unsigned DiagID) {
  402. // Scopes aren't available during instantiation. Fortunately, builtin
  403. // functions cannot be template args so they cannot be formed through template
  404. // instantiation. Therefore checking once during the parse is sufficient.
  405. if (SemaRef.inTemplateInstantiation())
  406. return false;
  407. Scope *S = SemaRef.getCurScope();
  408. while (S && !S->isSEHExceptScope())
  409. S = S->getParent();
  410. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  411. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  412. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  413. << DRE->getDecl()->getIdentifier();
  414. return true;
  415. }
  416. return false;
  417. }
  418. static inline bool isBlockPointer(Expr *Arg) {
  419. return Arg->getType()->isBlockPointerType();
  420. }
  421. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  422. /// void*, which is a requirement of device side enqueue.
  423. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  424. const BlockPointerType *BPT =
  425. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  426. ArrayRef<QualType> Params =
  427. BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
  428. unsigned ArgCounter = 0;
  429. bool IllegalParams = false;
  430. // Iterate through the block parameters until either one is found that is not
  431. // a local void*, or the block is valid.
  432. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  433. I != E; ++I, ++ArgCounter) {
  434. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  435. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  436. LangAS::opencl_local) {
  437. // Get the location of the error. If a block literal has been passed
  438. // (BlockExpr) then we can point straight to the offending argument,
  439. // else we just point to the variable reference.
  440. SourceLocation ErrorLoc;
  441. if (isa<BlockExpr>(BlockArg)) {
  442. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  443. ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
  444. } else if (isa<DeclRefExpr>(BlockArg)) {
  445. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
  446. }
  447. S.Diag(ErrorLoc,
  448. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  449. IllegalParams = true;
  450. }
  451. }
  452. return IllegalParams;
  453. }
  454. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  455. if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
  456. S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
  457. << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
  458. return true;
  459. }
  460. return false;
  461. }
  462. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  463. if (checkArgCount(S, TheCall, 2))
  464. return true;
  465. if (checkOpenCLSubgroupExt(S, TheCall))
  466. return true;
  467. // First argument is an ndrange_t type.
  468. Expr *NDRangeArg = TheCall->getArg(0);
  469. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  470. S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  471. << TheCall->getDirectCallee() << "'ndrange_t'";
  472. return true;
  473. }
  474. Expr *BlockArg = TheCall->getArg(1);
  475. if (!isBlockPointer(BlockArg)) {
  476. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  477. << TheCall->getDirectCallee() << "block";
  478. return true;
  479. }
  480. return checkOpenCLBlockArgs(S, BlockArg);
  481. }
  482. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  483. /// get_kernel_work_group_size
  484. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  485. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  486. if (checkArgCount(S, TheCall, 1))
  487. return true;
  488. Expr *BlockArg = TheCall->getArg(0);
  489. if (!isBlockPointer(BlockArg)) {
  490. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  491. << TheCall->getDirectCallee() << "block";
  492. return true;
  493. }
  494. return checkOpenCLBlockArgs(S, BlockArg);
  495. }
  496. /// Diagnose integer type and any valid implicit conversion to it.
  497. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  498. const QualType &IntType);
  499. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  500. unsigned Start, unsigned End) {
  501. bool IllegalParams = false;
  502. for (unsigned I = Start; I <= End; ++I)
  503. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  504. S.Context.getSizeType());
  505. return IllegalParams;
  506. }
  507. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  508. /// 'local void*' parameter of passed block.
  509. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  510. Expr *BlockArg,
  511. unsigned NumNonVarArgs) {
  512. const BlockPointerType *BPT =
  513. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  514. unsigned NumBlockParams =
  515. BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
  516. unsigned TotalNumArgs = TheCall->getNumArgs();
  517. // For each argument passed to the block, a corresponding uint needs to
  518. // be passed to describe the size of the local memory.
  519. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  520. S.Diag(TheCall->getBeginLoc(),
  521. diag::err_opencl_enqueue_kernel_local_size_args);
  522. return true;
  523. }
  524. // Check that the sizes of the local memory are specified by integers.
  525. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  526. TotalNumArgs - 1);
  527. }
  528. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  529. /// overload formats specified in Table 6.13.17.1.
  530. /// int enqueue_kernel(queue_t queue,
  531. /// kernel_enqueue_flags_t flags,
  532. /// const ndrange_t ndrange,
  533. /// void (^block)(void))
  534. /// int enqueue_kernel(queue_t queue,
  535. /// kernel_enqueue_flags_t flags,
  536. /// const ndrange_t ndrange,
  537. /// uint num_events_in_wait_list,
  538. /// clk_event_t *event_wait_list,
  539. /// clk_event_t *event_ret,
  540. /// void (^block)(void))
  541. /// int enqueue_kernel(queue_t queue,
  542. /// kernel_enqueue_flags_t flags,
  543. /// const ndrange_t ndrange,
  544. /// void (^block)(local void*, ...),
  545. /// uint size0, ...)
  546. /// int enqueue_kernel(queue_t queue,
  547. /// kernel_enqueue_flags_t flags,
  548. /// const ndrange_t ndrange,
  549. /// uint num_events_in_wait_list,
  550. /// clk_event_t *event_wait_list,
  551. /// clk_event_t *event_ret,
  552. /// void (^block)(local void*, ...),
  553. /// uint size0, ...)
  554. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  555. unsigned NumArgs = TheCall->getNumArgs();
  556. if (NumArgs < 4) {
  557. S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
  558. return true;
  559. }
  560. Expr *Arg0 = TheCall->getArg(0);
  561. Expr *Arg1 = TheCall->getArg(1);
  562. Expr *Arg2 = TheCall->getArg(2);
  563. Expr *Arg3 = TheCall->getArg(3);
  564. // First argument always needs to be a queue_t type.
  565. if (!Arg0->getType()->isQueueT()) {
  566. S.Diag(TheCall->getArg(0)->getBeginLoc(),
  567. diag::err_opencl_builtin_expected_type)
  568. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  569. return true;
  570. }
  571. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  572. if (!Arg1->getType()->isIntegerType()) {
  573. S.Diag(TheCall->getArg(1)->getBeginLoc(),
  574. diag::err_opencl_builtin_expected_type)
  575. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  576. return true;
  577. }
  578. // Third argument is always an ndrange_t type.
  579. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  580. S.Diag(TheCall->getArg(2)->getBeginLoc(),
  581. diag::err_opencl_builtin_expected_type)
  582. << TheCall->getDirectCallee() << "'ndrange_t'";
  583. return true;
  584. }
  585. // With four arguments, there is only one form that the function could be
  586. // called in: no events and no variable arguments.
  587. if (NumArgs == 4) {
  588. // check that the last argument is the right block type.
  589. if (!isBlockPointer(Arg3)) {
  590. S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  591. << TheCall->getDirectCallee() << "block";
  592. return true;
  593. }
  594. // we have a block type, check the prototype
  595. const BlockPointerType *BPT =
  596. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  597. if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
  598. S.Diag(Arg3->getBeginLoc(),
  599. diag::err_opencl_enqueue_kernel_blocks_no_args);
  600. return true;
  601. }
  602. return false;
  603. }
  604. // we can have block + varargs.
  605. if (isBlockPointer(Arg3))
  606. return (checkOpenCLBlockArgs(S, Arg3) ||
  607. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  608. // last two cases with either exactly 7 args or 7 args and varargs.
  609. if (NumArgs >= 7) {
  610. // check common block argument.
  611. Expr *Arg6 = TheCall->getArg(6);
  612. if (!isBlockPointer(Arg6)) {
  613. S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  614. << TheCall->getDirectCallee() << "block";
  615. return true;
  616. }
  617. if (checkOpenCLBlockArgs(S, Arg6))
  618. return true;
  619. // Forth argument has to be any integer type.
  620. if (!Arg3->getType()->isIntegerType()) {
  621. S.Diag(TheCall->getArg(3)->getBeginLoc(),
  622. diag::err_opencl_builtin_expected_type)
  623. << TheCall->getDirectCallee() << "integer";
  624. return true;
  625. }
  626. // check remaining common arguments.
  627. Expr *Arg4 = TheCall->getArg(4);
  628. Expr *Arg5 = TheCall->getArg(5);
  629. // Fifth argument is always passed as a pointer to clk_event_t.
  630. if (!Arg4->isNullPointerConstant(S.Context,
  631. Expr::NPC_ValueDependentIsNotNull) &&
  632. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  633. S.Diag(TheCall->getArg(4)->getBeginLoc(),
  634. diag::err_opencl_builtin_expected_type)
  635. << TheCall->getDirectCallee()
  636. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  637. return true;
  638. }
  639. // Sixth argument is always passed as a pointer to clk_event_t.
  640. if (!Arg5->isNullPointerConstant(S.Context,
  641. Expr::NPC_ValueDependentIsNotNull) &&
  642. !(Arg5->getType()->isPointerType() &&
  643. Arg5->getType()->getPointeeType()->isClkEventT())) {
  644. S.Diag(TheCall->getArg(5)->getBeginLoc(),
  645. diag::err_opencl_builtin_expected_type)
  646. << TheCall->getDirectCallee()
  647. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  648. return true;
  649. }
  650. if (NumArgs == 7)
  651. return false;
  652. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  653. }
  654. // None of the specific case has been detected, give generic error
  655. S.Diag(TheCall->getBeginLoc(),
  656. diag::err_opencl_enqueue_kernel_incorrect_args);
  657. return true;
  658. }
  659. /// Returns OpenCL access qual.
  660. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  661. return D->getAttr<OpenCLAccessAttr>();
  662. }
  663. /// Returns true if pipe element type is different from the pointer.
  664. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  665. const Expr *Arg0 = Call->getArg(0);
  666. // First argument type should always be pipe.
  667. if (!Arg0->getType()->isPipeType()) {
  668. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  669. << Call->getDirectCallee() << Arg0->getSourceRange();
  670. return true;
  671. }
  672. OpenCLAccessAttr *AccessQual =
  673. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  674. // Validates the access qualifier is compatible with the call.
  675. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  676. // read_only and write_only, and assumed to be read_only if no qualifier is
  677. // specified.
  678. switch (Call->getDirectCallee()->getBuiltinID()) {
  679. case Builtin::BIread_pipe:
  680. case Builtin::BIreserve_read_pipe:
  681. case Builtin::BIcommit_read_pipe:
  682. case Builtin::BIwork_group_reserve_read_pipe:
  683. case Builtin::BIsub_group_reserve_read_pipe:
  684. case Builtin::BIwork_group_commit_read_pipe:
  685. case Builtin::BIsub_group_commit_read_pipe:
  686. if (!(!AccessQual || AccessQual->isReadOnly())) {
  687. S.Diag(Arg0->getBeginLoc(),
  688. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  689. << "read_only" << Arg0->getSourceRange();
  690. return true;
  691. }
  692. break;
  693. case Builtin::BIwrite_pipe:
  694. case Builtin::BIreserve_write_pipe:
  695. case Builtin::BIcommit_write_pipe:
  696. case Builtin::BIwork_group_reserve_write_pipe:
  697. case Builtin::BIsub_group_reserve_write_pipe:
  698. case Builtin::BIwork_group_commit_write_pipe:
  699. case Builtin::BIsub_group_commit_write_pipe:
  700. if (!(AccessQual && AccessQual->isWriteOnly())) {
  701. S.Diag(Arg0->getBeginLoc(),
  702. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  703. << "write_only" << Arg0->getSourceRange();
  704. return true;
  705. }
  706. break;
  707. default:
  708. break;
  709. }
  710. return false;
  711. }
  712. /// Returns true if pipe element type is different from the pointer.
  713. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  714. const Expr *Arg0 = Call->getArg(0);
  715. const Expr *ArgIdx = Call->getArg(Idx);
  716. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  717. const QualType EltTy = PipeTy->getElementType();
  718. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  719. // The Idx argument should be a pointer and the type of the pointer and
  720. // the type of pipe element should also be the same.
  721. if (!ArgTy ||
  722. !S.Context.hasSameType(
  723. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  724. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  725. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  726. << ArgIdx->getType() << ArgIdx->getSourceRange();
  727. return true;
  728. }
  729. return false;
  730. }
  731. // Performs semantic analysis for the read/write_pipe call.
  732. // \param S Reference to the semantic analyzer.
  733. // \param Call A pointer to the builtin call.
  734. // \return True if a semantic error has been found, false otherwise.
  735. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  736. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  737. // functions have two forms.
  738. switch (Call->getNumArgs()) {
  739. case 2:
  740. if (checkOpenCLPipeArg(S, Call))
  741. return true;
  742. // The call with 2 arguments should be
  743. // read/write_pipe(pipe T, T*).
  744. // Check packet type T.
  745. if (checkOpenCLPipePacketType(S, Call, 1))
  746. return true;
  747. break;
  748. case 4: {
  749. if (checkOpenCLPipeArg(S, Call))
  750. return true;
  751. // The call with 4 arguments should be
  752. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  753. // Check reserve_id_t.
  754. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  755. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  756. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  757. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  758. return true;
  759. }
  760. // Check the index.
  761. const Expr *Arg2 = Call->getArg(2);
  762. if (!Arg2->getType()->isIntegerType() &&
  763. !Arg2->getType()->isUnsignedIntegerType()) {
  764. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  765. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  766. << Arg2->getType() << Arg2->getSourceRange();
  767. return true;
  768. }
  769. // Check packet type T.
  770. if (checkOpenCLPipePacketType(S, Call, 3))
  771. return true;
  772. } break;
  773. default:
  774. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
  775. << Call->getDirectCallee() << Call->getSourceRange();
  776. return true;
  777. }
  778. return false;
  779. }
  780. // Performs a semantic analysis on the {work_group_/sub_group_
  781. // /_}reserve_{read/write}_pipe
  782. // \param S Reference to the semantic analyzer.
  783. // \param Call The call to the builtin function to be analyzed.
  784. // \return True if a semantic error was found, false otherwise.
  785. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  786. if (checkArgCount(S, Call, 2))
  787. return true;
  788. if (checkOpenCLPipeArg(S, Call))
  789. return true;
  790. // Check the reserve size.
  791. if (!Call->getArg(1)->getType()->isIntegerType() &&
  792. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  793. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  794. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  795. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  796. return true;
  797. }
  798. // Since return type of reserve_read/write_pipe built-in function is
  799. // reserve_id_t, which is not defined in the builtin def file , we used int
  800. // as return type and need to override the return type of these functions.
  801. Call->setType(S.Context.OCLReserveIDTy);
  802. return false;
  803. }
  804. // Performs a semantic analysis on {work_group_/sub_group_
  805. // /_}commit_{read/write}_pipe
  806. // \param S Reference to the semantic analyzer.
  807. // \param Call The call to the builtin function to be analyzed.
  808. // \return True if a semantic error was found, false otherwise.
  809. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  810. if (checkArgCount(S, Call, 2))
  811. return true;
  812. if (checkOpenCLPipeArg(S, Call))
  813. return true;
  814. // Check reserve_id_t.
  815. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  816. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  817. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  818. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  819. return true;
  820. }
  821. return false;
  822. }
  823. // Performs a semantic analysis on the call to built-in Pipe
  824. // Query Functions.
  825. // \param S Reference to the semantic analyzer.
  826. // \param Call The call to the builtin function to be analyzed.
  827. // \return True if a semantic error was found, false otherwise.
  828. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  829. if (checkArgCount(S, Call, 1))
  830. return true;
  831. if (!Call->getArg(0)->getType()->isPipeType()) {
  832. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  833. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  834. return true;
  835. }
  836. return false;
  837. }
  838. // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  839. // Performs semantic analysis for the to_global/local/private call.
  840. // \param S Reference to the semantic analyzer.
  841. // \param BuiltinID ID of the builtin function.
  842. // \param Call A pointer to the builtin call.
  843. // \return True if a semantic error has been found, false otherwise.
  844. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  845. CallExpr *Call) {
  846. if (Call->getNumArgs() != 1) {
  847. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
  848. << Call->getDirectCallee() << Call->getSourceRange();
  849. return true;
  850. }
  851. auto RT = Call->getArg(0)->getType();
  852. if (!RT->isPointerType() || RT->getPointeeType()
  853. .getAddressSpace() == LangAS::opencl_constant) {
  854. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
  855. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  856. return true;
  857. }
  858. if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
  859. S.Diag(Call->getArg(0)->getBeginLoc(),
  860. diag::warn_opencl_generic_address_space_arg)
  861. << Call->getDirectCallee()->getNameInfo().getAsString()
  862. << Call->getArg(0)->getSourceRange();
  863. }
  864. RT = RT->getPointeeType();
  865. auto Qual = RT.getQualifiers();
  866. switch (BuiltinID) {
  867. case Builtin::BIto_global:
  868. Qual.setAddressSpace(LangAS::opencl_global);
  869. break;
  870. case Builtin::BIto_local:
  871. Qual.setAddressSpace(LangAS::opencl_local);
  872. break;
  873. case Builtin::BIto_private:
  874. Qual.setAddressSpace(LangAS::opencl_private);
  875. break;
  876. default:
  877. llvm_unreachable("Invalid builtin function");
  878. }
  879. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  880. RT.getUnqualifiedType(), Qual)));
  881. return false;
  882. }
  883. static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
  884. if (checkArgCount(S, TheCall, 1))
  885. return ExprError();
  886. // Compute __builtin_launder's parameter type from the argument.
  887. // The parameter type is:
  888. // * The type of the argument if it's not an array or function type,
  889. // Otherwise,
  890. // * The decayed argument type.
  891. QualType ParamTy = [&]() {
  892. QualType ArgTy = TheCall->getArg(0)->getType();
  893. if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
  894. return S.Context.getPointerType(Ty->getElementType());
  895. if (ArgTy->isFunctionType()) {
  896. return S.Context.getPointerType(ArgTy);
  897. }
  898. return ArgTy;
  899. }();
  900. TheCall->setType(ParamTy);
  901. auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
  902. if (!ParamTy->isPointerType())
  903. return 0;
  904. if (ParamTy->isFunctionPointerType())
  905. return 1;
  906. if (ParamTy->isVoidPointerType())
  907. return 2;
  908. return llvm::Optional<unsigned>{};
  909. }();
  910. if (DiagSelect.hasValue()) {
  911. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
  912. << DiagSelect.getValue() << TheCall->getSourceRange();
  913. return ExprError();
  914. }
  915. // We either have an incomplete class type, or we have a class template
  916. // whose instantiation has not been forced. Example:
  917. //
  918. // template <class T> struct Foo { T value; };
  919. // Foo<int> *p = nullptr;
  920. // auto *d = __builtin_launder(p);
  921. if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
  922. diag::err_incomplete_type))
  923. return ExprError();
  924. assert(ParamTy->getPointeeType()->isObjectType() &&
  925. "Unhandled non-object pointer case");
  926. InitializedEntity Entity =
  927. InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
  928. ExprResult Arg =
  929. S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
  930. if (Arg.isInvalid())
  931. return ExprError();
  932. TheCall->setArg(0, Arg.get());
  933. return TheCall;
  934. }
  935. // Emit an error and return true if the current architecture is not in the list
  936. // of supported architectures.
  937. static bool
  938. CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
  939. ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
  940. llvm::Triple::ArchType CurArch =
  941. S.getASTContext().getTargetInfo().getTriple().getArch();
  942. if (llvm::is_contained(SupportedArchs, CurArch))
  943. return false;
  944. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  945. << TheCall->getSourceRange();
  946. return true;
  947. }
  948. ExprResult
  949. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  950. CallExpr *TheCall) {
  951. ExprResult TheCallResult(TheCall);
  952. // Find out if any arguments are required to be integer constant expressions.
  953. unsigned ICEArguments = 0;
  954. ASTContext::GetBuiltinTypeError Error;
  955. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  956. if (Error != ASTContext::GE_None)
  957. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  958. // If any arguments are required to be ICE's, check and diagnose.
  959. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  960. // Skip arguments not required to be ICE's.
  961. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  962. llvm::APSInt Result;
  963. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  964. return true;
  965. ICEArguments &= ~(1 << ArgNo);
  966. }
  967. switch (BuiltinID) {
  968. case Builtin::BI__builtin___CFStringMakeConstantString:
  969. assert(TheCall->getNumArgs() == 1 &&
  970. "Wrong # arguments to builtin CFStringMakeConstantString");
  971. if (CheckObjCString(TheCall->getArg(0)))
  972. return ExprError();
  973. break;
  974. case Builtin::BI__builtin_ms_va_start:
  975. case Builtin::BI__builtin_stdarg_start:
  976. case Builtin::BI__builtin_va_start:
  977. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  978. return ExprError();
  979. break;
  980. case Builtin::BI__va_start: {
  981. switch (Context.getTargetInfo().getTriple().getArch()) {
  982. case llvm::Triple::aarch64:
  983. case llvm::Triple::arm:
  984. case llvm::Triple::thumb:
  985. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  986. return ExprError();
  987. break;
  988. default:
  989. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  990. return ExprError();
  991. break;
  992. }
  993. break;
  994. }
  995. // The acquire, release, and no fence variants are ARM and AArch64 only.
  996. case Builtin::BI_interlockedbittestandset_acq:
  997. case Builtin::BI_interlockedbittestandset_rel:
  998. case Builtin::BI_interlockedbittestandset_nf:
  999. case Builtin::BI_interlockedbittestandreset_acq:
  1000. case Builtin::BI_interlockedbittestandreset_rel:
  1001. case Builtin::BI_interlockedbittestandreset_nf:
  1002. if (CheckBuiltinTargetSupport(
  1003. *this, BuiltinID, TheCall,
  1004. {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
  1005. return ExprError();
  1006. break;
  1007. // The 64-bit bittest variants are x64, ARM, and AArch64 only.
  1008. case Builtin::BI_bittest64:
  1009. case Builtin::BI_bittestandcomplement64:
  1010. case Builtin::BI_bittestandreset64:
  1011. case Builtin::BI_bittestandset64:
  1012. case Builtin::BI_interlockedbittestandreset64:
  1013. case Builtin::BI_interlockedbittestandset64:
  1014. if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
  1015. {llvm::Triple::x86_64, llvm::Triple::arm,
  1016. llvm::Triple::thumb, llvm::Triple::aarch64}))
  1017. return ExprError();
  1018. break;
  1019. case Builtin::BI__builtin_isgreater:
  1020. case Builtin::BI__builtin_isgreaterequal:
  1021. case Builtin::BI__builtin_isless:
  1022. case Builtin::BI__builtin_islessequal:
  1023. case Builtin::BI__builtin_islessgreater:
  1024. case Builtin::BI__builtin_isunordered:
  1025. if (SemaBuiltinUnorderedCompare(TheCall))
  1026. return ExprError();
  1027. break;
  1028. case Builtin::BI__builtin_fpclassify:
  1029. if (SemaBuiltinFPClassification(TheCall, 6))
  1030. return ExprError();
  1031. break;
  1032. case Builtin::BI__builtin_isfinite:
  1033. case Builtin::BI__builtin_isinf:
  1034. case Builtin::BI__builtin_isinf_sign:
  1035. case Builtin::BI__builtin_isnan:
  1036. case Builtin::BI__builtin_isnormal:
  1037. case Builtin::BI__builtin_signbit:
  1038. case Builtin::BI__builtin_signbitf:
  1039. case Builtin::BI__builtin_signbitl:
  1040. if (SemaBuiltinFPClassification(TheCall, 1))
  1041. return ExprError();
  1042. break;
  1043. case Builtin::BI__builtin_shufflevector:
  1044. return SemaBuiltinShuffleVector(TheCall);
  1045. // TheCall will be freed by the smart pointer here, but that's fine, since
  1046. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  1047. case Builtin::BI__builtin_prefetch:
  1048. if (SemaBuiltinPrefetch(TheCall))
  1049. return ExprError();
  1050. break;
  1051. case Builtin::BI__builtin_alloca_with_align:
  1052. if (SemaBuiltinAllocaWithAlign(TheCall))
  1053. return ExprError();
  1054. break;
  1055. case Builtin::BI__assume:
  1056. case Builtin::BI__builtin_assume:
  1057. if (SemaBuiltinAssume(TheCall))
  1058. return ExprError();
  1059. break;
  1060. case Builtin::BI__builtin_assume_aligned:
  1061. if (SemaBuiltinAssumeAligned(TheCall))
  1062. return ExprError();
  1063. break;
  1064. case Builtin::BI__builtin_dynamic_object_size:
  1065. case Builtin::BI__builtin_object_size:
  1066. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  1067. return ExprError();
  1068. break;
  1069. case Builtin::BI__builtin_longjmp:
  1070. if (SemaBuiltinLongjmp(TheCall))
  1071. return ExprError();
  1072. break;
  1073. case Builtin::BI__builtin_setjmp:
  1074. if (SemaBuiltinSetjmp(TheCall))
  1075. return ExprError();
  1076. break;
  1077. case Builtin::BI_setjmp:
  1078. case Builtin::BI_setjmpex:
  1079. if (checkArgCount(*this, TheCall, 1))
  1080. return true;
  1081. break;
  1082. case Builtin::BI__builtin_classify_type:
  1083. if (checkArgCount(*this, TheCall, 1)) return true;
  1084. TheCall->setType(Context.IntTy);
  1085. break;
  1086. case Builtin::BI__builtin_constant_p: {
  1087. if (checkArgCount(*this, TheCall, 1)) return true;
  1088. ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
  1089. if (Arg.isInvalid()) return true;
  1090. TheCall->setArg(0, Arg.get());
  1091. TheCall->setType(Context.IntTy);
  1092. break;
  1093. }
  1094. case Builtin::BI__builtin_launder:
  1095. return SemaBuiltinLaunder(*this, TheCall);
  1096. case Builtin::BI__sync_fetch_and_add:
  1097. case Builtin::BI__sync_fetch_and_add_1:
  1098. case Builtin::BI__sync_fetch_and_add_2:
  1099. case Builtin::BI__sync_fetch_and_add_4:
  1100. case Builtin::BI__sync_fetch_and_add_8:
  1101. case Builtin::BI__sync_fetch_and_add_16:
  1102. case Builtin::BI__sync_fetch_and_sub:
  1103. case Builtin::BI__sync_fetch_and_sub_1:
  1104. case Builtin::BI__sync_fetch_and_sub_2:
  1105. case Builtin::BI__sync_fetch_and_sub_4:
  1106. case Builtin::BI__sync_fetch_and_sub_8:
  1107. case Builtin::BI__sync_fetch_and_sub_16:
  1108. case Builtin::BI__sync_fetch_and_or:
  1109. case Builtin::BI__sync_fetch_and_or_1:
  1110. case Builtin::BI__sync_fetch_and_or_2:
  1111. case Builtin::BI__sync_fetch_and_or_4:
  1112. case Builtin::BI__sync_fetch_and_or_8:
  1113. case Builtin::BI__sync_fetch_and_or_16:
  1114. case Builtin::BI__sync_fetch_and_and:
  1115. case Builtin::BI__sync_fetch_and_and_1:
  1116. case Builtin::BI__sync_fetch_and_and_2:
  1117. case Builtin::BI__sync_fetch_and_and_4:
  1118. case Builtin::BI__sync_fetch_and_and_8:
  1119. case Builtin::BI__sync_fetch_and_and_16:
  1120. case Builtin::BI__sync_fetch_and_xor:
  1121. case Builtin::BI__sync_fetch_and_xor_1:
  1122. case Builtin::BI__sync_fetch_and_xor_2:
  1123. case Builtin::BI__sync_fetch_and_xor_4:
  1124. case Builtin::BI__sync_fetch_and_xor_8:
  1125. case Builtin::BI__sync_fetch_and_xor_16:
  1126. case Builtin::BI__sync_fetch_and_nand:
  1127. case Builtin::BI__sync_fetch_and_nand_1:
  1128. case Builtin::BI__sync_fetch_and_nand_2:
  1129. case Builtin::BI__sync_fetch_and_nand_4:
  1130. case Builtin::BI__sync_fetch_and_nand_8:
  1131. case Builtin::BI__sync_fetch_and_nand_16:
  1132. case Builtin::BI__sync_add_and_fetch:
  1133. case Builtin::BI__sync_add_and_fetch_1:
  1134. case Builtin::BI__sync_add_and_fetch_2:
  1135. case Builtin::BI__sync_add_and_fetch_4:
  1136. case Builtin::BI__sync_add_and_fetch_8:
  1137. case Builtin::BI__sync_add_and_fetch_16:
  1138. case Builtin::BI__sync_sub_and_fetch:
  1139. case Builtin::BI__sync_sub_and_fetch_1:
  1140. case Builtin::BI__sync_sub_and_fetch_2:
  1141. case Builtin::BI__sync_sub_and_fetch_4:
  1142. case Builtin::BI__sync_sub_and_fetch_8:
  1143. case Builtin::BI__sync_sub_and_fetch_16:
  1144. case Builtin::BI__sync_and_and_fetch:
  1145. case Builtin::BI__sync_and_and_fetch_1:
  1146. case Builtin::BI__sync_and_and_fetch_2:
  1147. case Builtin::BI__sync_and_and_fetch_4:
  1148. case Builtin::BI__sync_and_and_fetch_8:
  1149. case Builtin::BI__sync_and_and_fetch_16:
  1150. case Builtin::BI__sync_or_and_fetch:
  1151. case Builtin::BI__sync_or_and_fetch_1:
  1152. case Builtin::BI__sync_or_and_fetch_2:
  1153. case Builtin::BI__sync_or_and_fetch_4:
  1154. case Builtin::BI__sync_or_and_fetch_8:
  1155. case Builtin::BI__sync_or_and_fetch_16:
  1156. case Builtin::BI__sync_xor_and_fetch:
  1157. case Builtin::BI__sync_xor_and_fetch_1:
  1158. case Builtin::BI__sync_xor_and_fetch_2:
  1159. case Builtin::BI__sync_xor_and_fetch_4:
  1160. case Builtin::BI__sync_xor_and_fetch_8:
  1161. case Builtin::BI__sync_xor_and_fetch_16:
  1162. case Builtin::BI__sync_nand_and_fetch:
  1163. case Builtin::BI__sync_nand_and_fetch_1:
  1164. case Builtin::BI__sync_nand_and_fetch_2:
  1165. case Builtin::BI__sync_nand_and_fetch_4:
  1166. case Builtin::BI__sync_nand_and_fetch_8:
  1167. case Builtin::BI__sync_nand_and_fetch_16:
  1168. case Builtin::BI__sync_val_compare_and_swap:
  1169. case Builtin::BI__sync_val_compare_and_swap_1:
  1170. case Builtin::BI__sync_val_compare_and_swap_2:
  1171. case Builtin::BI__sync_val_compare_and_swap_4:
  1172. case Builtin::BI__sync_val_compare_and_swap_8:
  1173. case Builtin::BI__sync_val_compare_and_swap_16:
  1174. case Builtin::BI__sync_bool_compare_and_swap:
  1175. case Builtin::BI__sync_bool_compare_and_swap_1:
  1176. case Builtin::BI__sync_bool_compare_and_swap_2:
  1177. case Builtin::BI__sync_bool_compare_and_swap_4:
  1178. case Builtin::BI__sync_bool_compare_and_swap_8:
  1179. case Builtin::BI__sync_bool_compare_and_swap_16:
  1180. case Builtin::BI__sync_lock_test_and_set:
  1181. case Builtin::BI__sync_lock_test_and_set_1:
  1182. case Builtin::BI__sync_lock_test_and_set_2:
  1183. case Builtin::BI__sync_lock_test_and_set_4:
  1184. case Builtin::BI__sync_lock_test_and_set_8:
  1185. case Builtin::BI__sync_lock_test_and_set_16:
  1186. case Builtin::BI__sync_lock_release:
  1187. case Builtin::BI__sync_lock_release_1:
  1188. case Builtin::BI__sync_lock_release_2:
  1189. case Builtin::BI__sync_lock_release_4:
  1190. case Builtin::BI__sync_lock_release_8:
  1191. case Builtin::BI__sync_lock_release_16:
  1192. case Builtin::BI__sync_swap:
  1193. case Builtin::BI__sync_swap_1:
  1194. case Builtin::BI__sync_swap_2:
  1195. case Builtin::BI__sync_swap_4:
  1196. case Builtin::BI__sync_swap_8:
  1197. case Builtin::BI__sync_swap_16:
  1198. return SemaBuiltinAtomicOverloaded(TheCallResult);
  1199. case Builtin::BI__sync_synchronize:
  1200. Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
  1201. << TheCall->getCallee()->getSourceRange();
  1202. break;
  1203. case Builtin::BI__builtin_nontemporal_load:
  1204. case Builtin::BI__builtin_nontemporal_store:
  1205. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  1206. #define BUILTIN(ID, TYPE, ATTRS)
  1207. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  1208. case Builtin::BI##ID: \
  1209. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  1210. #include "clang/Basic/Builtins.def"
  1211. case Builtin::BI__annotation:
  1212. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  1213. return ExprError();
  1214. break;
  1215. case Builtin::BI__builtin_annotation:
  1216. if (SemaBuiltinAnnotation(*this, TheCall))
  1217. return ExprError();
  1218. break;
  1219. case Builtin::BI__builtin_addressof:
  1220. if (SemaBuiltinAddressof(*this, TheCall))
  1221. return ExprError();
  1222. break;
  1223. case Builtin::BI__builtin_add_overflow:
  1224. case Builtin::BI__builtin_sub_overflow:
  1225. case Builtin::BI__builtin_mul_overflow:
  1226. if (SemaBuiltinOverflow(*this, TheCall))
  1227. return ExprError();
  1228. break;
  1229. case Builtin::BI__builtin_operator_new:
  1230. case Builtin::BI__builtin_operator_delete: {
  1231. bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
  1232. ExprResult Res =
  1233. SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
  1234. if (Res.isInvalid())
  1235. CorrectDelayedTyposInExpr(TheCallResult.get());
  1236. return Res;
  1237. }
  1238. case Builtin::BI__builtin_dump_struct: {
  1239. // We first want to ensure we are called with 2 arguments
  1240. if (checkArgCount(*this, TheCall, 2))
  1241. return ExprError();
  1242. // Ensure that the first argument is of type 'struct XX *'
  1243. const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
  1244. const QualType PtrArgType = PtrArg->getType();
  1245. if (!PtrArgType->isPointerType() ||
  1246. !PtrArgType->getPointeeType()->isRecordType()) {
  1247. Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1248. << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
  1249. << "structure pointer";
  1250. return ExprError();
  1251. }
  1252. // Ensure that the second argument is of type 'FunctionType'
  1253. const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
  1254. const QualType FnPtrArgType = FnPtrArg->getType();
  1255. if (!FnPtrArgType->isPointerType()) {
  1256. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1257. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1258. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1259. return ExprError();
  1260. }
  1261. const auto *FuncType =
  1262. FnPtrArgType->getPointeeType()->getAs<FunctionType>();
  1263. if (!FuncType) {
  1264. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1265. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1266. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1267. return ExprError();
  1268. }
  1269. if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
  1270. if (!FT->getNumParams()) {
  1271. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1272. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1273. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1274. return ExprError();
  1275. }
  1276. QualType PT = FT->getParamType(0);
  1277. if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
  1278. !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
  1279. !PT->getPointeeType().isConstQualified()) {
  1280. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1281. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1282. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1283. return ExprError();
  1284. }
  1285. }
  1286. TheCall->setType(Context.IntTy);
  1287. break;
  1288. }
  1289. case Builtin::BI__builtin_call_with_static_chain:
  1290. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  1291. return ExprError();
  1292. break;
  1293. case Builtin::BI__exception_code:
  1294. case Builtin::BI_exception_code:
  1295. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  1296. diag::err_seh___except_block))
  1297. return ExprError();
  1298. break;
  1299. case Builtin::BI__exception_info:
  1300. case Builtin::BI_exception_info:
  1301. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  1302. diag::err_seh___except_filter))
  1303. return ExprError();
  1304. break;
  1305. case Builtin::BI__GetExceptionInfo:
  1306. if (checkArgCount(*this, TheCall, 1))
  1307. return ExprError();
  1308. if (CheckCXXThrowOperand(
  1309. TheCall->getBeginLoc(),
  1310. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1311. TheCall))
  1312. return ExprError();
  1313. TheCall->setType(Context.VoidPtrTy);
  1314. break;
  1315. // OpenCL v2.0, s6.13.16 - Pipe functions
  1316. case Builtin::BIread_pipe:
  1317. case Builtin::BIwrite_pipe:
  1318. // Since those two functions are declared with var args, we need a semantic
  1319. // check for the argument.
  1320. if (SemaBuiltinRWPipe(*this, TheCall))
  1321. return ExprError();
  1322. break;
  1323. case Builtin::BIreserve_read_pipe:
  1324. case Builtin::BIreserve_write_pipe:
  1325. case Builtin::BIwork_group_reserve_read_pipe:
  1326. case Builtin::BIwork_group_reserve_write_pipe:
  1327. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1328. return ExprError();
  1329. break;
  1330. case Builtin::BIsub_group_reserve_read_pipe:
  1331. case Builtin::BIsub_group_reserve_write_pipe:
  1332. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1333. SemaBuiltinReserveRWPipe(*this, TheCall))
  1334. return ExprError();
  1335. break;
  1336. case Builtin::BIcommit_read_pipe:
  1337. case Builtin::BIcommit_write_pipe:
  1338. case Builtin::BIwork_group_commit_read_pipe:
  1339. case Builtin::BIwork_group_commit_write_pipe:
  1340. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1341. return ExprError();
  1342. break;
  1343. case Builtin::BIsub_group_commit_read_pipe:
  1344. case Builtin::BIsub_group_commit_write_pipe:
  1345. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1346. SemaBuiltinCommitRWPipe(*this, TheCall))
  1347. return ExprError();
  1348. break;
  1349. case Builtin::BIget_pipe_num_packets:
  1350. case Builtin::BIget_pipe_max_packets:
  1351. if (SemaBuiltinPipePackets(*this, TheCall))
  1352. return ExprError();
  1353. break;
  1354. case Builtin::BIto_global:
  1355. case Builtin::BIto_local:
  1356. case Builtin::BIto_private:
  1357. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1358. return ExprError();
  1359. break;
  1360. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1361. case Builtin::BIenqueue_kernel:
  1362. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1363. return ExprError();
  1364. break;
  1365. case Builtin::BIget_kernel_work_group_size:
  1366. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1367. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1368. return ExprError();
  1369. break;
  1370. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1371. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1372. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1373. return ExprError();
  1374. break;
  1375. case Builtin::BI__builtin_os_log_format:
  1376. case Builtin::BI__builtin_os_log_format_buffer_size:
  1377. if (SemaBuiltinOSLogFormat(TheCall))
  1378. return ExprError();
  1379. break;
  1380. }
  1381. // Since the target specific builtins for each arch overlap, only check those
  1382. // of the arch we are compiling for.
  1383. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  1384. switch (Context.getTargetInfo().getTriple().getArch()) {
  1385. case llvm::Triple::arm:
  1386. case llvm::Triple::armeb:
  1387. case llvm::Triple::thumb:
  1388. case llvm::Triple::thumbeb:
  1389. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  1390. return ExprError();
  1391. break;
  1392. case llvm::Triple::aarch64:
  1393. case llvm::Triple::aarch64_be:
  1394. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  1395. return ExprError();
  1396. break;
  1397. case llvm::Triple::hexagon:
  1398. if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
  1399. return ExprError();
  1400. break;
  1401. case llvm::Triple::mips:
  1402. case llvm::Triple::mipsel:
  1403. case llvm::Triple::mips64:
  1404. case llvm::Triple::mips64el:
  1405. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  1406. return ExprError();
  1407. break;
  1408. case llvm::Triple::systemz:
  1409. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  1410. return ExprError();
  1411. break;
  1412. case llvm::Triple::x86:
  1413. case llvm::Triple::x86_64:
  1414. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  1415. return ExprError();
  1416. break;
  1417. case llvm::Triple::ppc:
  1418. case llvm::Triple::ppc64:
  1419. case llvm::Triple::ppc64le:
  1420. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  1421. return ExprError();
  1422. break;
  1423. default:
  1424. break;
  1425. }
  1426. }
  1427. return TheCallResult;
  1428. }
  1429. // Get the valid immediate range for the specified NEON type code.
  1430. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  1431. NeonTypeFlags Type(t);
  1432. int IsQuad = ForceQuad ? true : Type.isQuad();
  1433. switch (Type.getEltType()) {
  1434. case NeonTypeFlags::Int8:
  1435. case NeonTypeFlags::Poly8:
  1436. return shift ? 7 : (8 << IsQuad) - 1;
  1437. case NeonTypeFlags::Int16:
  1438. case NeonTypeFlags::Poly16:
  1439. return shift ? 15 : (4 << IsQuad) - 1;
  1440. case NeonTypeFlags::Int32:
  1441. return shift ? 31 : (2 << IsQuad) - 1;
  1442. case NeonTypeFlags::Int64:
  1443. case NeonTypeFlags::Poly64:
  1444. return shift ? 63 : (1 << IsQuad) - 1;
  1445. case NeonTypeFlags::Poly128:
  1446. return shift ? 127 : (1 << IsQuad) - 1;
  1447. case NeonTypeFlags::Float16:
  1448. assert(!shift && "cannot shift float types!");
  1449. return (4 << IsQuad) - 1;
  1450. case NeonTypeFlags::Float32:
  1451. assert(!shift && "cannot shift float types!");
  1452. return (2 << IsQuad) - 1;
  1453. case NeonTypeFlags::Float64:
  1454. assert(!shift && "cannot shift float types!");
  1455. return (1 << IsQuad) - 1;
  1456. }
  1457. llvm_unreachable("Invalid NeonTypeFlag!");
  1458. }
  1459. /// getNeonEltType - Return the QualType corresponding to the elements of
  1460. /// the vector type specified by the NeonTypeFlags. This is used to check
  1461. /// the pointer arguments for Neon load/store intrinsics.
  1462. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  1463. bool IsPolyUnsigned, bool IsInt64Long) {
  1464. switch (Flags.getEltType()) {
  1465. case NeonTypeFlags::Int8:
  1466. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  1467. case NeonTypeFlags::Int16:
  1468. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  1469. case NeonTypeFlags::Int32:
  1470. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  1471. case NeonTypeFlags::Int64:
  1472. if (IsInt64Long)
  1473. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  1474. else
  1475. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  1476. : Context.LongLongTy;
  1477. case NeonTypeFlags::Poly8:
  1478. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  1479. case NeonTypeFlags::Poly16:
  1480. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  1481. case NeonTypeFlags::Poly64:
  1482. if (IsInt64Long)
  1483. return Context.UnsignedLongTy;
  1484. else
  1485. return Context.UnsignedLongLongTy;
  1486. case NeonTypeFlags::Poly128:
  1487. break;
  1488. case NeonTypeFlags::Float16:
  1489. return Context.HalfTy;
  1490. case NeonTypeFlags::Float32:
  1491. return Context.FloatTy;
  1492. case NeonTypeFlags::Float64:
  1493. return Context.DoubleTy;
  1494. }
  1495. llvm_unreachable("Invalid NeonTypeFlag!");
  1496. }
  1497. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1498. llvm::APSInt Result;
  1499. uint64_t mask = 0;
  1500. unsigned TV = 0;
  1501. int PtrArgNum = -1;
  1502. bool HasConstPtr = false;
  1503. switch (BuiltinID) {
  1504. #define GET_NEON_OVERLOAD_CHECK
  1505. #include "clang/Basic/arm_neon.inc"
  1506. #include "clang/Basic/arm_fp16.inc"
  1507. #undef GET_NEON_OVERLOAD_CHECK
  1508. }
  1509. // For NEON intrinsics which are overloaded on vector element type, validate
  1510. // the immediate which specifies which variant to emit.
  1511. unsigned ImmArg = TheCall->getNumArgs()-1;
  1512. if (mask) {
  1513. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  1514. return true;
  1515. TV = Result.getLimitedValue(64);
  1516. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  1517. return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
  1518. << TheCall->getArg(ImmArg)->getSourceRange();
  1519. }
  1520. if (PtrArgNum >= 0) {
  1521. // Check that pointer arguments have the specified type.
  1522. Expr *Arg = TheCall->getArg(PtrArgNum);
  1523. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  1524. Arg = ICE->getSubExpr();
  1525. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  1526. QualType RHSTy = RHS.get()->getType();
  1527. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  1528. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  1529. Arch == llvm::Triple::aarch64_be;
  1530. bool IsInt64Long =
  1531. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  1532. QualType EltTy =
  1533. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  1534. if (HasConstPtr)
  1535. EltTy = EltTy.withConst();
  1536. QualType LHSTy = Context.getPointerType(EltTy);
  1537. AssignConvertType ConvTy;
  1538. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  1539. if (RHS.isInvalid())
  1540. return true;
  1541. if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
  1542. RHS.get(), AA_Assigning))
  1543. return true;
  1544. }
  1545. // For NEON intrinsics which take an immediate value as part of the
  1546. // instruction, range check them here.
  1547. unsigned i = 0, l = 0, u = 0;
  1548. switch (BuiltinID) {
  1549. default:
  1550. return false;
  1551. #define GET_NEON_IMMEDIATE_CHECK
  1552. #include "clang/Basic/arm_neon.inc"
  1553. #include "clang/Basic/arm_fp16.inc"
  1554. #undef GET_NEON_IMMEDIATE_CHECK
  1555. }
  1556. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1557. }
  1558. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  1559. unsigned MaxWidth) {
  1560. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1561. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1562. BuiltinID == ARM::BI__builtin_arm_strex ||
  1563. BuiltinID == ARM::BI__builtin_arm_stlex ||
  1564. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1565. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1566. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1567. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  1568. "unexpected ARM builtin");
  1569. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1570. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1571. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1572. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  1573. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1574. // Ensure that we have the proper number of arguments.
  1575. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  1576. return true;
  1577. // Inspect the pointer argument of the atomic builtin. This should always be
  1578. // a pointer type, whose element is an integral scalar or pointer type.
  1579. // Because it is a pointer type, we don't have to worry about any implicit
  1580. // casts here.
  1581. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  1582. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  1583. if (PointerArgRes.isInvalid())
  1584. return true;
  1585. PointerArg = PointerArgRes.get();
  1586. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  1587. if (!pointerType) {
  1588. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  1589. << PointerArg->getType() << PointerArg->getSourceRange();
  1590. return true;
  1591. }
  1592. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  1593. // task is to insert the appropriate casts into the AST. First work out just
  1594. // what the appropriate type is.
  1595. QualType ValType = pointerType->getPointeeType();
  1596. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  1597. if (IsLdrex)
  1598. AddrType.addConst();
  1599. // Issue a warning if the cast is dodgy.
  1600. CastKind CastNeeded = CK_NoOp;
  1601. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  1602. CastNeeded = CK_BitCast;
  1603. Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
  1604. << PointerArg->getType() << Context.getPointerType(AddrType)
  1605. << AA_Passing << PointerArg->getSourceRange();
  1606. }
  1607. // Finally, do the cast and replace the argument with the corrected version.
  1608. AddrType = Context.getPointerType(AddrType);
  1609. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  1610. if (PointerArgRes.isInvalid())
  1611. return true;
  1612. PointerArg = PointerArgRes.get();
  1613. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  1614. // In general, we allow ints, floats and pointers to be loaded and stored.
  1615. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1616. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  1617. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  1618. << PointerArg->getType() << PointerArg->getSourceRange();
  1619. return true;
  1620. }
  1621. // But ARM doesn't have instructions to deal with 128-bit versions.
  1622. if (Context.getTypeSize(ValType) > MaxWidth) {
  1623. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  1624. Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
  1625. << PointerArg->getType() << PointerArg->getSourceRange();
  1626. return true;
  1627. }
  1628. switch (ValType.getObjCLifetime()) {
  1629. case Qualifiers::OCL_None:
  1630. case Qualifiers::OCL_ExplicitNone:
  1631. // okay
  1632. break;
  1633. case Qualifiers::OCL_Weak:
  1634. case Qualifiers::OCL_Strong:
  1635. case Qualifiers::OCL_Autoreleasing:
  1636. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  1637. << ValType << PointerArg->getSourceRange();
  1638. return true;
  1639. }
  1640. if (IsLdrex) {
  1641. TheCall->setType(ValType);
  1642. return false;
  1643. }
  1644. // Initialize the argument to be stored.
  1645. ExprResult ValArg = TheCall->getArg(0);
  1646. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  1647. Context, ValType, /*consume*/ false);
  1648. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  1649. if (ValArg.isInvalid())
  1650. return true;
  1651. TheCall->setArg(0, ValArg.get());
  1652. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  1653. // but the custom checker bypasses all default analysis.
  1654. TheCall->setType(Context.IntTy);
  1655. return false;
  1656. }
  1657. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1658. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1659. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1660. BuiltinID == ARM::BI__builtin_arm_strex ||
  1661. BuiltinID == ARM::BI__builtin_arm_stlex) {
  1662. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  1663. }
  1664. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  1665. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1666. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  1667. }
  1668. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  1669. BuiltinID == ARM::BI__builtin_arm_wsr64)
  1670. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  1671. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  1672. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  1673. BuiltinID == ARM::BI__builtin_arm_wsr ||
  1674. BuiltinID == ARM::BI__builtin_arm_wsrp)
  1675. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1676. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1677. return true;
  1678. // For intrinsics which take an immediate value as part of the instruction,
  1679. // range check them here.
  1680. // FIXME: VFP Intrinsics should error if VFP not present.
  1681. switch (BuiltinID) {
  1682. default: return false;
  1683. case ARM::BI__builtin_arm_ssat:
  1684. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  1685. case ARM::BI__builtin_arm_usat:
  1686. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  1687. case ARM::BI__builtin_arm_ssat16:
  1688. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  1689. case ARM::BI__builtin_arm_usat16:
  1690. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  1691. case ARM::BI__builtin_arm_vcvtr_f:
  1692. case ARM::BI__builtin_arm_vcvtr_d:
  1693. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  1694. case ARM::BI__builtin_arm_dmb:
  1695. case ARM::BI__builtin_arm_dsb:
  1696. case ARM::BI__builtin_arm_isb:
  1697. case ARM::BI__builtin_arm_dbg:
  1698. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  1699. }
  1700. }
  1701. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  1702. CallExpr *TheCall) {
  1703. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1704. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1705. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1706. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  1707. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  1708. }
  1709. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  1710. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1711. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  1712. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  1713. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  1714. }
  1715. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  1716. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  1717. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1718. // Memory Tagging Extensions (MTE) Intrinsics
  1719. if (BuiltinID == AArch64::BI__builtin_arm_irg ||
  1720. BuiltinID == AArch64::BI__builtin_arm_addg ||
  1721. BuiltinID == AArch64::BI__builtin_arm_gmi ||
  1722. BuiltinID == AArch64::BI__builtin_arm_ldg ||
  1723. BuiltinID == AArch64::BI__builtin_arm_stg ||
  1724. BuiltinID == AArch64::BI__builtin_arm_subp) {
  1725. return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
  1726. }
  1727. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  1728. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  1729. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  1730. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  1731. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1732. // Only check the valid encoding range. Any constant in this range would be
  1733. // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
  1734. // an exception for incorrect registers. This matches MSVC behavior.
  1735. if (BuiltinID == AArch64::BI_ReadStatusReg ||
  1736. BuiltinID == AArch64::BI_WriteStatusReg)
  1737. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
  1738. if (BuiltinID == AArch64::BI__getReg)
  1739. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
  1740. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1741. return true;
  1742. // For intrinsics which take an immediate value as part of the instruction,
  1743. // range check them here.
  1744. unsigned i = 0, l = 0, u = 0;
  1745. switch (BuiltinID) {
  1746. default: return false;
  1747. case AArch64::BI__builtin_arm_dmb:
  1748. case AArch64::BI__builtin_arm_dsb:
  1749. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  1750. }
  1751. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1752. }
  1753. bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
  1754. struct BuiltinAndString {
  1755. unsigned BuiltinID;
  1756. const char *Str;
  1757. };
  1758. static BuiltinAndString ValidCPU[] = {
  1759. { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
  1760. { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
  1761. { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
  1762. { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
  1763. { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
  1764. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
  1765. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
  1766. { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
  1767. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
  1768. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
  1769. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
  1770. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
  1771. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
  1772. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
  1773. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
  1774. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
  1775. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
  1776. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
  1777. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
  1778. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
  1779. { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
  1780. { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
  1781. { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
  1782. };
  1783. static BuiltinAndString ValidHVX[] = {
  1784. { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
  1785. { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
  1786. { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
  1787. { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
  1788. { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
  1789. { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
  1790. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
  1791. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
  1792. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
  1793. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
  1794. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
  1795. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
  1796. { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
  1797. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
  1798. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
  1799. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
  1800. { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
  1801. { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
  1802. { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
  1803. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
  1804. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
  1805. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
  1806. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
  1807. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
  1808. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
  1809. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
  1810. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
  1811. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
  1812. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
  1813. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
  1814. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
  1815. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
  1816. { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
  1817. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
  1818. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
  1819. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
  1820. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
  1821. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
  1822. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
  1823. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
  1824. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
  1825. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
  1826. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
  1827. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
  1828. { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
  1829. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
  1830. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
  1831. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
  1832. { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
  1833. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
  1834. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
  1835. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
  1836. { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
  1837. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
  1838. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
  1839. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
  1840. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
  1841. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
  1842. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
  1843. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
  1844. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
  1845. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
  1846. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
  1847. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
  1848. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
  1849. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
  1850. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
  1851. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
  1852. { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
  1853. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
  1854. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
  1855. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
  1856. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
  1857. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
  1858. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
  1859. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
  1860. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
  1861. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
  1862. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
  1863. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
  1864. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
  1865. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
  1866. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
  1867. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
  1868. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
  1869. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
  1870. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
  1871. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
  1872. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
  1873. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
  1874. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
  1875. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
  1876. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
  1877. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
  1878. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
  1879. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
  1880. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
  1881. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
  1882. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
  1883. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
  1884. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
  1885. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
  1886. { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
  1887. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
  1888. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
  1889. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
  1890. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
  1891. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
  1892. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
  1893. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
  1894. { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
  1895. { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
  1896. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
  1897. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
  1898. { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
  1899. { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
  1900. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
  1901. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
  1902. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
  1903. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
  1904. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
  1905. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
  1906. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
  1907. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
  1908. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
  1909. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
  1910. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
  1911. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
  1912. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
  1913. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
  1914. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
  1915. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
  1916. { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
  1917. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
  1918. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
  1919. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
  1920. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
  1921. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
  1922. { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
  1923. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
  1924. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
  1925. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
  1926. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
  1927. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
  1928. { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
  1929. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
  1930. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
  1931. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
  1932. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
  1933. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
  1934. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
  1935. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
  1936. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
  1937. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
  1938. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
  1939. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
  1940. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
  1941. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
  1942. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
  1943. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
  1944. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
  1945. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
  1946. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
  1947. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
  1948. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
  1949. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
  1950. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
  1951. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
  1952. { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
  1953. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
  1954. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
  1955. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
  1956. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
  1957. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
  1958. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
  1959. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
  1960. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
  1961. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
  1962. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
  1963. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
  1964. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
  1965. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
  1966. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
  1967. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
  1968. { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
  1969. { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
  1970. { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
  1971. { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
  1972. { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
  1973. { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
  1974. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
  1975. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
  1976. { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
  1977. { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
  1978. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
  1979. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
  1980. { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
  1981. { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
  1982. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
  1983. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
  1984. { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
  1985. { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
  1986. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
  1987. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
  1988. { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
  1989. { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
  1990. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
  1991. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
  1992. { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
  1993. { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
  1994. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
  1995. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
  1996. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
  1997. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
  1998. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
  1999. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
  2000. { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
  2001. { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
  2002. { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
  2003. { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
  2004. { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
  2005. { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
  2006. { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
  2007. { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
  2008. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
  2009. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
  2010. { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
  2011. { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
  2012. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
  2013. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
  2014. { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
  2015. { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
  2016. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
  2017. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
  2018. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
  2019. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
  2020. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
  2021. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
  2022. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
  2023. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
  2024. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
  2025. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
  2026. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
  2027. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
  2028. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
  2029. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
  2030. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
  2031. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
  2032. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
  2033. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
  2034. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
  2035. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
  2036. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
  2037. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
  2038. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
  2039. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
  2040. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
  2041. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
  2042. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
  2043. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
  2044. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
  2045. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
  2046. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
  2047. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
  2048. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
  2049. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
  2050. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
  2051. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
  2052. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
  2053. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
  2054. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
  2055. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
  2056. { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
  2057. { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
  2058. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
  2059. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
  2060. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
  2061. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
  2062. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
  2063. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
  2064. { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
  2065. { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
  2066. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
  2067. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
  2068. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
  2069. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
  2070. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
  2071. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
  2072. { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
  2073. { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
  2074. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
  2075. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
  2076. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
  2077. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
  2078. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
  2079. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
  2080. { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
  2081. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
  2082. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
  2083. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
  2084. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
  2085. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
  2086. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
  2087. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
  2088. { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
  2089. { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
  2090. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
  2091. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
  2092. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
  2093. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
  2094. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
  2095. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
  2096. { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
  2097. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
  2098. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
  2099. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
  2100. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
  2101. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
  2102. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
  2103. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
  2104. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
  2105. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
  2106. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
  2107. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
  2108. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
  2109. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
  2110. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
  2111. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
  2112. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
  2113. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
  2114. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
  2115. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
  2116. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
  2117. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
  2118. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
  2119. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
  2120. { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
  2121. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
  2122. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
  2123. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
  2124. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
  2125. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
  2126. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
  2127. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
  2128. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
  2129. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
  2130. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
  2131. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
  2132. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
  2133. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
  2134. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
  2135. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
  2136. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
  2137. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
  2138. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
  2139. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
  2140. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
  2141. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
  2142. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
  2143. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
  2144. { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
  2145. { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
  2146. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
  2147. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
  2148. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
  2149. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
  2150. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
  2151. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
  2152. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
  2153. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
  2154. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
  2155. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
  2156. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
  2157. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
  2158. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
  2159. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
  2160. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
  2161. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
  2162. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
  2163. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
  2164. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
  2165. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
  2166. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
  2167. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
  2168. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
  2169. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
  2170. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
  2171. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
  2172. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
  2173. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
  2174. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
  2175. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
  2176. { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
  2177. { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
  2178. { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
  2179. { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
  2180. { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
  2181. { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
  2182. { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
  2183. { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
  2184. { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
  2185. { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
  2186. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
  2187. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
  2188. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
  2189. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
  2190. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
  2191. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
  2192. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
  2193. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
  2194. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
  2195. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
  2196. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
  2197. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
  2198. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
  2199. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
  2200. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
  2201. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
  2202. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
  2203. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
  2204. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
  2205. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
  2206. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
  2207. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
  2208. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
  2209. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
  2210. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
  2211. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
  2212. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
  2213. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
  2214. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
  2215. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
  2216. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
  2217. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
  2218. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
  2219. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
  2220. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
  2221. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
  2222. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
  2223. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
  2224. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
  2225. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
  2226. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
  2227. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
  2228. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
  2229. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
  2230. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
  2231. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
  2232. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
  2233. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
  2234. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
  2235. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
  2236. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
  2237. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
  2238. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
  2239. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
  2240. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
  2241. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
  2242. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
  2243. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
  2244. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
  2245. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
  2246. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
  2247. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
  2248. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
  2249. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
  2250. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
  2251. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
  2252. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
  2253. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
  2254. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
  2255. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
  2256. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
  2257. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
  2258. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
  2259. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
  2260. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
  2261. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
  2262. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
  2263. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
  2264. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
  2265. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
  2266. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
  2267. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
  2268. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
  2269. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
  2270. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
  2271. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
  2272. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
  2273. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
  2274. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
  2275. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
  2276. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
  2277. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
  2278. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
  2279. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
  2280. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
  2281. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
  2282. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
  2283. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
  2284. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
  2285. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
  2286. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
  2287. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
  2288. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
  2289. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
  2290. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
  2291. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
  2292. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
  2293. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
  2294. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
  2295. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
  2296. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
  2297. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
  2298. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
  2299. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
  2300. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
  2301. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
  2302. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
  2303. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
  2304. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
  2305. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
  2306. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
  2307. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
  2308. { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
  2309. { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
  2310. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
  2311. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
  2312. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
  2313. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
  2314. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
  2315. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
  2316. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
  2317. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
  2318. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
  2319. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
  2320. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
  2321. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
  2322. { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
  2323. { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
  2324. { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
  2325. { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
  2326. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
  2327. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
  2328. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
  2329. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
  2330. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
  2331. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
  2332. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
  2333. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
  2334. { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
  2335. { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
  2336. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
  2337. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
  2338. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
  2339. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
  2340. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
  2341. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
  2342. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
  2343. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
  2344. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
  2345. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
  2346. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
  2347. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
  2348. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
  2349. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
  2350. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
  2351. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
  2352. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
  2353. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
  2354. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
  2355. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
  2356. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
  2357. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
  2358. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
  2359. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
  2360. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
  2361. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
  2362. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
  2363. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
  2364. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
  2365. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
  2366. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
  2367. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
  2368. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
  2369. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
  2370. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
  2371. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
  2372. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
  2373. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
  2374. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
  2375. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
  2376. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
  2377. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
  2378. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
  2379. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
  2380. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
  2381. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
  2382. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
  2383. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
  2384. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
  2385. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
  2386. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
  2387. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
  2388. { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
  2389. { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
  2390. { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
  2391. { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
  2392. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
  2393. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
  2394. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
  2395. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
  2396. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
  2397. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
  2398. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
  2399. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
  2400. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
  2401. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
  2402. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
  2403. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
  2404. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
  2405. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
  2406. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
  2407. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
  2408. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
  2409. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
  2410. { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
  2411. { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
  2412. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
  2413. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
  2414. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
  2415. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
  2416. { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
  2417. { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
  2418. { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
  2419. { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
  2420. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
  2421. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
  2422. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
  2423. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
  2424. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
  2425. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
  2426. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
  2427. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
  2428. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
  2429. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
  2430. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
  2431. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
  2432. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
  2433. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
  2434. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
  2435. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
  2436. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
  2437. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
  2438. { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
  2439. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
  2440. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
  2441. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
  2442. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
  2443. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
  2444. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
  2445. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
  2446. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
  2447. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
  2448. { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
  2449. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
  2450. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
  2451. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
  2452. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
  2453. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
  2454. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
  2455. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
  2456. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
  2457. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
  2458. { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
  2459. { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
  2460. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
  2461. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
  2462. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
  2463. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
  2464. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
  2465. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
  2466. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
  2467. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
  2468. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
  2469. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
  2470. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
  2471. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
  2472. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
  2473. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
  2474. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
  2475. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
  2476. { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
  2477. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
  2478. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
  2479. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
  2480. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
  2481. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
  2482. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
  2483. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
  2484. { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
  2485. { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
  2486. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
  2487. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
  2488. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
  2489. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
  2490. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
  2491. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
  2492. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
  2493. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
  2494. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
  2495. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
  2496. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
  2497. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
  2498. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
  2499. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
  2500. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
  2501. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
  2502. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
  2503. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
  2504. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
  2505. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
  2506. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
  2507. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
  2508. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
  2509. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
  2510. { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
  2511. { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
  2512. { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
  2513. { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
  2514. { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
  2515. { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
  2516. };
  2517. // Sort the tables on first execution so we can binary search them.
  2518. auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
  2519. return LHS.BuiltinID < RHS.BuiltinID;
  2520. };
  2521. static const bool SortOnce =
  2522. (llvm::sort(ValidCPU, SortCmp),
  2523. llvm::sort(ValidHVX, SortCmp), true);
  2524. (void)SortOnce;
  2525. auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
  2526. return BI.BuiltinID < BuiltinID;
  2527. };
  2528. const TargetInfo &TI = Context.getTargetInfo();
  2529. const BuiltinAndString *FC =
  2530. llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
  2531. if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
  2532. const TargetOptions &Opts = TI.getTargetOpts();
  2533. StringRef CPU = Opts.CPU;
  2534. if (!CPU.empty()) {
  2535. assert(CPU.startswith("hexagon") && "Unexpected CPU name");
  2536. CPU.consume_front("hexagon");
  2537. SmallVector<StringRef, 3> CPUs;
  2538. StringRef(FC->Str).split(CPUs, ',');
  2539. if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
  2540. return Diag(TheCall->getBeginLoc(),
  2541. diag::err_hexagon_builtin_unsupported_cpu);
  2542. }
  2543. }
  2544. const BuiltinAndString *FH =
  2545. llvm::lower_bound(ValidHVX, BuiltinID, 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 = llvm::partition_point(
  2767. Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
  2768. if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
  2769. return false;
  2770. bool Error = false;
  2771. for (const ArgInfo &A : F->Infos) {
  2772. // Ignore empty ArgInfo elements.
  2773. if (A.BitWidth == 0)
  2774. continue;
  2775. int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
  2776. int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
  2777. if (!A.Align) {
  2778. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
  2779. } else {
  2780. unsigned M = 1 << A.Align;
  2781. Min *= M;
  2782. Max *= M;
  2783. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
  2784. SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
  2785. }
  2786. }
  2787. return Error;
  2788. }
  2789. bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
  2790. CallExpr *TheCall) {
  2791. return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
  2792. CheckHexagonBuiltinArgument(BuiltinID, TheCall);
  2793. }
  2794. // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
  2795. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  2796. // ordering for DSP is unspecified. MSA is ordered by the data format used
  2797. // by the underlying instruction i.e., df/m, df/n and then by size.
  2798. //
  2799. // FIXME: The size tests here should instead be tablegen'd along with the
  2800. // definitions from include/clang/Basic/BuiltinsMips.def.
  2801. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  2802. // be too.
  2803. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2804. unsigned i = 0, l = 0, u = 0, m = 0;
  2805. switch (BuiltinID) {
  2806. default: return false;
  2807. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  2808. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  2809. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  2810. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  2811. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  2812. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  2813. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  2814. // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
  2815. // df/m field.
  2816. // These intrinsics take an unsigned 3 bit immediate.
  2817. case Mips::BI__builtin_msa_bclri_b:
  2818. case Mips::BI__builtin_msa_bnegi_b:
  2819. case Mips::BI__builtin_msa_bseti_b:
  2820. case Mips::BI__builtin_msa_sat_s_b:
  2821. case Mips::BI__builtin_msa_sat_u_b:
  2822. case Mips::BI__builtin_msa_slli_b:
  2823. case Mips::BI__builtin_msa_srai_b:
  2824. case Mips::BI__builtin_msa_srari_b:
  2825. case Mips::BI__builtin_msa_srli_b:
  2826. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  2827. case Mips::BI__builtin_msa_binsli_b:
  2828. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  2829. // These intrinsics take an unsigned 4 bit immediate.
  2830. case Mips::BI__builtin_msa_bclri_h:
  2831. case Mips::BI__builtin_msa_bnegi_h:
  2832. case Mips::BI__builtin_msa_bseti_h:
  2833. case Mips::BI__builtin_msa_sat_s_h:
  2834. case Mips::BI__builtin_msa_sat_u_h:
  2835. case Mips::BI__builtin_msa_slli_h:
  2836. case Mips::BI__builtin_msa_srai_h:
  2837. case Mips::BI__builtin_msa_srari_h:
  2838. case Mips::BI__builtin_msa_srli_h:
  2839. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  2840. case Mips::BI__builtin_msa_binsli_h:
  2841. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  2842. // These intrinsics take an unsigned 5 bit immediate.
  2843. // The first block of intrinsics actually have an unsigned 5 bit field,
  2844. // not a df/n field.
  2845. case Mips::BI__builtin_msa_cfcmsa:
  2846. case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
  2847. case Mips::BI__builtin_msa_clei_u_b:
  2848. case Mips::BI__builtin_msa_clei_u_h:
  2849. case Mips::BI__builtin_msa_clei_u_w:
  2850. case Mips::BI__builtin_msa_clei_u_d:
  2851. case Mips::BI__builtin_msa_clti_u_b:
  2852. case Mips::BI__builtin_msa_clti_u_h:
  2853. case Mips::BI__builtin_msa_clti_u_w:
  2854. case Mips::BI__builtin_msa_clti_u_d:
  2855. case Mips::BI__builtin_msa_maxi_u_b:
  2856. case Mips::BI__builtin_msa_maxi_u_h:
  2857. case Mips::BI__builtin_msa_maxi_u_w:
  2858. case Mips::BI__builtin_msa_maxi_u_d:
  2859. case Mips::BI__builtin_msa_mini_u_b:
  2860. case Mips::BI__builtin_msa_mini_u_h:
  2861. case Mips::BI__builtin_msa_mini_u_w:
  2862. case Mips::BI__builtin_msa_mini_u_d:
  2863. case Mips::BI__builtin_msa_addvi_b:
  2864. case Mips::BI__builtin_msa_addvi_h:
  2865. case Mips::BI__builtin_msa_addvi_w:
  2866. case Mips::BI__builtin_msa_addvi_d:
  2867. case Mips::BI__builtin_msa_bclri_w:
  2868. case Mips::BI__builtin_msa_bnegi_w:
  2869. case Mips::BI__builtin_msa_bseti_w:
  2870. case Mips::BI__builtin_msa_sat_s_w:
  2871. case Mips::BI__builtin_msa_sat_u_w:
  2872. case Mips::BI__builtin_msa_slli_w:
  2873. case Mips::BI__builtin_msa_srai_w:
  2874. case Mips::BI__builtin_msa_srari_w:
  2875. case Mips::BI__builtin_msa_srli_w:
  2876. case Mips::BI__builtin_msa_srlri_w:
  2877. case Mips::BI__builtin_msa_subvi_b:
  2878. case Mips::BI__builtin_msa_subvi_h:
  2879. case Mips::BI__builtin_msa_subvi_w:
  2880. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  2881. case Mips::BI__builtin_msa_binsli_w:
  2882. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  2883. // These intrinsics take an unsigned 6 bit immediate.
  2884. case Mips::BI__builtin_msa_bclri_d:
  2885. case Mips::BI__builtin_msa_bnegi_d:
  2886. case Mips::BI__builtin_msa_bseti_d:
  2887. case Mips::BI__builtin_msa_sat_s_d:
  2888. case Mips::BI__builtin_msa_sat_u_d:
  2889. case Mips::BI__builtin_msa_slli_d:
  2890. case Mips::BI__builtin_msa_srai_d:
  2891. case Mips::BI__builtin_msa_srari_d:
  2892. case Mips::BI__builtin_msa_srli_d:
  2893. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  2894. case Mips::BI__builtin_msa_binsli_d:
  2895. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  2896. // These intrinsics take a signed 5 bit immediate.
  2897. case Mips::BI__builtin_msa_ceqi_b:
  2898. case Mips::BI__builtin_msa_ceqi_h:
  2899. case Mips::BI__builtin_msa_ceqi_w:
  2900. case Mips::BI__builtin_msa_ceqi_d:
  2901. case Mips::BI__builtin_msa_clti_s_b:
  2902. case Mips::BI__builtin_msa_clti_s_h:
  2903. case Mips::BI__builtin_msa_clti_s_w:
  2904. case Mips::BI__builtin_msa_clti_s_d:
  2905. case Mips::BI__builtin_msa_clei_s_b:
  2906. case Mips::BI__builtin_msa_clei_s_h:
  2907. case Mips::BI__builtin_msa_clei_s_w:
  2908. case Mips::BI__builtin_msa_clei_s_d:
  2909. case Mips::BI__builtin_msa_maxi_s_b:
  2910. case Mips::BI__builtin_msa_maxi_s_h:
  2911. case Mips::BI__builtin_msa_maxi_s_w:
  2912. case Mips::BI__builtin_msa_maxi_s_d:
  2913. case Mips::BI__builtin_msa_mini_s_b:
  2914. case Mips::BI__builtin_msa_mini_s_h:
  2915. case Mips::BI__builtin_msa_mini_s_w:
  2916. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  2917. // These intrinsics take an unsigned 8 bit immediate.
  2918. case Mips::BI__builtin_msa_andi_b:
  2919. case Mips::BI__builtin_msa_nori_b:
  2920. case Mips::BI__builtin_msa_ori_b:
  2921. case Mips::BI__builtin_msa_shf_b:
  2922. case Mips::BI__builtin_msa_shf_h:
  2923. case Mips::BI__builtin_msa_shf_w:
  2924. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  2925. case Mips::BI__builtin_msa_bseli_b:
  2926. case Mips::BI__builtin_msa_bmnzi_b:
  2927. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  2928. // df/n format
  2929. // These intrinsics take an unsigned 4 bit immediate.
  2930. case Mips::BI__builtin_msa_copy_s_b:
  2931. case Mips::BI__builtin_msa_copy_u_b:
  2932. case Mips::BI__builtin_msa_insve_b:
  2933. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  2934. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  2935. // These intrinsics take an unsigned 3 bit immediate.
  2936. case Mips::BI__builtin_msa_copy_s_h:
  2937. case Mips::BI__builtin_msa_copy_u_h:
  2938. case Mips::BI__builtin_msa_insve_h:
  2939. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  2940. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  2941. // These intrinsics take an unsigned 2 bit immediate.
  2942. case Mips::BI__builtin_msa_copy_s_w:
  2943. case Mips::BI__builtin_msa_copy_u_w:
  2944. case Mips::BI__builtin_msa_insve_w:
  2945. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  2946. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  2947. // These intrinsics take an unsigned 1 bit immediate.
  2948. case Mips::BI__builtin_msa_copy_s_d:
  2949. case Mips::BI__builtin_msa_copy_u_d:
  2950. case Mips::BI__builtin_msa_insve_d:
  2951. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  2952. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  2953. // Memory offsets and immediate loads.
  2954. // These intrinsics take a signed 10 bit immediate.
  2955. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  2956. case Mips::BI__builtin_msa_ldi_h:
  2957. case Mips::BI__builtin_msa_ldi_w:
  2958. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  2959. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
  2960. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
  2961. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
  2962. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
  2963. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
  2964. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
  2965. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
  2966. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
  2967. }
  2968. if (!m)
  2969. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2970. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  2971. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  2972. }
  2973. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2974. unsigned i = 0, l = 0, u = 0;
  2975. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  2976. BuiltinID == PPC::BI__builtin_divdeu ||
  2977. BuiltinID == PPC::BI__builtin_bpermd;
  2978. bool IsTarget64Bit = Context.getTargetInfo()
  2979. .getTypeWidth(Context
  2980. .getTargetInfo()
  2981. .getIntPtrType()) == 64;
  2982. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  2983. BuiltinID == PPC::BI__builtin_divweu ||
  2984. BuiltinID == PPC::BI__builtin_divde ||
  2985. BuiltinID == PPC::BI__builtin_divdeu;
  2986. if (Is64BitBltin && !IsTarget64Bit)
  2987. return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
  2988. << TheCall->getSourceRange();
  2989. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  2990. (BuiltinID == PPC::BI__builtin_bpermd &&
  2991. !Context.getTargetInfo().hasFeature("bpermd")))
  2992. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  2993. << TheCall->getSourceRange();
  2994. auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
  2995. if (!Context.getTargetInfo().hasFeature("vsx"))
  2996. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  2997. << TheCall->getSourceRange();
  2998. return false;
  2999. };
  3000. switch (BuiltinID) {
  3001. default: return false;
  3002. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  3003. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  3004. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  3005. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3006. case PPC::BI__builtin_tbegin:
  3007. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  3008. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  3009. case PPC::BI__builtin_tabortwc:
  3010. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  3011. case PPC::BI__builtin_tabortwci:
  3012. case PPC::BI__builtin_tabortdci:
  3013. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  3014. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  3015. case PPC::BI__builtin_vsx_xxpermdi:
  3016. case PPC::BI__builtin_vsx_xxsldwi:
  3017. return SemaBuiltinVSX(TheCall);
  3018. case PPC::BI__builtin_unpack_vector_int128:
  3019. return SemaVSXCheck(TheCall) ||
  3020. SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  3021. case PPC::BI__builtin_pack_vector_int128:
  3022. return SemaVSXCheck(TheCall);
  3023. }
  3024. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3025. }
  3026. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  3027. CallExpr *TheCall) {
  3028. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  3029. Expr *Arg = TheCall->getArg(0);
  3030. llvm::APSInt AbortCode(32);
  3031. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  3032. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  3033. return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
  3034. << Arg->getSourceRange();
  3035. }
  3036. // For intrinsics which take an immediate value as part of the instruction,
  3037. // range check them here.
  3038. unsigned i = 0, l = 0, u = 0;
  3039. switch (BuiltinID) {
  3040. default: return false;
  3041. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  3042. case SystemZ::BI__builtin_s390_verimb:
  3043. case SystemZ::BI__builtin_s390_verimh:
  3044. case SystemZ::BI__builtin_s390_verimf:
  3045. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  3046. case SystemZ::BI__builtin_s390_vfaeb:
  3047. case SystemZ::BI__builtin_s390_vfaeh:
  3048. case SystemZ::BI__builtin_s390_vfaef:
  3049. case SystemZ::BI__builtin_s390_vfaebs:
  3050. case SystemZ::BI__builtin_s390_vfaehs:
  3051. case SystemZ::BI__builtin_s390_vfaefs:
  3052. case SystemZ::BI__builtin_s390_vfaezb:
  3053. case SystemZ::BI__builtin_s390_vfaezh:
  3054. case SystemZ::BI__builtin_s390_vfaezf:
  3055. case SystemZ::BI__builtin_s390_vfaezbs:
  3056. case SystemZ::BI__builtin_s390_vfaezhs:
  3057. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  3058. case SystemZ::BI__builtin_s390_vfisb:
  3059. case SystemZ::BI__builtin_s390_vfidb:
  3060. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  3061. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3062. case SystemZ::BI__builtin_s390_vftcisb:
  3063. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  3064. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  3065. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  3066. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  3067. case SystemZ::BI__builtin_s390_vstrcb:
  3068. case SystemZ::BI__builtin_s390_vstrch:
  3069. case SystemZ::BI__builtin_s390_vstrcf:
  3070. case SystemZ::BI__builtin_s390_vstrczb:
  3071. case SystemZ::BI__builtin_s390_vstrczh:
  3072. case SystemZ::BI__builtin_s390_vstrczf:
  3073. case SystemZ::BI__builtin_s390_vstrcbs:
  3074. case SystemZ::BI__builtin_s390_vstrchs:
  3075. case SystemZ::BI__builtin_s390_vstrcfs:
  3076. case SystemZ::BI__builtin_s390_vstrczbs:
  3077. case SystemZ::BI__builtin_s390_vstrczhs:
  3078. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  3079. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  3080. case SystemZ::BI__builtin_s390_vfminsb:
  3081. case SystemZ::BI__builtin_s390_vfmaxsb:
  3082. case SystemZ::BI__builtin_s390_vfmindb:
  3083. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  3084. }
  3085. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3086. }
  3087. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  3088. /// This checks that the target supports __builtin_cpu_supports and
  3089. /// that the string argument is constant and valid.
  3090. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  3091. Expr *Arg = TheCall->getArg(0);
  3092. // Check if the argument is a string literal.
  3093. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3094. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3095. << Arg->getSourceRange();
  3096. // Check the contents of the string.
  3097. StringRef Feature =
  3098. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3099. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  3100. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
  3101. << Arg->getSourceRange();
  3102. return false;
  3103. }
  3104. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  3105. /// This checks that the target supports __builtin_cpu_is and
  3106. /// that the string argument is constant and valid.
  3107. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  3108. Expr *Arg = TheCall->getArg(0);
  3109. // Check if the argument is a string literal.
  3110. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3111. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3112. << Arg->getSourceRange();
  3113. // Check the contents of the string.
  3114. StringRef Feature =
  3115. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3116. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  3117. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
  3118. << Arg->getSourceRange();
  3119. return false;
  3120. }
  3121. // Check if the rounding mode is legal.
  3122. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  3123. // Indicates if this instruction has rounding control or just SAE.
  3124. bool HasRC = false;
  3125. unsigned ArgNum = 0;
  3126. switch (BuiltinID) {
  3127. default:
  3128. return false;
  3129. case X86::BI__builtin_ia32_vcvttsd2si32:
  3130. case X86::BI__builtin_ia32_vcvttsd2si64:
  3131. case X86::BI__builtin_ia32_vcvttsd2usi32:
  3132. case X86::BI__builtin_ia32_vcvttsd2usi64:
  3133. case X86::BI__builtin_ia32_vcvttss2si32:
  3134. case X86::BI__builtin_ia32_vcvttss2si64:
  3135. case X86::BI__builtin_ia32_vcvttss2usi32:
  3136. case X86::BI__builtin_ia32_vcvttss2usi64:
  3137. ArgNum = 1;
  3138. break;
  3139. case X86::BI__builtin_ia32_maxpd512:
  3140. case X86::BI__builtin_ia32_maxps512:
  3141. case X86::BI__builtin_ia32_minpd512:
  3142. case X86::BI__builtin_ia32_minps512:
  3143. ArgNum = 2;
  3144. break;
  3145. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  3146. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  3147. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  3148. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  3149. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  3150. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  3151. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  3152. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  3153. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  3154. case X86::BI__builtin_ia32_exp2pd_mask:
  3155. case X86::BI__builtin_ia32_exp2ps_mask:
  3156. case X86::BI__builtin_ia32_getexppd512_mask:
  3157. case X86::BI__builtin_ia32_getexpps512_mask:
  3158. case X86::BI__builtin_ia32_rcp28pd_mask:
  3159. case X86::BI__builtin_ia32_rcp28ps_mask:
  3160. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  3161. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  3162. case X86::BI__builtin_ia32_vcomisd:
  3163. case X86::BI__builtin_ia32_vcomiss:
  3164. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  3165. ArgNum = 3;
  3166. break;
  3167. case X86::BI__builtin_ia32_cmppd512_mask:
  3168. case X86::BI__builtin_ia32_cmpps512_mask:
  3169. case X86::BI__builtin_ia32_cmpsd_mask:
  3170. case X86::BI__builtin_ia32_cmpss_mask:
  3171. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  3172. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  3173. case X86::BI__builtin_ia32_getexpss128_round_mask:
  3174. case X86::BI__builtin_ia32_getmantpd512_mask:
  3175. case X86::BI__builtin_ia32_getmantps512_mask:
  3176. case X86::BI__builtin_ia32_maxsd_round_mask:
  3177. case X86::BI__builtin_ia32_maxss_round_mask:
  3178. case X86::BI__builtin_ia32_minsd_round_mask:
  3179. case X86::BI__builtin_ia32_minss_round_mask:
  3180. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  3181. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  3182. case X86::BI__builtin_ia32_reducepd512_mask:
  3183. case X86::BI__builtin_ia32_reduceps512_mask:
  3184. case X86::BI__builtin_ia32_rndscalepd_mask:
  3185. case X86::BI__builtin_ia32_rndscaleps_mask:
  3186. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  3187. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  3188. ArgNum = 4;
  3189. break;
  3190. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3191. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3192. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3193. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3194. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3195. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3196. case X86::BI__builtin_ia32_fixupimmss_mask:
  3197. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3198. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3199. case X86::BI__builtin_ia32_getmantss_round_mask:
  3200. case X86::BI__builtin_ia32_rangepd512_mask:
  3201. case X86::BI__builtin_ia32_rangeps512_mask:
  3202. case X86::BI__builtin_ia32_rangesd128_round_mask:
  3203. case X86::BI__builtin_ia32_rangess128_round_mask:
  3204. case X86::BI__builtin_ia32_reducesd_mask:
  3205. case X86::BI__builtin_ia32_reducess_mask:
  3206. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3207. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3208. ArgNum = 5;
  3209. break;
  3210. case X86::BI__builtin_ia32_vcvtsd2si64:
  3211. case X86::BI__builtin_ia32_vcvtsd2si32:
  3212. case X86::BI__builtin_ia32_vcvtsd2usi32:
  3213. case X86::BI__builtin_ia32_vcvtsd2usi64:
  3214. case X86::BI__builtin_ia32_vcvtss2si32:
  3215. case X86::BI__builtin_ia32_vcvtss2si64:
  3216. case X86::BI__builtin_ia32_vcvtss2usi32:
  3217. case X86::BI__builtin_ia32_vcvtss2usi64:
  3218. case X86::BI__builtin_ia32_sqrtpd512:
  3219. case X86::BI__builtin_ia32_sqrtps512:
  3220. ArgNum = 1;
  3221. HasRC = true;
  3222. break;
  3223. case X86::BI__builtin_ia32_addpd512:
  3224. case X86::BI__builtin_ia32_addps512:
  3225. case X86::BI__builtin_ia32_divpd512:
  3226. case X86::BI__builtin_ia32_divps512:
  3227. case X86::BI__builtin_ia32_mulpd512:
  3228. case X86::BI__builtin_ia32_mulps512:
  3229. case X86::BI__builtin_ia32_subpd512:
  3230. case X86::BI__builtin_ia32_subps512:
  3231. case X86::BI__builtin_ia32_cvtsi2sd64:
  3232. case X86::BI__builtin_ia32_cvtsi2ss32:
  3233. case X86::BI__builtin_ia32_cvtsi2ss64:
  3234. case X86::BI__builtin_ia32_cvtusi2sd64:
  3235. case X86::BI__builtin_ia32_cvtusi2ss32:
  3236. case X86::BI__builtin_ia32_cvtusi2ss64:
  3237. ArgNum = 2;
  3238. HasRC = true;
  3239. break;
  3240. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  3241. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  3242. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  3243. case X86::BI__builtin_ia32_cvtpd2dq512_mask:
  3244. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  3245. case X86::BI__builtin_ia32_cvtpd2udq512_mask:
  3246. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  3247. case X86::BI__builtin_ia32_cvtps2dq512_mask:
  3248. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  3249. case X86::BI__builtin_ia32_cvtps2udq512_mask:
  3250. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  3251. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  3252. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  3253. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  3254. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  3255. ArgNum = 3;
  3256. HasRC = true;
  3257. break;
  3258. case X86::BI__builtin_ia32_addss_round_mask:
  3259. case X86::BI__builtin_ia32_addsd_round_mask:
  3260. case X86::BI__builtin_ia32_divss_round_mask:
  3261. case X86::BI__builtin_ia32_divsd_round_mask:
  3262. case X86::BI__builtin_ia32_mulss_round_mask:
  3263. case X86::BI__builtin_ia32_mulsd_round_mask:
  3264. case X86::BI__builtin_ia32_subss_round_mask:
  3265. case X86::BI__builtin_ia32_subsd_round_mask:
  3266. case X86::BI__builtin_ia32_scalefpd512_mask:
  3267. case X86::BI__builtin_ia32_scalefps512_mask:
  3268. case X86::BI__builtin_ia32_scalefsd_round_mask:
  3269. case X86::BI__builtin_ia32_scalefss_round_mask:
  3270. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  3271. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  3272. case X86::BI__builtin_ia32_sqrtss_round_mask:
  3273. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  3274. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  3275. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  3276. case X86::BI__builtin_ia32_vfmaddss3_mask:
  3277. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  3278. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  3279. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  3280. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  3281. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  3282. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  3283. case X86::BI__builtin_ia32_vfmaddps512_mask:
  3284. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  3285. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  3286. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  3287. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  3288. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  3289. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  3290. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  3291. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  3292. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  3293. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  3294. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  3295. ArgNum = 4;
  3296. HasRC = true;
  3297. break;
  3298. }
  3299. llvm::APSInt Result;
  3300. // We can't check the value of a dependent argument.
  3301. Expr *Arg = TheCall->getArg(ArgNum);
  3302. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3303. return false;
  3304. // Check constant-ness first.
  3305. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3306. return true;
  3307. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  3308. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  3309. // combined with ROUND_NO_EXC.
  3310. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  3311. Result == 8/*ROUND_NO_EXC*/ ||
  3312. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  3313. return false;
  3314. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
  3315. << Arg->getSourceRange();
  3316. }
  3317. // Check if the gather/scatter scale is legal.
  3318. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  3319. CallExpr *TheCall) {
  3320. unsigned ArgNum = 0;
  3321. switch (BuiltinID) {
  3322. default:
  3323. return false;
  3324. case X86::BI__builtin_ia32_gatherpfdpd:
  3325. case X86::BI__builtin_ia32_gatherpfdps:
  3326. case X86::BI__builtin_ia32_gatherpfqpd:
  3327. case X86::BI__builtin_ia32_gatherpfqps:
  3328. case X86::BI__builtin_ia32_scatterpfdpd:
  3329. case X86::BI__builtin_ia32_scatterpfdps:
  3330. case X86::BI__builtin_ia32_scatterpfqpd:
  3331. case X86::BI__builtin_ia32_scatterpfqps:
  3332. ArgNum = 3;
  3333. break;
  3334. case X86::BI__builtin_ia32_gatherd_pd:
  3335. case X86::BI__builtin_ia32_gatherd_pd256:
  3336. case X86::BI__builtin_ia32_gatherq_pd:
  3337. case X86::BI__builtin_ia32_gatherq_pd256:
  3338. case X86::BI__builtin_ia32_gatherd_ps:
  3339. case X86::BI__builtin_ia32_gatherd_ps256:
  3340. case X86::BI__builtin_ia32_gatherq_ps:
  3341. case X86::BI__builtin_ia32_gatherq_ps256:
  3342. case X86::BI__builtin_ia32_gatherd_q:
  3343. case X86::BI__builtin_ia32_gatherd_q256:
  3344. case X86::BI__builtin_ia32_gatherq_q:
  3345. case X86::BI__builtin_ia32_gatherq_q256:
  3346. case X86::BI__builtin_ia32_gatherd_d:
  3347. case X86::BI__builtin_ia32_gatherd_d256:
  3348. case X86::BI__builtin_ia32_gatherq_d:
  3349. case X86::BI__builtin_ia32_gatherq_d256:
  3350. case X86::BI__builtin_ia32_gather3div2df:
  3351. case X86::BI__builtin_ia32_gather3div2di:
  3352. case X86::BI__builtin_ia32_gather3div4df:
  3353. case X86::BI__builtin_ia32_gather3div4di:
  3354. case X86::BI__builtin_ia32_gather3div4sf:
  3355. case X86::BI__builtin_ia32_gather3div4si:
  3356. case X86::BI__builtin_ia32_gather3div8sf:
  3357. case X86::BI__builtin_ia32_gather3div8si:
  3358. case X86::BI__builtin_ia32_gather3siv2df:
  3359. case X86::BI__builtin_ia32_gather3siv2di:
  3360. case X86::BI__builtin_ia32_gather3siv4df:
  3361. case X86::BI__builtin_ia32_gather3siv4di:
  3362. case X86::BI__builtin_ia32_gather3siv4sf:
  3363. case X86::BI__builtin_ia32_gather3siv4si:
  3364. case X86::BI__builtin_ia32_gather3siv8sf:
  3365. case X86::BI__builtin_ia32_gather3siv8si:
  3366. case X86::BI__builtin_ia32_gathersiv8df:
  3367. case X86::BI__builtin_ia32_gathersiv16sf:
  3368. case X86::BI__builtin_ia32_gatherdiv8df:
  3369. case X86::BI__builtin_ia32_gatherdiv16sf:
  3370. case X86::BI__builtin_ia32_gathersiv8di:
  3371. case X86::BI__builtin_ia32_gathersiv16si:
  3372. case X86::BI__builtin_ia32_gatherdiv8di:
  3373. case X86::BI__builtin_ia32_gatherdiv16si:
  3374. case X86::BI__builtin_ia32_scatterdiv2df:
  3375. case X86::BI__builtin_ia32_scatterdiv2di:
  3376. case X86::BI__builtin_ia32_scatterdiv4df:
  3377. case X86::BI__builtin_ia32_scatterdiv4di:
  3378. case X86::BI__builtin_ia32_scatterdiv4sf:
  3379. case X86::BI__builtin_ia32_scatterdiv4si:
  3380. case X86::BI__builtin_ia32_scatterdiv8sf:
  3381. case X86::BI__builtin_ia32_scatterdiv8si:
  3382. case X86::BI__builtin_ia32_scattersiv2df:
  3383. case X86::BI__builtin_ia32_scattersiv2di:
  3384. case X86::BI__builtin_ia32_scattersiv4df:
  3385. case X86::BI__builtin_ia32_scattersiv4di:
  3386. case X86::BI__builtin_ia32_scattersiv4sf:
  3387. case X86::BI__builtin_ia32_scattersiv4si:
  3388. case X86::BI__builtin_ia32_scattersiv8sf:
  3389. case X86::BI__builtin_ia32_scattersiv8si:
  3390. case X86::BI__builtin_ia32_scattersiv8df:
  3391. case X86::BI__builtin_ia32_scattersiv16sf:
  3392. case X86::BI__builtin_ia32_scatterdiv8df:
  3393. case X86::BI__builtin_ia32_scatterdiv16sf:
  3394. case X86::BI__builtin_ia32_scattersiv8di:
  3395. case X86::BI__builtin_ia32_scattersiv16si:
  3396. case X86::BI__builtin_ia32_scatterdiv8di:
  3397. case X86::BI__builtin_ia32_scatterdiv16si:
  3398. ArgNum = 4;
  3399. break;
  3400. }
  3401. llvm::APSInt Result;
  3402. // We can't check the value of a dependent argument.
  3403. Expr *Arg = TheCall->getArg(ArgNum);
  3404. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3405. return false;
  3406. // Check constant-ness first.
  3407. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3408. return true;
  3409. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  3410. return false;
  3411. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
  3412. << Arg->getSourceRange();
  3413. }
  3414. static bool isX86_32Builtin(unsigned BuiltinID) {
  3415. // These builtins only work on x86-32 targets.
  3416. switch (BuiltinID) {
  3417. case X86::BI__builtin_ia32_readeflags_u32:
  3418. case X86::BI__builtin_ia32_writeeflags_u32:
  3419. return true;
  3420. }
  3421. return false;
  3422. }
  3423. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  3424. if (BuiltinID == X86::BI__builtin_cpu_supports)
  3425. return SemaBuiltinCpuSupports(*this, TheCall);
  3426. if (BuiltinID == X86::BI__builtin_cpu_is)
  3427. return SemaBuiltinCpuIs(*this, TheCall);
  3428. // Check for 32-bit only builtins on a 64-bit target.
  3429. const llvm::Triple &TT = Context.getTargetInfo().getTriple();
  3430. if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
  3431. return Diag(TheCall->getCallee()->getBeginLoc(),
  3432. diag::err_32_bit_builtin_64_bit_tgt);
  3433. // If the intrinsic has rounding or SAE make sure its valid.
  3434. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  3435. return true;
  3436. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  3437. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  3438. return true;
  3439. // For intrinsics which take an immediate value as part of the instruction,
  3440. // range check them here.
  3441. int i = 0, l = 0, u = 0;
  3442. switch (BuiltinID) {
  3443. default:
  3444. return false;
  3445. case X86::BI__builtin_ia32_vec_ext_v2si:
  3446. case X86::BI__builtin_ia32_vec_ext_v2di:
  3447. case X86::BI__builtin_ia32_vextractf128_pd256:
  3448. case X86::BI__builtin_ia32_vextractf128_ps256:
  3449. case X86::BI__builtin_ia32_vextractf128_si256:
  3450. case X86::BI__builtin_ia32_extract128i256:
  3451. case X86::BI__builtin_ia32_extractf64x4_mask:
  3452. case X86::BI__builtin_ia32_extracti64x4_mask:
  3453. case X86::BI__builtin_ia32_extractf32x8_mask:
  3454. case X86::BI__builtin_ia32_extracti32x8_mask:
  3455. case X86::BI__builtin_ia32_extractf64x2_256_mask:
  3456. case X86::BI__builtin_ia32_extracti64x2_256_mask:
  3457. case X86::BI__builtin_ia32_extractf32x4_256_mask:
  3458. case X86::BI__builtin_ia32_extracti32x4_256_mask:
  3459. i = 1; l = 0; u = 1;
  3460. break;
  3461. case X86::BI__builtin_ia32_vec_set_v2di:
  3462. case X86::BI__builtin_ia32_vinsertf128_pd256:
  3463. case X86::BI__builtin_ia32_vinsertf128_ps256:
  3464. case X86::BI__builtin_ia32_vinsertf128_si256:
  3465. case X86::BI__builtin_ia32_insert128i256:
  3466. case X86::BI__builtin_ia32_insertf32x8:
  3467. case X86::BI__builtin_ia32_inserti32x8:
  3468. case X86::BI__builtin_ia32_insertf64x4:
  3469. case X86::BI__builtin_ia32_inserti64x4:
  3470. case X86::BI__builtin_ia32_insertf64x2_256:
  3471. case X86::BI__builtin_ia32_inserti64x2_256:
  3472. case X86::BI__builtin_ia32_insertf32x4_256:
  3473. case X86::BI__builtin_ia32_inserti32x4_256:
  3474. i = 2; l = 0; u = 1;
  3475. break;
  3476. case X86::BI__builtin_ia32_vpermilpd:
  3477. case X86::BI__builtin_ia32_vec_ext_v4hi:
  3478. case X86::BI__builtin_ia32_vec_ext_v4si:
  3479. case X86::BI__builtin_ia32_vec_ext_v4sf:
  3480. case X86::BI__builtin_ia32_vec_ext_v4di:
  3481. case X86::BI__builtin_ia32_extractf32x4_mask:
  3482. case X86::BI__builtin_ia32_extracti32x4_mask:
  3483. case X86::BI__builtin_ia32_extractf64x2_512_mask:
  3484. case X86::BI__builtin_ia32_extracti64x2_512_mask:
  3485. i = 1; l = 0; u = 3;
  3486. break;
  3487. case X86::BI_mm_prefetch:
  3488. case X86::BI__builtin_ia32_vec_ext_v8hi:
  3489. case X86::BI__builtin_ia32_vec_ext_v8si:
  3490. i = 1; l = 0; u = 7;
  3491. break;
  3492. case X86::BI__builtin_ia32_sha1rnds4:
  3493. case X86::BI__builtin_ia32_blendpd:
  3494. case X86::BI__builtin_ia32_shufpd:
  3495. case X86::BI__builtin_ia32_vec_set_v4hi:
  3496. case X86::BI__builtin_ia32_vec_set_v4si:
  3497. case X86::BI__builtin_ia32_vec_set_v4di:
  3498. case X86::BI__builtin_ia32_shuf_f32x4_256:
  3499. case X86::BI__builtin_ia32_shuf_f64x2_256:
  3500. case X86::BI__builtin_ia32_shuf_i32x4_256:
  3501. case X86::BI__builtin_ia32_shuf_i64x2_256:
  3502. case X86::BI__builtin_ia32_insertf64x2_512:
  3503. case X86::BI__builtin_ia32_inserti64x2_512:
  3504. case X86::BI__builtin_ia32_insertf32x4:
  3505. case X86::BI__builtin_ia32_inserti32x4:
  3506. i = 2; l = 0; u = 3;
  3507. break;
  3508. case X86::BI__builtin_ia32_vpermil2pd:
  3509. case X86::BI__builtin_ia32_vpermil2pd256:
  3510. case X86::BI__builtin_ia32_vpermil2ps:
  3511. case X86::BI__builtin_ia32_vpermil2ps256:
  3512. i = 3; l = 0; u = 3;
  3513. break;
  3514. case X86::BI__builtin_ia32_cmpb128_mask:
  3515. case X86::BI__builtin_ia32_cmpw128_mask:
  3516. case X86::BI__builtin_ia32_cmpd128_mask:
  3517. case X86::BI__builtin_ia32_cmpq128_mask:
  3518. case X86::BI__builtin_ia32_cmpb256_mask:
  3519. case X86::BI__builtin_ia32_cmpw256_mask:
  3520. case X86::BI__builtin_ia32_cmpd256_mask:
  3521. case X86::BI__builtin_ia32_cmpq256_mask:
  3522. case X86::BI__builtin_ia32_cmpb512_mask:
  3523. case X86::BI__builtin_ia32_cmpw512_mask:
  3524. case X86::BI__builtin_ia32_cmpd512_mask:
  3525. case X86::BI__builtin_ia32_cmpq512_mask:
  3526. case X86::BI__builtin_ia32_ucmpb128_mask:
  3527. case X86::BI__builtin_ia32_ucmpw128_mask:
  3528. case X86::BI__builtin_ia32_ucmpd128_mask:
  3529. case X86::BI__builtin_ia32_ucmpq128_mask:
  3530. case X86::BI__builtin_ia32_ucmpb256_mask:
  3531. case X86::BI__builtin_ia32_ucmpw256_mask:
  3532. case X86::BI__builtin_ia32_ucmpd256_mask:
  3533. case X86::BI__builtin_ia32_ucmpq256_mask:
  3534. case X86::BI__builtin_ia32_ucmpb512_mask:
  3535. case X86::BI__builtin_ia32_ucmpw512_mask:
  3536. case X86::BI__builtin_ia32_ucmpd512_mask:
  3537. case X86::BI__builtin_ia32_ucmpq512_mask:
  3538. case X86::BI__builtin_ia32_vpcomub:
  3539. case X86::BI__builtin_ia32_vpcomuw:
  3540. case X86::BI__builtin_ia32_vpcomud:
  3541. case X86::BI__builtin_ia32_vpcomuq:
  3542. case X86::BI__builtin_ia32_vpcomb:
  3543. case X86::BI__builtin_ia32_vpcomw:
  3544. case X86::BI__builtin_ia32_vpcomd:
  3545. case X86::BI__builtin_ia32_vpcomq:
  3546. case X86::BI__builtin_ia32_vec_set_v8hi:
  3547. case X86::BI__builtin_ia32_vec_set_v8si:
  3548. i = 2; l = 0; u = 7;
  3549. break;
  3550. case X86::BI__builtin_ia32_vpermilpd256:
  3551. case X86::BI__builtin_ia32_roundps:
  3552. case X86::BI__builtin_ia32_roundpd:
  3553. case X86::BI__builtin_ia32_roundps256:
  3554. case X86::BI__builtin_ia32_roundpd256:
  3555. case X86::BI__builtin_ia32_getmantpd128_mask:
  3556. case X86::BI__builtin_ia32_getmantpd256_mask:
  3557. case X86::BI__builtin_ia32_getmantps128_mask:
  3558. case X86::BI__builtin_ia32_getmantps256_mask:
  3559. case X86::BI__builtin_ia32_getmantpd512_mask:
  3560. case X86::BI__builtin_ia32_getmantps512_mask:
  3561. case X86::BI__builtin_ia32_vec_ext_v16qi:
  3562. case X86::BI__builtin_ia32_vec_ext_v16hi:
  3563. i = 1; l = 0; u = 15;
  3564. break;
  3565. case X86::BI__builtin_ia32_pblendd128:
  3566. case X86::BI__builtin_ia32_blendps:
  3567. case X86::BI__builtin_ia32_blendpd256:
  3568. case X86::BI__builtin_ia32_shufpd256:
  3569. case X86::BI__builtin_ia32_roundss:
  3570. case X86::BI__builtin_ia32_roundsd:
  3571. case X86::BI__builtin_ia32_rangepd128_mask:
  3572. case X86::BI__builtin_ia32_rangepd256_mask:
  3573. case X86::BI__builtin_ia32_rangepd512_mask:
  3574. case X86::BI__builtin_ia32_rangeps128_mask:
  3575. case X86::BI__builtin_ia32_rangeps256_mask:
  3576. case X86::BI__builtin_ia32_rangeps512_mask:
  3577. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3578. case X86::BI__builtin_ia32_getmantss_round_mask:
  3579. case X86::BI__builtin_ia32_vec_set_v16qi:
  3580. case X86::BI__builtin_ia32_vec_set_v16hi:
  3581. i = 2; l = 0; u = 15;
  3582. break;
  3583. case X86::BI__builtin_ia32_vec_ext_v32qi:
  3584. i = 1; l = 0; u = 31;
  3585. break;
  3586. case X86::BI__builtin_ia32_cmpps:
  3587. case X86::BI__builtin_ia32_cmpss:
  3588. case X86::BI__builtin_ia32_cmppd:
  3589. case X86::BI__builtin_ia32_cmpsd:
  3590. case X86::BI__builtin_ia32_cmpps256:
  3591. case X86::BI__builtin_ia32_cmppd256:
  3592. case X86::BI__builtin_ia32_cmpps128_mask:
  3593. case X86::BI__builtin_ia32_cmppd128_mask:
  3594. case X86::BI__builtin_ia32_cmpps256_mask:
  3595. case X86::BI__builtin_ia32_cmppd256_mask:
  3596. case X86::BI__builtin_ia32_cmpps512_mask:
  3597. case X86::BI__builtin_ia32_cmppd512_mask:
  3598. case X86::BI__builtin_ia32_cmpsd_mask:
  3599. case X86::BI__builtin_ia32_cmpss_mask:
  3600. case X86::BI__builtin_ia32_vec_set_v32qi:
  3601. i = 2; l = 0; u = 31;
  3602. break;
  3603. case X86::BI__builtin_ia32_permdf256:
  3604. case X86::BI__builtin_ia32_permdi256:
  3605. case X86::BI__builtin_ia32_permdf512:
  3606. case X86::BI__builtin_ia32_permdi512:
  3607. case X86::BI__builtin_ia32_vpermilps:
  3608. case X86::BI__builtin_ia32_vpermilps256:
  3609. case X86::BI__builtin_ia32_vpermilpd512:
  3610. case X86::BI__builtin_ia32_vpermilps512:
  3611. case X86::BI__builtin_ia32_pshufd:
  3612. case X86::BI__builtin_ia32_pshufd256:
  3613. case X86::BI__builtin_ia32_pshufd512:
  3614. case X86::BI__builtin_ia32_pshufhw:
  3615. case X86::BI__builtin_ia32_pshufhw256:
  3616. case X86::BI__builtin_ia32_pshufhw512:
  3617. case X86::BI__builtin_ia32_pshuflw:
  3618. case X86::BI__builtin_ia32_pshuflw256:
  3619. case X86::BI__builtin_ia32_pshuflw512:
  3620. case X86::BI__builtin_ia32_vcvtps2ph:
  3621. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  3622. case X86::BI__builtin_ia32_vcvtps2ph256:
  3623. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  3624. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  3625. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  3626. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  3627. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  3628. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  3629. case X86::BI__builtin_ia32_rndscaleps_mask:
  3630. case X86::BI__builtin_ia32_rndscalepd_mask:
  3631. case X86::BI__builtin_ia32_reducepd128_mask:
  3632. case X86::BI__builtin_ia32_reducepd256_mask:
  3633. case X86::BI__builtin_ia32_reducepd512_mask:
  3634. case X86::BI__builtin_ia32_reduceps128_mask:
  3635. case X86::BI__builtin_ia32_reduceps256_mask:
  3636. case X86::BI__builtin_ia32_reduceps512_mask:
  3637. case X86::BI__builtin_ia32_prold512:
  3638. case X86::BI__builtin_ia32_prolq512:
  3639. case X86::BI__builtin_ia32_prold128:
  3640. case X86::BI__builtin_ia32_prold256:
  3641. case X86::BI__builtin_ia32_prolq128:
  3642. case X86::BI__builtin_ia32_prolq256:
  3643. case X86::BI__builtin_ia32_prord512:
  3644. case X86::BI__builtin_ia32_prorq512:
  3645. case X86::BI__builtin_ia32_prord128:
  3646. case X86::BI__builtin_ia32_prord256:
  3647. case X86::BI__builtin_ia32_prorq128:
  3648. case X86::BI__builtin_ia32_prorq256:
  3649. case X86::BI__builtin_ia32_fpclasspd128_mask:
  3650. case X86::BI__builtin_ia32_fpclasspd256_mask:
  3651. case X86::BI__builtin_ia32_fpclassps128_mask:
  3652. case X86::BI__builtin_ia32_fpclassps256_mask:
  3653. case X86::BI__builtin_ia32_fpclassps512_mask:
  3654. case X86::BI__builtin_ia32_fpclasspd512_mask:
  3655. case X86::BI__builtin_ia32_fpclasssd_mask:
  3656. case X86::BI__builtin_ia32_fpclassss_mask:
  3657. case X86::BI__builtin_ia32_pslldqi128_byteshift:
  3658. case X86::BI__builtin_ia32_pslldqi256_byteshift:
  3659. case X86::BI__builtin_ia32_pslldqi512_byteshift:
  3660. case X86::BI__builtin_ia32_psrldqi128_byteshift:
  3661. case X86::BI__builtin_ia32_psrldqi256_byteshift:
  3662. case X86::BI__builtin_ia32_psrldqi512_byteshift:
  3663. case X86::BI__builtin_ia32_kshiftliqi:
  3664. case X86::BI__builtin_ia32_kshiftlihi:
  3665. case X86::BI__builtin_ia32_kshiftlisi:
  3666. case X86::BI__builtin_ia32_kshiftlidi:
  3667. case X86::BI__builtin_ia32_kshiftriqi:
  3668. case X86::BI__builtin_ia32_kshiftrihi:
  3669. case X86::BI__builtin_ia32_kshiftrisi:
  3670. case X86::BI__builtin_ia32_kshiftridi:
  3671. i = 1; l = 0; u = 255;
  3672. break;
  3673. case X86::BI__builtin_ia32_vperm2f128_pd256:
  3674. case X86::BI__builtin_ia32_vperm2f128_ps256:
  3675. case X86::BI__builtin_ia32_vperm2f128_si256:
  3676. case X86::BI__builtin_ia32_permti256:
  3677. case X86::BI__builtin_ia32_pblendw128:
  3678. case X86::BI__builtin_ia32_pblendw256:
  3679. case X86::BI__builtin_ia32_blendps256:
  3680. case X86::BI__builtin_ia32_pblendd256:
  3681. case X86::BI__builtin_ia32_palignr128:
  3682. case X86::BI__builtin_ia32_palignr256:
  3683. case X86::BI__builtin_ia32_palignr512:
  3684. case X86::BI__builtin_ia32_alignq512:
  3685. case X86::BI__builtin_ia32_alignd512:
  3686. case X86::BI__builtin_ia32_alignd128:
  3687. case X86::BI__builtin_ia32_alignd256:
  3688. case X86::BI__builtin_ia32_alignq128:
  3689. case X86::BI__builtin_ia32_alignq256:
  3690. case X86::BI__builtin_ia32_vcomisd:
  3691. case X86::BI__builtin_ia32_vcomiss:
  3692. case X86::BI__builtin_ia32_shuf_f32x4:
  3693. case X86::BI__builtin_ia32_shuf_f64x2:
  3694. case X86::BI__builtin_ia32_shuf_i32x4:
  3695. case X86::BI__builtin_ia32_shuf_i64x2:
  3696. case X86::BI__builtin_ia32_shufpd512:
  3697. case X86::BI__builtin_ia32_shufps:
  3698. case X86::BI__builtin_ia32_shufps256:
  3699. case X86::BI__builtin_ia32_shufps512:
  3700. case X86::BI__builtin_ia32_dbpsadbw128:
  3701. case X86::BI__builtin_ia32_dbpsadbw256:
  3702. case X86::BI__builtin_ia32_dbpsadbw512:
  3703. case X86::BI__builtin_ia32_vpshldd128:
  3704. case X86::BI__builtin_ia32_vpshldd256:
  3705. case X86::BI__builtin_ia32_vpshldd512:
  3706. case X86::BI__builtin_ia32_vpshldq128:
  3707. case X86::BI__builtin_ia32_vpshldq256:
  3708. case X86::BI__builtin_ia32_vpshldq512:
  3709. case X86::BI__builtin_ia32_vpshldw128:
  3710. case X86::BI__builtin_ia32_vpshldw256:
  3711. case X86::BI__builtin_ia32_vpshldw512:
  3712. case X86::BI__builtin_ia32_vpshrdd128:
  3713. case X86::BI__builtin_ia32_vpshrdd256:
  3714. case X86::BI__builtin_ia32_vpshrdd512:
  3715. case X86::BI__builtin_ia32_vpshrdq128:
  3716. case X86::BI__builtin_ia32_vpshrdq256:
  3717. case X86::BI__builtin_ia32_vpshrdq512:
  3718. case X86::BI__builtin_ia32_vpshrdw128:
  3719. case X86::BI__builtin_ia32_vpshrdw256:
  3720. case X86::BI__builtin_ia32_vpshrdw512:
  3721. i = 2; l = 0; u = 255;
  3722. break;
  3723. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3724. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3725. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3726. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3727. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3728. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3729. case X86::BI__builtin_ia32_fixupimmss_mask:
  3730. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3731. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  3732. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  3733. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  3734. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  3735. case X86::BI__builtin_ia32_fixupimmps128_mask:
  3736. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  3737. case X86::BI__builtin_ia32_fixupimmps256_mask:
  3738. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  3739. case X86::BI__builtin_ia32_pternlogd512_mask:
  3740. case X86::BI__builtin_ia32_pternlogd512_maskz:
  3741. case X86::BI__builtin_ia32_pternlogq512_mask:
  3742. case X86::BI__builtin_ia32_pternlogq512_maskz:
  3743. case X86::BI__builtin_ia32_pternlogd128_mask:
  3744. case X86::BI__builtin_ia32_pternlogd128_maskz:
  3745. case X86::BI__builtin_ia32_pternlogd256_mask:
  3746. case X86::BI__builtin_ia32_pternlogd256_maskz:
  3747. case X86::BI__builtin_ia32_pternlogq128_mask:
  3748. case X86::BI__builtin_ia32_pternlogq128_maskz:
  3749. case X86::BI__builtin_ia32_pternlogq256_mask:
  3750. case X86::BI__builtin_ia32_pternlogq256_maskz:
  3751. i = 3; l = 0; u = 255;
  3752. break;
  3753. case X86::BI__builtin_ia32_gatherpfdpd:
  3754. case X86::BI__builtin_ia32_gatherpfdps:
  3755. case X86::BI__builtin_ia32_gatherpfqpd:
  3756. case X86::BI__builtin_ia32_gatherpfqps:
  3757. case X86::BI__builtin_ia32_scatterpfdpd:
  3758. case X86::BI__builtin_ia32_scatterpfdps:
  3759. case X86::BI__builtin_ia32_scatterpfqpd:
  3760. case X86::BI__builtin_ia32_scatterpfqps:
  3761. i = 4; l = 2; u = 3;
  3762. break;
  3763. case X86::BI__builtin_ia32_reducesd_mask:
  3764. case X86::BI__builtin_ia32_reducess_mask:
  3765. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3766. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3767. i = 4; l = 0; u = 255;
  3768. break;
  3769. }
  3770. // Note that we don't force a hard error on the range check here, allowing
  3771. // template-generated or macro-generated dead code to potentially have out-of-
  3772. // range values. These need to code generate, but don't need to necessarily
  3773. // make any sense. We use a warning that defaults to an error.
  3774. return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
  3775. }
  3776. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  3777. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  3778. /// Returns true when the format fits the function and the FormatStringInfo has
  3779. /// been populated.
  3780. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  3781. FormatStringInfo *FSI) {
  3782. FSI->HasVAListArg = Format->getFirstArg() == 0;
  3783. FSI->FormatIdx = Format->getFormatIdx() - 1;
  3784. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  3785. // The way the format attribute works in GCC, the implicit this argument
  3786. // of member functions is counted. However, it doesn't appear in our own
  3787. // lists, so decrement format_idx in that case.
  3788. if (IsCXXMember) {
  3789. if(FSI->FormatIdx == 0)
  3790. return false;
  3791. --FSI->FormatIdx;
  3792. if (FSI->FirstDataArg != 0)
  3793. --FSI->FirstDataArg;
  3794. }
  3795. return true;
  3796. }
  3797. /// Checks if a the given expression evaluates to null.
  3798. ///
  3799. /// Returns true if the value evaluates to null.
  3800. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  3801. // If the expression has non-null type, it doesn't evaluate to null.
  3802. if (auto nullability
  3803. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  3804. if (*nullability == NullabilityKind::NonNull)
  3805. return false;
  3806. }
  3807. // As a special case, transparent unions initialized with zero are
  3808. // considered null for the purposes of the nonnull attribute.
  3809. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  3810. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  3811. if (const CompoundLiteralExpr *CLE =
  3812. dyn_cast<CompoundLiteralExpr>(Expr))
  3813. if (const InitListExpr *ILE =
  3814. dyn_cast<InitListExpr>(CLE->getInitializer()))
  3815. Expr = ILE->getInit(0);
  3816. }
  3817. bool Result;
  3818. return (!Expr->isValueDependent() &&
  3819. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  3820. !Result);
  3821. }
  3822. static void CheckNonNullArgument(Sema &S,
  3823. const Expr *ArgExpr,
  3824. SourceLocation CallSiteLoc) {
  3825. if (CheckNonNullExpr(S, ArgExpr))
  3826. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  3827. S.PDiag(diag::warn_null_arg)
  3828. << 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. // Already checked by by constant evaluator.
  3893. if (S.isConstantEvaluated())
  3894. return;
  3895. // Check the attributes attached to the method/function itself.
  3896. llvm::SmallBitVector NonNullArgs;
  3897. if (FDecl) {
  3898. // Handle the nonnull attribute on the function/method declaration itself.
  3899. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  3900. if (!NonNull->args_size()) {
  3901. // Easy case: all pointer arguments are nonnull.
  3902. for (const auto *Arg : Args)
  3903. if (S.isValidPointerAttrType(Arg->getType()))
  3904. CheckNonNullArgument(S, Arg, CallSiteLoc);
  3905. return;
  3906. }
  3907. for (const ParamIdx &Idx : NonNull->args()) {
  3908. unsigned IdxAST = Idx.getASTIndex();
  3909. if (IdxAST >= Args.size())
  3910. continue;
  3911. if (NonNullArgs.empty())
  3912. NonNullArgs.resize(Args.size());
  3913. NonNullArgs.set(IdxAST);
  3914. }
  3915. }
  3916. }
  3917. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  3918. // Handle the nonnull attribute on the parameters of the
  3919. // function/method.
  3920. ArrayRef<ParmVarDecl*> parms;
  3921. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  3922. parms = FD->parameters();
  3923. else
  3924. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  3925. unsigned ParamIndex = 0;
  3926. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  3927. I != E; ++I, ++ParamIndex) {
  3928. const ParmVarDecl *PVD = *I;
  3929. if (PVD->hasAttr<NonNullAttr>() ||
  3930. isNonNullType(S.Context, PVD->getType())) {
  3931. if (NonNullArgs.empty())
  3932. NonNullArgs.resize(Args.size());
  3933. NonNullArgs.set(ParamIndex);
  3934. }
  3935. }
  3936. } else {
  3937. // If we have a non-function, non-method declaration but no
  3938. // function prototype, try to dig out the function prototype.
  3939. if (!Proto) {
  3940. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  3941. QualType type = VD->getType().getNonReferenceType();
  3942. if (auto pointerType = type->getAs<PointerType>())
  3943. type = pointerType->getPointeeType();
  3944. else if (auto blockType = type->getAs<BlockPointerType>())
  3945. type = blockType->getPointeeType();
  3946. // FIXME: data member pointers?
  3947. // Dig out the function prototype, if there is one.
  3948. Proto = type->getAs<FunctionProtoType>();
  3949. }
  3950. }
  3951. // Fill in non-null argument information from the nullability
  3952. // information on the parameter types (if we have them).
  3953. if (Proto) {
  3954. unsigned Index = 0;
  3955. for (auto paramType : Proto->getParamTypes()) {
  3956. if (isNonNullType(S.Context, paramType)) {
  3957. if (NonNullArgs.empty())
  3958. NonNullArgs.resize(Args.size());
  3959. NonNullArgs.set(Index);
  3960. }
  3961. ++Index;
  3962. }
  3963. }
  3964. }
  3965. // Check for non-null arguments.
  3966. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  3967. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  3968. if (NonNullArgs[ArgIndex])
  3969. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  3970. }
  3971. }
  3972. /// Handles the checks for format strings, non-POD arguments to vararg
  3973. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  3974. /// attributes.
  3975. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  3976. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  3977. bool IsMemberFunction, SourceLocation Loc,
  3978. SourceRange Range, VariadicCallType CallType) {
  3979. // FIXME: We should check as much as we can in the template definition.
  3980. if (CurContext->isDependentContext())
  3981. return;
  3982. // Printf and scanf checking.
  3983. llvm::SmallBitVector CheckedVarArgs;
  3984. if (FDecl) {
  3985. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3986. // Only create vector if there are format attributes.
  3987. CheckedVarArgs.resize(Args.size());
  3988. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  3989. CheckedVarArgs);
  3990. }
  3991. }
  3992. // Refuse POD arguments that weren't caught by the format string
  3993. // checks above.
  3994. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  3995. if (CallType != VariadicDoesNotApply &&
  3996. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  3997. unsigned NumParams = Proto ? Proto->getNumParams()
  3998. : FDecl && isa<FunctionDecl>(FDecl)
  3999. ? cast<FunctionDecl>(FDecl)->getNumParams()
  4000. : FDecl && isa<ObjCMethodDecl>(FDecl)
  4001. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  4002. : 0;
  4003. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  4004. // Args[ArgIdx] can be null in malformed code.
  4005. if (const Expr *Arg = Args[ArgIdx]) {
  4006. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  4007. checkVariadicArgument(Arg, CallType);
  4008. }
  4009. }
  4010. }
  4011. if (FDecl || Proto) {
  4012. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  4013. // Type safety checking.
  4014. if (FDecl) {
  4015. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  4016. CheckArgumentWithTypeTag(I, Args, Loc);
  4017. }
  4018. }
  4019. if (FD)
  4020. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  4021. }
  4022. /// CheckConstructorCall - Check a constructor call for correctness and safety
  4023. /// properties not enforced by the C type system.
  4024. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  4025. ArrayRef<const Expr *> Args,
  4026. const FunctionProtoType *Proto,
  4027. SourceLocation Loc) {
  4028. VariadicCallType CallType =
  4029. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  4030. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  4031. Loc, SourceRange(), CallType);
  4032. }
  4033. /// CheckFunctionCall - Check a direct function call for various correctness
  4034. /// and safety properties not strictly enforced by the C type system.
  4035. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  4036. const FunctionProtoType *Proto) {
  4037. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  4038. isa<CXXMethodDecl>(FDecl);
  4039. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  4040. IsMemberOperatorCall;
  4041. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  4042. TheCall->getCallee());
  4043. Expr** Args = TheCall->getArgs();
  4044. unsigned NumArgs = TheCall->getNumArgs();
  4045. Expr *ImplicitThis = nullptr;
  4046. if (IsMemberOperatorCall) {
  4047. // If this is a call to a member operator, hide the first argument
  4048. // from checkCall.
  4049. // FIXME: Our choice of AST representation here is less than ideal.
  4050. ImplicitThis = Args[0];
  4051. ++Args;
  4052. --NumArgs;
  4053. } else if (IsMemberFunction)
  4054. ImplicitThis =
  4055. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  4056. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  4057. IsMemberFunction, TheCall->getRParenLoc(),
  4058. TheCall->getCallee()->getSourceRange(), CallType);
  4059. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  4060. // None of the checks below are needed for functions that don't have
  4061. // simple names (e.g., C++ conversion functions).
  4062. if (!FnInfo)
  4063. return false;
  4064. CheckAbsoluteValueFunction(TheCall, FDecl);
  4065. CheckMaxUnsignedZero(TheCall, FDecl);
  4066. if (getLangOpts().ObjC)
  4067. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  4068. unsigned CMId = FDecl->getMemoryFunctionKind();
  4069. if (CMId == 0)
  4070. return false;
  4071. // Handle memory setting and copying functions.
  4072. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  4073. CheckStrlcpycatArguments(TheCall, FnInfo);
  4074. else if (CMId == Builtin::BIstrncat)
  4075. CheckStrncatArguments(TheCall, FnInfo);
  4076. else
  4077. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  4078. return false;
  4079. }
  4080. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  4081. ArrayRef<const Expr *> Args) {
  4082. VariadicCallType CallType =
  4083. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  4084. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  4085. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  4086. CallType);
  4087. return false;
  4088. }
  4089. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  4090. const FunctionProtoType *Proto) {
  4091. QualType Ty;
  4092. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  4093. Ty = V->getType().getNonReferenceType();
  4094. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  4095. Ty = F->getType().getNonReferenceType();
  4096. else
  4097. return false;
  4098. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  4099. !Ty->isFunctionProtoType())
  4100. return false;
  4101. VariadicCallType CallType;
  4102. if (!Proto || !Proto->isVariadic()) {
  4103. CallType = VariadicDoesNotApply;
  4104. } else if (Ty->isBlockPointerType()) {
  4105. CallType = VariadicBlock;
  4106. } else { // Ty->isFunctionPointerType()
  4107. CallType = VariadicFunction;
  4108. }
  4109. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  4110. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4111. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4112. TheCall->getCallee()->getSourceRange(), CallType);
  4113. return false;
  4114. }
  4115. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  4116. /// such as function pointers returned from functions.
  4117. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  4118. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  4119. TheCall->getCallee());
  4120. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  4121. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4122. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4123. TheCall->getCallee()->getSourceRange(), CallType);
  4124. return false;
  4125. }
  4126. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  4127. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  4128. return false;
  4129. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  4130. switch (Op) {
  4131. case AtomicExpr::AO__c11_atomic_init:
  4132. case AtomicExpr::AO__opencl_atomic_init:
  4133. llvm_unreachable("There is no ordering argument for an init");
  4134. case AtomicExpr::AO__c11_atomic_load:
  4135. case AtomicExpr::AO__opencl_atomic_load:
  4136. case AtomicExpr::AO__atomic_load_n:
  4137. case AtomicExpr::AO__atomic_load:
  4138. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  4139. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4140. case AtomicExpr::AO__c11_atomic_store:
  4141. case AtomicExpr::AO__opencl_atomic_store:
  4142. case AtomicExpr::AO__atomic_store:
  4143. case AtomicExpr::AO__atomic_store_n:
  4144. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  4145. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  4146. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4147. default:
  4148. return true;
  4149. }
  4150. }
  4151. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  4152. AtomicExpr::AtomicOp Op) {
  4153. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  4154. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4155. // All the non-OpenCL operations take one of the following forms.
  4156. // The OpenCL operations take the __c11 forms with one extra argument for
  4157. // synchronization scope.
  4158. enum {
  4159. // C __c11_atomic_init(A *, C)
  4160. Init,
  4161. // C __c11_atomic_load(A *, int)
  4162. Load,
  4163. // void __atomic_load(A *, CP, int)
  4164. LoadCopy,
  4165. // void __atomic_store(A *, CP, int)
  4166. Copy,
  4167. // C __c11_atomic_add(A *, M, int)
  4168. Arithmetic,
  4169. // C __atomic_exchange_n(A *, CP, int)
  4170. Xchg,
  4171. // void __atomic_exchange(A *, C *, CP, int)
  4172. GNUXchg,
  4173. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  4174. C11CmpXchg,
  4175. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  4176. GNUCmpXchg
  4177. } Form = Init;
  4178. const unsigned NumForm = GNUCmpXchg + 1;
  4179. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  4180. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  4181. // where:
  4182. // C is an appropriate type,
  4183. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  4184. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  4185. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  4186. // the int parameters are for orderings.
  4187. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  4188. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  4189. "need to update code for modified forms");
  4190. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  4191. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  4192. AtomicExpr::AO__atomic_load,
  4193. "need to update code for modified C11 atomics");
  4194. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  4195. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  4196. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  4197. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  4198. IsOpenCL;
  4199. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  4200. Op == AtomicExpr::AO__atomic_store_n ||
  4201. Op == AtomicExpr::AO__atomic_exchange_n ||
  4202. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  4203. bool IsAddSub = false;
  4204. bool IsMinMax = false;
  4205. switch (Op) {
  4206. case AtomicExpr::AO__c11_atomic_init:
  4207. case AtomicExpr::AO__opencl_atomic_init:
  4208. Form = Init;
  4209. break;
  4210. case AtomicExpr::AO__c11_atomic_load:
  4211. case AtomicExpr::AO__opencl_atomic_load:
  4212. case AtomicExpr::AO__atomic_load_n:
  4213. Form = Load;
  4214. break;
  4215. case AtomicExpr::AO__atomic_load:
  4216. Form = LoadCopy;
  4217. break;
  4218. case AtomicExpr::AO__c11_atomic_store:
  4219. case AtomicExpr::AO__opencl_atomic_store:
  4220. case AtomicExpr::AO__atomic_store:
  4221. case AtomicExpr::AO__atomic_store_n:
  4222. Form = Copy;
  4223. break;
  4224. case AtomicExpr::AO__c11_atomic_fetch_add:
  4225. case AtomicExpr::AO__c11_atomic_fetch_sub:
  4226. case AtomicExpr::AO__opencl_atomic_fetch_add:
  4227. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  4228. case AtomicExpr::AO__opencl_atomic_fetch_min:
  4229. case AtomicExpr::AO__opencl_atomic_fetch_max:
  4230. case AtomicExpr::AO__atomic_fetch_add:
  4231. case AtomicExpr::AO__atomic_fetch_sub:
  4232. case AtomicExpr::AO__atomic_add_fetch:
  4233. case AtomicExpr::AO__atomic_sub_fetch:
  4234. IsAddSub = true;
  4235. LLVM_FALLTHROUGH;
  4236. case AtomicExpr::AO__c11_atomic_fetch_and:
  4237. case AtomicExpr::AO__c11_atomic_fetch_or:
  4238. case AtomicExpr::AO__c11_atomic_fetch_xor:
  4239. case AtomicExpr::AO__opencl_atomic_fetch_and:
  4240. case AtomicExpr::AO__opencl_atomic_fetch_or:
  4241. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  4242. case AtomicExpr::AO__atomic_fetch_and:
  4243. case AtomicExpr::AO__atomic_fetch_or:
  4244. case AtomicExpr::AO__atomic_fetch_xor:
  4245. case AtomicExpr::AO__atomic_fetch_nand:
  4246. case AtomicExpr::AO__atomic_and_fetch:
  4247. case AtomicExpr::AO__atomic_or_fetch:
  4248. case AtomicExpr::AO__atomic_xor_fetch:
  4249. case AtomicExpr::AO__atomic_nand_fetch:
  4250. Form = Arithmetic;
  4251. break;
  4252. case AtomicExpr::AO__atomic_fetch_min:
  4253. case AtomicExpr::AO__atomic_fetch_max:
  4254. IsMinMax = true;
  4255. Form = Arithmetic;
  4256. break;
  4257. case AtomicExpr::AO__c11_atomic_exchange:
  4258. case AtomicExpr::AO__opencl_atomic_exchange:
  4259. case AtomicExpr::AO__atomic_exchange_n:
  4260. Form = Xchg;
  4261. break;
  4262. case AtomicExpr::AO__atomic_exchange:
  4263. Form = GNUXchg;
  4264. break;
  4265. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  4266. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  4267. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  4268. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  4269. Form = C11CmpXchg;
  4270. break;
  4271. case AtomicExpr::AO__atomic_compare_exchange:
  4272. case AtomicExpr::AO__atomic_compare_exchange_n:
  4273. Form = GNUCmpXchg;
  4274. break;
  4275. }
  4276. unsigned AdjustedNumArgs = NumArgs[Form];
  4277. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  4278. ++AdjustedNumArgs;
  4279. // Check we have the right number of arguments.
  4280. if (TheCall->getNumArgs() < AdjustedNumArgs) {
  4281. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  4282. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4283. << TheCall->getCallee()->getSourceRange();
  4284. return ExprError();
  4285. } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
  4286. Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
  4287. diag::err_typecheck_call_too_many_args)
  4288. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4289. << TheCall->getCallee()->getSourceRange();
  4290. return ExprError();
  4291. }
  4292. // Inspect the first argument of the atomic operation.
  4293. Expr *Ptr = TheCall->getArg(0);
  4294. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  4295. if (ConvertedPtr.isInvalid())
  4296. return ExprError();
  4297. Ptr = ConvertedPtr.get();
  4298. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  4299. if (!pointerType) {
  4300. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4301. << Ptr->getType() << Ptr->getSourceRange();
  4302. return ExprError();
  4303. }
  4304. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  4305. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  4306. QualType ValType = AtomTy; // 'C'
  4307. if (IsC11) {
  4308. if (!AtomTy->isAtomicType()) {
  4309. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
  4310. << Ptr->getType() << Ptr->getSourceRange();
  4311. return ExprError();
  4312. }
  4313. if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
  4314. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  4315. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
  4316. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  4317. << Ptr->getSourceRange();
  4318. return ExprError();
  4319. }
  4320. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  4321. } else if (Form != Load && Form != LoadCopy) {
  4322. if (ValType.isConstQualified()) {
  4323. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
  4324. << Ptr->getType() << Ptr->getSourceRange();
  4325. return ExprError();
  4326. }
  4327. }
  4328. // For an arithmetic operation, the implied arithmetic must be well-formed.
  4329. if (Form == Arithmetic) {
  4330. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  4331. if (IsAddSub && !ValType->isIntegerType()
  4332. && !ValType->isPointerType()) {
  4333. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4334. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4335. return ExprError();
  4336. }
  4337. if (IsMinMax) {
  4338. const BuiltinType *BT = ValType->getAs<BuiltinType>();
  4339. if (!BT || (BT->getKind() != BuiltinType::Int &&
  4340. BT->getKind() != BuiltinType::UInt)) {
  4341. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
  4342. return ExprError();
  4343. }
  4344. }
  4345. if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
  4346. Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
  4347. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4348. return ExprError();
  4349. }
  4350. if (IsC11 && ValType->isPointerType() &&
  4351. RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
  4352. diag::err_incomplete_type)) {
  4353. return ExprError();
  4354. }
  4355. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  4356. // For __atomic_*_n operations, the value type must be a scalar integral or
  4357. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  4358. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4359. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4360. return ExprError();
  4361. }
  4362. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  4363. !AtomTy->isScalarType()) {
  4364. // For GNU atomics, require a trivially-copyable type. This is not part of
  4365. // the GNU atomics specification, but we enforce it for sanity.
  4366. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
  4367. << Ptr->getType() << Ptr->getSourceRange();
  4368. return ExprError();
  4369. }
  4370. switch (ValType.getObjCLifetime()) {
  4371. case Qualifiers::OCL_None:
  4372. case Qualifiers::OCL_ExplicitNone:
  4373. // okay
  4374. break;
  4375. case Qualifiers::OCL_Weak:
  4376. case Qualifiers::OCL_Strong:
  4377. case Qualifiers::OCL_Autoreleasing:
  4378. // FIXME: Can this happen? By this point, ValType should be known
  4379. // to be trivially copyable.
  4380. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4381. << ValType << Ptr->getSourceRange();
  4382. return ExprError();
  4383. }
  4384. // All atomic operations have an overload which takes a pointer to a volatile
  4385. // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
  4386. // into the result or the other operands. Similarly atomic_load takes a
  4387. // pointer to a const 'A'.
  4388. ValType.removeLocalVolatile();
  4389. ValType.removeLocalConst();
  4390. QualType ResultType = ValType;
  4391. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  4392. Form == Init)
  4393. ResultType = Context.VoidTy;
  4394. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  4395. ResultType = Context.BoolTy;
  4396. // The type of a parameter passed 'by value'. In the GNU atomics, such
  4397. // arguments are actually passed as pointers.
  4398. QualType ByValType = ValType; // 'CP'
  4399. bool IsPassedByAddress = false;
  4400. if (!IsC11 && !IsN) {
  4401. ByValType = Ptr->getType();
  4402. IsPassedByAddress = true;
  4403. }
  4404. // The first argument's non-CV pointer type is used to deduce the type of
  4405. // subsequent arguments, except for:
  4406. // - weak flag (always converted to bool)
  4407. // - memory order (always converted to int)
  4408. // - scope (always converted to int)
  4409. for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
  4410. QualType Ty;
  4411. if (i < NumVals[Form] + 1) {
  4412. switch (i) {
  4413. case 0:
  4414. // The first argument is always a pointer. It has a fixed type.
  4415. // It is always dereferenced, a nullptr is undefined.
  4416. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4417. // Nothing else to do: we already know all we want about this pointer.
  4418. continue;
  4419. case 1:
  4420. // The second argument is the non-atomic operand. For arithmetic, this
  4421. // is always passed by value, and for a compare_exchange it is always
  4422. // passed by address. For the rest, GNU uses by-address and C11 uses
  4423. // by-value.
  4424. assert(Form != Load);
  4425. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  4426. Ty = ValType;
  4427. else if (Form == Copy || Form == Xchg) {
  4428. if (IsPassedByAddress)
  4429. // The value pointer is always dereferenced, a nullptr is undefined.
  4430. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4431. Ty = ByValType;
  4432. } else if (Form == Arithmetic)
  4433. Ty = Context.getPointerDiffType();
  4434. else {
  4435. Expr *ValArg = TheCall->getArg(i);
  4436. // The value pointer is always dereferenced, a nullptr is undefined.
  4437. CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
  4438. LangAS AS = LangAS::Default;
  4439. // Keep address space of non-atomic pointer type.
  4440. if (const PointerType *PtrTy =
  4441. ValArg->getType()->getAs<PointerType>()) {
  4442. AS = PtrTy->getPointeeType().getAddressSpace();
  4443. }
  4444. Ty = Context.getPointerType(
  4445. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  4446. }
  4447. break;
  4448. case 2:
  4449. // The third argument to compare_exchange / GNU exchange is the desired
  4450. // value, either by-value (for the C11 and *_n variant) or as a pointer.
  4451. if (IsPassedByAddress)
  4452. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4453. Ty = ByValType;
  4454. break;
  4455. case 3:
  4456. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  4457. Ty = Context.BoolTy;
  4458. break;
  4459. }
  4460. } else {
  4461. // The order(s) and scope are always converted to int.
  4462. Ty = Context.IntTy;
  4463. }
  4464. InitializedEntity Entity =
  4465. InitializedEntity::InitializeParameter(Context, Ty, false);
  4466. ExprResult Arg = TheCall->getArg(i);
  4467. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4468. if (Arg.isInvalid())
  4469. return true;
  4470. TheCall->setArg(i, Arg.get());
  4471. }
  4472. // Permute the arguments into a 'consistent' order.
  4473. SmallVector<Expr*, 5> SubExprs;
  4474. SubExprs.push_back(Ptr);
  4475. switch (Form) {
  4476. case Init:
  4477. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  4478. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4479. break;
  4480. case Load:
  4481. SubExprs.push_back(TheCall->getArg(1)); // Order
  4482. break;
  4483. case LoadCopy:
  4484. case Copy:
  4485. case Arithmetic:
  4486. case Xchg:
  4487. SubExprs.push_back(TheCall->getArg(2)); // Order
  4488. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4489. break;
  4490. case GNUXchg:
  4491. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  4492. SubExprs.push_back(TheCall->getArg(3)); // Order
  4493. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4494. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4495. break;
  4496. case C11CmpXchg:
  4497. SubExprs.push_back(TheCall->getArg(3)); // Order
  4498. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4499. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  4500. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4501. break;
  4502. case GNUCmpXchg:
  4503. SubExprs.push_back(TheCall->getArg(4)); // Order
  4504. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4505. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  4506. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4507. SubExprs.push_back(TheCall->getArg(3)); // Weak
  4508. break;
  4509. }
  4510. if (SubExprs.size() >= 2 && Form != Init) {
  4511. llvm::APSInt Result(32);
  4512. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  4513. !isValidOrderingForOp(Result.getSExtValue(), Op))
  4514. Diag(SubExprs[1]->getBeginLoc(),
  4515. diag::warn_atomic_op_has_invalid_memory_order)
  4516. << SubExprs[1]->getSourceRange();
  4517. }
  4518. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  4519. auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
  4520. llvm::APSInt Result(32);
  4521. if (Scope->isIntegerConstantExpr(Result, Context) &&
  4522. !ScopeModel->isValid(Result.getZExtValue())) {
  4523. Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
  4524. << Scope->getSourceRange();
  4525. }
  4526. SubExprs.push_back(Scope);
  4527. }
  4528. AtomicExpr *AE =
  4529. new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
  4530. ResultType, Op, TheCall->getRParenLoc());
  4531. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  4532. Op == AtomicExpr::AO__c11_atomic_store ||
  4533. Op == AtomicExpr::AO__opencl_atomic_load ||
  4534. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  4535. Context.AtomicUsesUnsupportedLibcall(AE))
  4536. Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
  4537. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  4538. Op == AtomicExpr::AO__opencl_atomic_load)
  4539. ? 0
  4540. : 1);
  4541. return AE;
  4542. }
  4543. /// checkBuiltinArgument - Given a call to a builtin function, perform
  4544. /// normal type-checking on the given argument, updating the call in
  4545. /// place. This is useful when a builtin function requires custom
  4546. /// type-checking for some of its arguments but not necessarily all of
  4547. /// them.
  4548. ///
  4549. /// Returns true on error.
  4550. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  4551. FunctionDecl *Fn = E->getDirectCallee();
  4552. assert(Fn && "builtin call without direct callee!");
  4553. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  4554. InitializedEntity Entity =
  4555. InitializedEntity::InitializeParameter(S.Context, Param);
  4556. ExprResult Arg = E->getArg(0);
  4557. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4558. if (Arg.isInvalid())
  4559. return true;
  4560. E->setArg(ArgIndex, Arg.get());
  4561. return false;
  4562. }
  4563. /// We have a call to a function like __sync_fetch_and_add, which is an
  4564. /// overloaded function based on the pointer type of its first argument.
  4565. /// The main BuildCallExpr routines have already promoted the types of
  4566. /// arguments because all of these calls are prototyped as void(...).
  4567. ///
  4568. /// This function goes through and does final semantic checking for these
  4569. /// builtins, as well as generating any warnings.
  4570. ExprResult
  4571. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  4572. CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
  4573. Expr *Callee = TheCall->getCallee();
  4574. DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
  4575. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4576. // Ensure that we have at least one argument to do type inference from.
  4577. if (TheCall->getNumArgs() < 1) {
  4578. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4579. << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
  4580. return ExprError();
  4581. }
  4582. // Inspect the first argument of the atomic builtin. This should always be
  4583. // a pointer type, whose element is an integral scalar or pointer type.
  4584. // Because it is a pointer type, we don't have to worry about any implicit
  4585. // casts here.
  4586. // FIXME: We don't allow floating point scalars as input.
  4587. Expr *FirstArg = TheCall->getArg(0);
  4588. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  4589. if (FirstArgResult.isInvalid())
  4590. return ExprError();
  4591. FirstArg = FirstArgResult.get();
  4592. TheCall->setArg(0, FirstArg);
  4593. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  4594. if (!pointerType) {
  4595. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4596. << FirstArg->getType() << FirstArg->getSourceRange();
  4597. return ExprError();
  4598. }
  4599. QualType ValType = pointerType->getPointeeType();
  4600. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4601. !ValType->isBlockPointerType()) {
  4602. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
  4603. << FirstArg->getType() << FirstArg->getSourceRange();
  4604. return ExprError();
  4605. }
  4606. if (ValType.isConstQualified()) {
  4607. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
  4608. << FirstArg->getType() << FirstArg->getSourceRange();
  4609. return ExprError();
  4610. }
  4611. switch (ValType.getObjCLifetime()) {
  4612. case Qualifiers::OCL_None:
  4613. case Qualifiers::OCL_ExplicitNone:
  4614. // okay
  4615. break;
  4616. case Qualifiers::OCL_Weak:
  4617. case Qualifiers::OCL_Strong:
  4618. case Qualifiers::OCL_Autoreleasing:
  4619. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4620. << ValType << FirstArg->getSourceRange();
  4621. return ExprError();
  4622. }
  4623. // Strip any qualifiers off ValType.
  4624. ValType = ValType.getUnqualifiedType();
  4625. // The majority of builtins return a value, but a few have special return
  4626. // types, so allow them to override appropriately below.
  4627. QualType ResultType = ValType;
  4628. // We need to figure out which concrete builtin this maps onto. For example,
  4629. // __sync_fetch_and_add with a 2 byte object turns into
  4630. // __sync_fetch_and_add_2.
  4631. #define BUILTIN_ROW(x) \
  4632. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  4633. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  4634. static const unsigned BuiltinIndices[][5] = {
  4635. BUILTIN_ROW(__sync_fetch_and_add),
  4636. BUILTIN_ROW(__sync_fetch_and_sub),
  4637. BUILTIN_ROW(__sync_fetch_and_or),
  4638. BUILTIN_ROW(__sync_fetch_and_and),
  4639. BUILTIN_ROW(__sync_fetch_and_xor),
  4640. BUILTIN_ROW(__sync_fetch_and_nand),
  4641. BUILTIN_ROW(__sync_add_and_fetch),
  4642. BUILTIN_ROW(__sync_sub_and_fetch),
  4643. BUILTIN_ROW(__sync_and_and_fetch),
  4644. BUILTIN_ROW(__sync_or_and_fetch),
  4645. BUILTIN_ROW(__sync_xor_and_fetch),
  4646. BUILTIN_ROW(__sync_nand_and_fetch),
  4647. BUILTIN_ROW(__sync_val_compare_and_swap),
  4648. BUILTIN_ROW(__sync_bool_compare_and_swap),
  4649. BUILTIN_ROW(__sync_lock_test_and_set),
  4650. BUILTIN_ROW(__sync_lock_release),
  4651. BUILTIN_ROW(__sync_swap)
  4652. };
  4653. #undef BUILTIN_ROW
  4654. // Determine the index of the size.
  4655. unsigned SizeIndex;
  4656. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  4657. case 1: SizeIndex = 0; break;
  4658. case 2: SizeIndex = 1; break;
  4659. case 4: SizeIndex = 2; break;
  4660. case 8: SizeIndex = 3; break;
  4661. case 16: SizeIndex = 4; break;
  4662. default:
  4663. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
  4664. << FirstArg->getType() << FirstArg->getSourceRange();
  4665. return ExprError();
  4666. }
  4667. // Each of these builtins has one pointer argument, followed by some number of
  4668. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  4669. // that we ignore. Find out which row of BuiltinIndices to read from as well
  4670. // as the number of fixed args.
  4671. unsigned BuiltinID = FDecl->getBuiltinID();
  4672. unsigned BuiltinIndex, NumFixed = 1;
  4673. bool WarnAboutSemanticsChange = false;
  4674. switch (BuiltinID) {
  4675. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  4676. case Builtin::BI__sync_fetch_and_add:
  4677. case Builtin::BI__sync_fetch_and_add_1:
  4678. case Builtin::BI__sync_fetch_and_add_2:
  4679. case Builtin::BI__sync_fetch_and_add_4:
  4680. case Builtin::BI__sync_fetch_and_add_8:
  4681. case Builtin::BI__sync_fetch_and_add_16:
  4682. BuiltinIndex = 0;
  4683. break;
  4684. case Builtin::BI__sync_fetch_and_sub:
  4685. case Builtin::BI__sync_fetch_and_sub_1:
  4686. case Builtin::BI__sync_fetch_and_sub_2:
  4687. case Builtin::BI__sync_fetch_and_sub_4:
  4688. case Builtin::BI__sync_fetch_and_sub_8:
  4689. case Builtin::BI__sync_fetch_and_sub_16:
  4690. BuiltinIndex = 1;
  4691. break;
  4692. case Builtin::BI__sync_fetch_and_or:
  4693. case Builtin::BI__sync_fetch_and_or_1:
  4694. case Builtin::BI__sync_fetch_and_or_2:
  4695. case Builtin::BI__sync_fetch_and_or_4:
  4696. case Builtin::BI__sync_fetch_and_or_8:
  4697. case Builtin::BI__sync_fetch_and_or_16:
  4698. BuiltinIndex = 2;
  4699. break;
  4700. case Builtin::BI__sync_fetch_and_and:
  4701. case Builtin::BI__sync_fetch_and_and_1:
  4702. case Builtin::BI__sync_fetch_and_and_2:
  4703. case Builtin::BI__sync_fetch_and_and_4:
  4704. case Builtin::BI__sync_fetch_and_and_8:
  4705. case Builtin::BI__sync_fetch_and_and_16:
  4706. BuiltinIndex = 3;
  4707. break;
  4708. case Builtin::BI__sync_fetch_and_xor:
  4709. case Builtin::BI__sync_fetch_and_xor_1:
  4710. case Builtin::BI__sync_fetch_and_xor_2:
  4711. case Builtin::BI__sync_fetch_and_xor_4:
  4712. case Builtin::BI__sync_fetch_and_xor_8:
  4713. case Builtin::BI__sync_fetch_and_xor_16:
  4714. BuiltinIndex = 4;
  4715. break;
  4716. case Builtin::BI__sync_fetch_and_nand:
  4717. case Builtin::BI__sync_fetch_and_nand_1:
  4718. case Builtin::BI__sync_fetch_and_nand_2:
  4719. case Builtin::BI__sync_fetch_and_nand_4:
  4720. case Builtin::BI__sync_fetch_and_nand_8:
  4721. case Builtin::BI__sync_fetch_and_nand_16:
  4722. BuiltinIndex = 5;
  4723. WarnAboutSemanticsChange = true;
  4724. break;
  4725. case Builtin::BI__sync_add_and_fetch:
  4726. case Builtin::BI__sync_add_and_fetch_1:
  4727. case Builtin::BI__sync_add_and_fetch_2:
  4728. case Builtin::BI__sync_add_and_fetch_4:
  4729. case Builtin::BI__sync_add_and_fetch_8:
  4730. case Builtin::BI__sync_add_and_fetch_16:
  4731. BuiltinIndex = 6;
  4732. break;
  4733. case Builtin::BI__sync_sub_and_fetch:
  4734. case Builtin::BI__sync_sub_and_fetch_1:
  4735. case Builtin::BI__sync_sub_and_fetch_2:
  4736. case Builtin::BI__sync_sub_and_fetch_4:
  4737. case Builtin::BI__sync_sub_and_fetch_8:
  4738. case Builtin::BI__sync_sub_and_fetch_16:
  4739. BuiltinIndex = 7;
  4740. break;
  4741. case Builtin::BI__sync_and_and_fetch:
  4742. case Builtin::BI__sync_and_and_fetch_1:
  4743. case Builtin::BI__sync_and_and_fetch_2:
  4744. case Builtin::BI__sync_and_and_fetch_4:
  4745. case Builtin::BI__sync_and_and_fetch_8:
  4746. case Builtin::BI__sync_and_and_fetch_16:
  4747. BuiltinIndex = 8;
  4748. break;
  4749. case Builtin::BI__sync_or_and_fetch:
  4750. case Builtin::BI__sync_or_and_fetch_1:
  4751. case Builtin::BI__sync_or_and_fetch_2:
  4752. case Builtin::BI__sync_or_and_fetch_4:
  4753. case Builtin::BI__sync_or_and_fetch_8:
  4754. case Builtin::BI__sync_or_and_fetch_16:
  4755. BuiltinIndex = 9;
  4756. break;
  4757. case Builtin::BI__sync_xor_and_fetch:
  4758. case Builtin::BI__sync_xor_and_fetch_1:
  4759. case Builtin::BI__sync_xor_and_fetch_2:
  4760. case Builtin::BI__sync_xor_and_fetch_4:
  4761. case Builtin::BI__sync_xor_and_fetch_8:
  4762. case Builtin::BI__sync_xor_and_fetch_16:
  4763. BuiltinIndex = 10;
  4764. break;
  4765. case Builtin::BI__sync_nand_and_fetch:
  4766. case Builtin::BI__sync_nand_and_fetch_1:
  4767. case Builtin::BI__sync_nand_and_fetch_2:
  4768. case Builtin::BI__sync_nand_and_fetch_4:
  4769. case Builtin::BI__sync_nand_and_fetch_8:
  4770. case Builtin::BI__sync_nand_and_fetch_16:
  4771. BuiltinIndex = 11;
  4772. WarnAboutSemanticsChange = true;
  4773. break;
  4774. case Builtin::BI__sync_val_compare_and_swap:
  4775. case Builtin::BI__sync_val_compare_and_swap_1:
  4776. case Builtin::BI__sync_val_compare_and_swap_2:
  4777. case Builtin::BI__sync_val_compare_and_swap_4:
  4778. case Builtin::BI__sync_val_compare_and_swap_8:
  4779. case Builtin::BI__sync_val_compare_and_swap_16:
  4780. BuiltinIndex = 12;
  4781. NumFixed = 2;
  4782. break;
  4783. case Builtin::BI__sync_bool_compare_and_swap:
  4784. case Builtin::BI__sync_bool_compare_and_swap_1:
  4785. case Builtin::BI__sync_bool_compare_and_swap_2:
  4786. case Builtin::BI__sync_bool_compare_and_swap_4:
  4787. case Builtin::BI__sync_bool_compare_and_swap_8:
  4788. case Builtin::BI__sync_bool_compare_and_swap_16:
  4789. BuiltinIndex = 13;
  4790. NumFixed = 2;
  4791. ResultType = Context.BoolTy;
  4792. break;
  4793. case Builtin::BI__sync_lock_test_and_set:
  4794. case Builtin::BI__sync_lock_test_and_set_1:
  4795. case Builtin::BI__sync_lock_test_and_set_2:
  4796. case Builtin::BI__sync_lock_test_and_set_4:
  4797. case Builtin::BI__sync_lock_test_and_set_8:
  4798. case Builtin::BI__sync_lock_test_and_set_16:
  4799. BuiltinIndex = 14;
  4800. break;
  4801. case Builtin::BI__sync_lock_release:
  4802. case Builtin::BI__sync_lock_release_1:
  4803. case Builtin::BI__sync_lock_release_2:
  4804. case Builtin::BI__sync_lock_release_4:
  4805. case Builtin::BI__sync_lock_release_8:
  4806. case Builtin::BI__sync_lock_release_16:
  4807. BuiltinIndex = 15;
  4808. NumFixed = 0;
  4809. ResultType = Context.VoidTy;
  4810. break;
  4811. case Builtin::BI__sync_swap:
  4812. case Builtin::BI__sync_swap_1:
  4813. case Builtin::BI__sync_swap_2:
  4814. case Builtin::BI__sync_swap_4:
  4815. case Builtin::BI__sync_swap_8:
  4816. case Builtin::BI__sync_swap_16:
  4817. BuiltinIndex = 16;
  4818. break;
  4819. }
  4820. // Now that we know how many fixed arguments we expect, first check that we
  4821. // have at least that many.
  4822. if (TheCall->getNumArgs() < 1+NumFixed) {
  4823. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4824. << 0 << 1 + NumFixed << TheCall->getNumArgs()
  4825. << Callee->getSourceRange();
  4826. return ExprError();
  4827. }
  4828. Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
  4829. << Callee->getSourceRange();
  4830. if (WarnAboutSemanticsChange) {
  4831. Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
  4832. << Callee->getSourceRange();
  4833. }
  4834. // Get the decl for the concrete builtin from this, we can tell what the
  4835. // concrete integer type we should convert to is.
  4836. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  4837. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  4838. FunctionDecl *NewBuiltinDecl;
  4839. if (NewBuiltinID == BuiltinID)
  4840. NewBuiltinDecl = FDecl;
  4841. else {
  4842. // Perform builtin lookup to avoid redeclaring it.
  4843. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  4844. LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
  4845. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  4846. assert(Res.getFoundDecl());
  4847. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  4848. if (!NewBuiltinDecl)
  4849. return ExprError();
  4850. }
  4851. // The first argument --- the pointer --- has a fixed type; we
  4852. // deduce the types of the rest of the arguments accordingly. Walk
  4853. // the remaining arguments, converting them to the deduced value type.
  4854. for (unsigned i = 0; i != NumFixed; ++i) {
  4855. ExprResult Arg = TheCall->getArg(i+1);
  4856. // GCC does an implicit conversion to the pointer or integer ValType. This
  4857. // can fail in some cases (1i -> int**), check for this error case now.
  4858. // Initialize the argument.
  4859. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  4860. ValType, /*consume*/ false);
  4861. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4862. if (Arg.isInvalid())
  4863. return ExprError();
  4864. // Okay, we have something that *can* be converted to the right type. Check
  4865. // to see if there is a potentially weird extension going on here. This can
  4866. // happen when you do an atomic operation on something like an char* and
  4867. // pass in 42. The 42 gets converted to char. This is even more strange
  4868. // for things like 45.123 -> char, etc.
  4869. // FIXME: Do this check.
  4870. TheCall->setArg(i+1, Arg.get());
  4871. }
  4872. // Create a new DeclRefExpr to refer to the new decl.
  4873. DeclRefExpr *NewDRE = DeclRefExpr::Create(
  4874. Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
  4875. /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
  4876. DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
  4877. // Set the callee in the CallExpr.
  4878. // FIXME: This loses syntactic information.
  4879. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  4880. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  4881. CK_BuiltinFnToFnPtr);
  4882. TheCall->setCallee(PromotedCall.get());
  4883. // Change the result type of the call to match the original value type. This
  4884. // is arbitrary, but the codegen for these builtins ins design to handle it
  4885. // gracefully.
  4886. TheCall->setType(ResultType);
  4887. return TheCallResult;
  4888. }
  4889. /// SemaBuiltinNontemporalOverloaded - We have a call to
  4890. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  4891. /// overloaded function based on the pointer type of its last argument.
  4892. ///
  4893. /// This function goes through and does final semantic checking for these
  4894. /// builtins.
  4895. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  4896. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  4897. DeclRefExpr *DRE =
  4898. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4899. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4900. unsigned BuiltinID = FDecl->getBuiltinID();
  4901. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  4902. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  4903. "Unexpected nontemporal load/store builtin!");
  4904. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  4905. unsigned numArgs = isStore ? 2 : 1;
  4906. // Ensure that we have the proper number of arguments.
  4907. if (checkArgCount(*this, TheCall, numArgs))
  4908. return ExprError();
  4909. // Inspect the last argument of the nontemporal builtin. This should always
  4910. // be a pointer type, from which we imply the type of the memory access.
  4911. // Because it is a pointer type, we don't have to worry about any implicit
  4912. // casts here.
  4913. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  4914. ExprResult PointerArgResult =
  4915. DefaultFunctionArrayLvalueConversion(PointerArg);
  4916. if (PointerArgResult.isInvalid())
  4917. return ExprError();
  4918. PointerArg = PointerArgResult.get();
  4919. TheCall->setArg(numArgs - 1, PointerArg);
  4920. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  4921. if (!pointerType) {
  4922. Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
  4923. << PointerArg->getType() << PointerArg->getSourceRange();
  4924. return ExprError();
  4925. }
  4926. QualType ValType = pointerType->getPointeeType();
  4927. // Strip any qualifiers off ValType.
  4928. ValType = ValType.getUnqualifiedType();
  4929. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4930. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  4931. !ValType->isVectorType()) {
  4932. Diag(DRE->getBeginLoc(),
  4933. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  4934. << PointerArg->getType() << PointerArg->getSourceRange();
  4935. return ExprError();
  4936. }
  4937. if (!isStore) {
  4938. TheCall->setType(ValType);
  4939. return TheCallResult;
  4940. }
  4941. ExprResult ValArg = TheCall->getArg(0);
  4942. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4943. Context, ValType, /*consume*/ false);
  4944. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  4945. if (ValArg.isInvalid())
  4946. return ExprError();
  4947. TheCall->setArg(0, ValArg.get());
  4948. TheCall->setType(Context.VoidTy);
  4949. return TheCallResult;
  4950. }
  4951. /// CheckObjCString - Checks that the argument to the builtin
  4952. /// CFString constructor is correct
  4953. /// Note: It might also make sense to do the UTF-16 conversion here (would
  4954. /// simplify the backend).
  4955. bool Sema::CheckObjCString(Expr *Arg) {
  4956. Arg = Arg->IgnoreParenCasts();
  4957. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  4958. if (!Literal || !Literal->isAscii()) {
  4959. Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
  4960. << Arg->getSourceRange();
  4961. return true;
  4962. }
  4963. if (Literal->containsNonAsciiOrNull()) {
  4964. StringRef String = Literal->getString();
  4965. unsigned NumBytes = String.size();
  4966. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  4967. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  4968. llvm::UTF16 *ToPtr = &ToBuf[0];
  4969. llvm::ConversionResult Result =
  4970. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  4971. ToPtr + NumBytes, llvm::strictConversion);
  4972. // Check for conversion failure.
  4973. if (Result != llvm::conversionOK)
  4974. Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
  4975. << Arg->getSourceRange();
  4976. }
  4977. return false;
  4978. }
  4979. /// CheckObjCString - Checks that the format string argument to the os_log()
  4980. /// and os_trace() functions is correct, and converts it to const char *.
  4981. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  4982. Arg = Arg->IgnoreParenCasts();
  4983. auto *Literal = dyn_cast<StringLiteral>(Arg);
  4984. if (!Literal) {
  4985. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  4986. Literal = ObjcLiteral->getString();
  4987. }
  4988. }
  4989. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  4990. return ExprError(
  4991. Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
  4992. << Arg->getSourceRange());
  4993. }
  4994. ExprResult Result(Literal);
  4995. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  4996. InitializedEntity Entity =
  4997. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  4998. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  4999. return Result;
  5000. }
  5001. /// Check that the user is calling the appropriate va_start builtin for the
  5002. /// target and calling convention.
  5003. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  5004. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  5005. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  5006. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  5007. bool IsWindows = TT.isOSWindows();
  5008. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  5009. if (IsX64 || IsAArch64) {
  5010. CallingConv CC = CC_C;
  5011. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  5012. CC = FD->getType()->getAs<FunctionType>()->getCallConv();
  5013. if (IsMSVAStart) {
  5014. // Don't allow this in System V ABI functions.
  5015. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  5016. return S.Diag(Fn->getBeginLoc(),
  5017. diag::err_ms_va_start_used_in_sysv_function);
  5018. } else {
  5019. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  5020. // On x64 Windows, don't allow this in System V ABI functions.
  5021. // (Yes, that means there's no corresponding way to support variadic
  5022. // System V ABI functions on Windows.)
  5023. if ((IsWindows && CC == CC_X86_64SysV) ||
  5024. (!IsWindows && CC == CC_Win64))
  5025. return S.Diag(Fn->getBeginLoc(),
  5026. diag::err_va_start_used_in_wrong_abi_function)
  5027. << !IsWindows;
  5028. }
  5029. return false;
  5030. }
  5031. if (IsMSVAStart)
  5032. return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
  5033. return false;
  5034. }
  5035. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  5036. ParmVarDecl **LastParam = nullptr) {
  5037. // Determine whether the current function, block, or obj-c method is variadic
  5038. // and get its parameter list.
  5039. bool IsVariadic = false;
  5040. ArrayRef<ParmVarDecl *> Params;
  5041. DeclContext *Caller = S.CurContext;
  5042. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  5043. IsVariadic = Block->isVariadic();
  5044. Params = Block->parameters();
  5045. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  5046. IsVariadic = FD->isVariadic();
  5047. Params = FD->parameters();
  5048. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  5049. IsVariadic = MD->isVariadic();
  5050. // FIXME: This isn't correct for methods (results in bogus warning).
  5051. Params = MD->parameters();
  5052. } else if (isa<CapturedDecl>(Caller)) {
  5053. // We don't support va_start in a CapturedDecl.
  5054. S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
  5055. return true;
  5056. } else {
  5057. // This must be some other declcontext that parses exprs.
  5058. S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
  5059. return true;
  5060. }
  5061. if (!IsVariadic) {
  5062. S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
  5063. return true;
  5064. }
  5065. if (LastParam)
  5066. *LastParam = Params.empty() ? nullptr : Params.back();
  5067. return false;
  5068. }
  5069. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  5070. /// for validity. Emit an error and return true on failure; return false
  5071. /// on success.
  5072. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  5073. Expr *Fn = TheCall->getCallee();
  5074. if (checkVAStartABI(*this, BuiltinID, Fn))
  5075. return true;
  5076. if (TheCall->getNumArgs() > 2) {
  5077. Diag(TheCall->getArg(2)->getBeginLoc(),
  5078. diag::err_typecheck_call_too_many_args)
  5079. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5080. << Fn->getSourceRange()
  5081. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5082. (*(TheCall->arg_end() - 1))->getEndLoc());
  5083. return true;
  5084. }
  5085. if (TheCall->getNumArgs() < 2) {
  5086. return Diag(TheCall->getEndLoc(),
  5087. diag::err_typecheck_call_too_few_args_at_least)
  5088. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  5089. }
  5090. // Type-check the first argument normally.
  5091. if (checkBuiltinArgument(*this, TheCall, 0))
  5092. return true;
  5093. // Check that the current function is variadic, and get its last parameter.
  5094. ParmVarDecl *LastParam;
  5095. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  5096. return true;
  5097. // Verify that the second argument to the builtin is the last argument of the
  5098. // current function or method.
  5099. bool SecondArgIsLastNamedArgument = false;
  5100. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  5101. // These are valid if SecondArgIsLastNamedArgument is false after the next
  5102. // block.
  5103. QualType Type;
  5104. SourceLocation ParamLoc;
  5105. bool IsCRegister = false;
  5106. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  5107. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  5108. SecondArgIsLastNamedArgument = PV == LastParam;
  5109. Type = PV->getType();
  5110. ParamLoc = PV->getLocation();
  5111. IsCRegister =
  5112. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  5113. }
  5114. }
  5115. if (!SecondArgIsLastNamedArgument)
  5116. Diag(TheCall->getArg(1)->getBeginLoc(),
  5117. diag::warn_second_arg_of_va_start_not_last_named_param);
  5118. else if (IsCRegister || Type->isReferenceType() ||
  5119. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  5120. // Promotable integers are UB, but enumerations need a bit of
  5121. // extra checking to see what their promotable type actually is.
  5122. if (!Type->isPromotableIntegerType())
  5123. return false;
  5124. if (!Type->isEnumeralType())
  5125. return true;
  5126. const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
  5127. return !(ED &&
  5128. Context.typesAreCompatible(ED->getPromotionType(), Type));
  5129. }()) {
  5130. unsigned Reason = 0;
  5131. if (Type->isReferenceType()) Reason = 1;
  5132. else if (IsCRegister) Reason = 2;
  5133. Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
  5134. Diag(ParamLoc, diag::note_parameter_type) << Type;
  5135. }
  5136. TheCall->setType(Context.VoidTy);
  5137. return false;
  5138. }
  5139. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  5140. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  5141. // const char *named_addr);
  5142. Expr *Func = Call->getCallee();
  5143. if (Call->getNumArgs() < 3)
  5144. return Diag(Call->getEndLoc(),
  5145. diag::err_typecheck_call_too_few_args_at_least)
  5146. << 0 /*function call*/ << 3 << Call->getNumArgs();
  5147. // Type-check the first argument normally.
  5148. if (checkBuiltinArgument(*this, Call, 0))
  5149. return true;
  5150. // Check that the current function is variadic.
  5151. if (checkVAStartIsInVariadicFunction(*this, Func))
  5152. return true;
  5153. // __va_start on Windows does not validate the parameter qualifiers
  5154. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  5155. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  5156. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  5157. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  5158. const QualType &ConstCharPtrTy =
  5159. Context.getPointerType(Context.CharTy.withConst());
  5160. if (!Arg1Ty->isPointerType() ||
  5161. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  5162. Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5163. << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
  5164. << 0 /* qualifier difference */
  5165. << 3 /* parameter mismatch */
  5166. << 2 << Arg1->getType() << ConstCharPtrTy;
  5167. const QualType SizeTy = Context.getSizeType();
  5168. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  5169. Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5170. << Arg2->getType() << SizeTy << 1 /* different class */
  5171. << 0 /* qualifier difference */
  5172. << 3 /* parameter mismatch */
  5173. << 3 << Arg2->getType() << SizeTy;
  5174. return false;
  5175. }
  5176. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  5177. /// friends. This is declared to take (...), so we have to check everything.
  5178. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  5179. if (TheCall->getNumArgs() < 2)
  5180. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5181. << 0 << 2 << TheCall->getNumArgs() /*function call*/;
  5182. if (TheCall->getNumArgs() > 2)
  5183. return Diag(TheCall->getArg(2)->getBeginLoc(),
  5184. diag::err_typecheck_call_too_many_args)
  5185. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5186. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5187. (*(TheCall->arg_end() - 1))->getEndLoc());
  5188. ExprResult OrigArg0 = TheCall->getArg(0);
  5189. ExprResult OrigArg1 = TheCall->getArg(1);
  5190. // Do standard promotions between the two arguments, returning their common
  5191. // type.
  5192. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  5193. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  5194. return true;
  5195. // Make sure any conversions are pushed back into the call; this is
  5196. // type safe since unordered compare builtins are declared as "_Bool
  5197. // foo(...)".
  5198. TheCall->setArg(0, OrigArg0.get());
  5199. TheCall->setArg(1, OrigArg1.get());
  5200. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  5201. return false;
  5202. // If the common type isn't a real floating type, then the arguments were
  5203. // invalid for this operation.
  5204. if (Res.isNull() || !Res->isRealFloatingType())
  5205. return Diag(OrigArg0.get()->getBeginLoc(),
  5206. diag::err_typecheck_call_invalid_ordered_compare)
  5207. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  5208. << SourceRange(OrigArg0.get()->getBeginLoc(),
  5209. OrigArg1.get()->getEndLoc());
  5210. return false;
  5211. }
  5212. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  5213. /// __builtin_isnan and friends. This is declared to take (...), so we have
  5214. /// to check everything. We expect the last argument to be a floating point
  5215. /// value.
  5216. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  5217. if (TheCall->getNumArgs() < NumArgs)
  5218. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5219. << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
  5220. if (TheCall->getNumArgs() > NumArgs)
  5221. return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
  5222. diag::err_typecheck_call_too_many_args)
  5223. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  5224. << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
  5225. (*(TheCall->arg_end() - 1))->getEndLoc());
  5226. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  5227. if (OrigArg->isTypeDependent())
  5228. return false;
  5229. // This operation requires a non-_Complex floating-point number.
  5230. if (!OrigArg->getType()->isRealFloatingType())
  5231. return Diag(OrigArg->getBeginLoc(),
  5232. diag::err_typecheck_call_invalid_unary_fp)
  5233. << OrigArg->getType() << OrigArg->getSourceRange();
  5234. // If this is an implicit conversion from float -> float, double, or
  5235. // long double, remove it.
  5236. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  5237. // Only remove standard FloatCasts, leaving other casts inplace
  5238. if (Cast->getCastKind() == CK_FloatingCast) {
  5239. Expr *CastArg = Cast->getSubExpr();
  5240. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  5241. assert(
  5242. (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  5243. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
  5244. Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
  5245. "promotion from float to either float, double, or long double is "
  5246. "the only expected cast here");
  5247. Cast->setSubExpr(nullptr);
  5248. TheCall->setArg(NumArgs-1, CastArg);
  5249. }
  5250. }
  5251. }
  5252. return false;
  5253. }
  5254. // Customized Sema Checking for VSX builtins that have the following signature:
  5255. // vector [...] builtinName(vector [...], vector [...], const int);
  5256. // Which takes the same type of vectors (any legal vector type) for the first
  5257. // two arguments and takes compile time constant for the third argument.
  5258. // Example builtins are :
  5259. // vector double vec_xxpermdi(vector double, vector double, int);
  5260. // vector short vec_xxsldwi(vector short, vector short, int);
  5261. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  5262. unsigned ExpectedNumArgs = 3;
  5263. if (TheCall->getNumArgs() < ExpectedNumArgs)
  5264. return Diag(TheCall->getEndLoc(),
  5265. diag::err_typecheck_call_too_few_args_at_least)
  5266. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5267. << TheCall->getSourceRange();
  5268. if (TheCall->getNumArgs() > ExpectedNumArgs)
  5269. return Diag(TheCall->getEndLoc(),
  5270. diag::err_typecheck_call_too_many_args_at_most)
  5271. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5272. << TheCall->getSourceRange();
  5273. // Check the third argument is a compile time constant
  5274. llvm::APSInt Value;
  5275. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  5276. return Diag(TheCall->getBeginLoc(),
  5277. diag::err_vsx_builtin_nonconstant_argument)
  5278. << 3 /* argument index */ << TheCall->getDirectCallee()
  5279. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5280. TheCall->getArg(2)->getEndLoc());
  5281. QualType Arg1Ty = TheCall->getArg(0)->getType();
  5282. QualType Arg2Ty = TheCall->getArg(1)->getType();
  5283. // Check the type of argument 1 and argument 2 are vectors.
  5284. SourceLocation BuiltinLoc = TheCall->getBeginLoc();
  5285. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  5286. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  5287. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  5288. << TheCall->getDirectCallee()
  5289. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5290. TheCall->getArg(1)->getEndLoc());
  5291. }
  5292. // Check the first two arguments are the same type.
  5293. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  5294. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  5295. << TheCall->getDirectCallee()
  5296. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5297. TheCall->getArg(1)->getEndLoc());
  5298. }
  5299. // When default clang type checking is turned off and the customized type
  5300. // checking is used, the returning type of the function must be explicitly
  5301. // set. Otherwise it is _Bool by default.
  5302. TheCall->setType(Arg1Ty);
  5303. return false;
  5304. }
  5305. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  5306. // This is declared to take (...), so we have to check everything.
  5307. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  5308. if (TheCall->getNumArgs() < 2)
  5309. return ExprError(Diag(TheCall->getEndLoc(),
  5310. diag::err_typecheck_call_too_few_args_at_least)
  5311. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5312. << TheCall->getSourceRange());
  5313. // Determine which of the following types of shufflevector we're checking:
  5314. // 1) unary, vector mask: (lhs, mask)
  5315. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  5316. QualType resType = TheCall->getArg(0)->getType();
  5317. unsigned numElements = 0;
  5318. if (!TheCall->getArg(0)->isTypeDependent() &&
  5319. !TheCall->getArg(1)->isTypeDependent()) {
  5320. QualType LHSType = TheCall->getArg(0)->getType();
  5321. QualType RHSType = TheCall->getArg(1)->getType();
  5322. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  5323. return ExprError(
  5324. Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
  5325. << TheCall->getDirectCallee()
  5326. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5327. TheCall->getArg(1)->getEndLoc()));
  5328. numElements = LHSType->getAs<VectorType>()->getNumElements();
  5329. unsigned numResElements = TheCall->getNumArgs() - 2;
  5330. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  5331. // with mask. If so, verify that RHS is an integer vector type with the
  5332. // same number of elts as lhs.
  5333. if (TheCall->getNumArgs() == 2) {
  5334. if (!RHSType->hasIntegerRepresentation() ||
  5335. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  5336. return ExprError(Diag(TheCall->getBeginLoc(),
  5337. diag::err_vec_builtin_incompatible_vector)
  5338. << TheCall->getDirectCallee()
  5339. << SourceRange(TheCall->getArg(1)->getBeginLoc(),
  5340. TheCall->getArg(1)->getEndLoc()));
  5341. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  5342. return ExprError(Diag(TheCall->getBeginLoc(),
  5343. diag::err_vec_builtin_incompatible_vector)
  5344. << TheCall->getDirectCallee()
  5345. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5346. TheCall->getArg(1)->getEndLoc()));
  5347. } else if (numElements != numResElements) {
  5348. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  5349. resType = Context.getVectorType(eltType, numResElements,
  5350. VectorType::GenericVector);
  5351. }
  5352. }
  5353. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  5354. if (TheCall->getArg(i)->isTypeDependent() ||
  5355. TheCall->getArg(i)->isValueDependent())
  5356. continue;
  5357. llvm::APSInt Result(32);
  5358. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  5359. return ExprError(Diag(TheCall->getBeginLoc(),
  5360. diag::err_shufflevector_nonconstant_argument)
  5361. << TheCall->getArg(i)->getSourceRange());
  5362. // Allow -1 which will be translated to undef in the IR.
  5363. if (Result.isSigned() && Result.isAllOnesValue())
  5364. continue;
  5365. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  5366. return ExprError(Diag(TheCall->getBeginLoc(),
  5367. diag::err_shufflevector_argument_too_large)
  5368. << TheCall->getArg(i)->getSourceRange());
  5369. }
  5370. SmallVector<Expr*, 32> exprs;
  5371. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  5372. exprs.push_back(TheCall->getArg(i));
  5373. TheCall->setArg(i, nullptr);
  5374. }
  5375. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  5376. TheCall->getCallee()->getBeginLoc(),
  5377. TheCall->getRParenLoc());
  5378. }
  5379. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  5380. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  5381. SourceLocation BuiltinLoc,
  5382. SourceLocation RParenLoc) {
  5383. ExprValueKind VK = VK_RValue;
  5384. ExprObjectKind OK = OK_Ordinary;
  5385. QualType DstTy = TInfo->getType();
  5386. QualType SrcTy = E->getType();
  5387. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  5388. return ExprError(Diag(BuiltinLoc,
  5389. diag::err_convertvector_non_vector)
  5390. << E->getSourceRange());
  5391. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  5392. return ExprError(Diag(BuiltinLoc,
  5393. diag::err_convertvector_non_vector_type));
  5394. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  5395. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  5396. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  5397. if (SrcElts != DstElts)
  5398. return ExprError(Diag(BuiltinLoc,
  5399. diag::err_convertvector_incompatible_vector)
  5400. << E->getSourceRange());
  5401. }
  5402. return new (Context)
  5403. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5404. }
  5405. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  5406. // This is declared to take (const void*, ...) and can take two
  5407. // optional constant int args.
  5408. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  5409. unsigned NumArgs = TheCall->getNumArgs();
  5410. if (NumArgs > 3)
  5411. return Diag(TheCall->getEndLoc(),
  5412. diag::err_typecheck_call_too_many_args_at_most)
  5413. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5414. // Argument 0 is checked for us and the remaining arguments must be
  5415. // constant integers.
  5416. for (unsigned i = 1; i != NumArgs; ++i)
  5417. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  5418. return true;
  5419. return false;
  5420. }
  5421. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  5422. // __assume does not evaluate its arguments, and should warn if its argument
  5423. // has side effects.
  5424. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  5425. Expr *Arg = TheCall->getArg(0);
  5426. if (Arg->isInstantiationDependent()) return false;
  5427. if (Arg->HasSideEffects(Context))
  5428. Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
  5429. << Arg->getSourceRange()
  5430. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  5431. return false;
  5432. }
  5433. /// Handle __builtin_alloca_with_align. This is declared
  5434. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  5435. /// than 8.
  5436. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  5437. // The alignment must be a constant integer.
  5438. Expr *Arg = TheCall->getArg(1);
  5439. // We can't check the value of a dependent argument.
  5440. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5441. if (const auto *UE =
  5442. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  5443. if (UE->getKind() == UETT_AlignOf ||
  5444. UE->getKind() == UETT_PreferredAlignOf)
  5445. Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
  5446. << Arg->getSourceRange();
  5447. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  5448. if (!Result.isPowerOf2())
  5449. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5450. << Arg->getSourceRange();
  5451. if (Result < Context.getCharWidth())
  5452. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
  5453. << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
  5454. if (Result > std::numeric_limits<int32_t>::max())
  5455. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
  5456. << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
  5457. }
  5458. return false;
  5459. }
  5460. /// Handle __builtin_assume_aligned. This is declared
  5461. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  5462. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  5463. unsigned NumArgs = TheCall->getNumArgs();
  5464. if (NumArgs > 3)
  5465. return Diag(TheCall->getEndLoc(),
  5466. diag::err_typecheck_call_too_many_args_at_most)
  5467. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5468. // The alignment must be a constant integer.
  5469. Expr *Arg = TheCall->getArg(1);
  5470. // We can't check the value of a dependent argument.
  5471. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5472. llvm::APSInt Result;
  5473. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5474. return true;
  5475. if (!Result.isPowerOf2())
  5476. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5477. << Arg->getSourceRange();
  5478. }
  5479. if (NumArgs > 2) {
  5480. ExprResult Arg(TheCall->getArg(2));
  5481. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  5482. Context.getSizeType(), false);
  5483. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5484. if (Arg.isInvalid()) return true;
  5485. TheCall->setArg(2, Arg.get());
  5486. }
  5487. return false;
  5488. }
  5489. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  5490. unsigned BuiltinID =
  5491. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  5492. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  5493. unsigned NumArgs = TheCall->getNumArgs();
  5494. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  5495. if (NumArgs < NumRequiredArgs) {
  5496. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5497. << 0 /* function call */ << NumRequiredArgs << NumArgs
  5498. << TheCall->getSourceRange();
  5499. }
  5500. if (NumArgs >= NumRequiredArgs + 0x100) {
  5501. return Diag(TheCall->getEndLoc(),
  5502. diag::err_typecheck_call_too_many_args_at_most)
  5503. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  5504. << TheCall->getSourceRange();
  5505. }
  5506. unsigned i = 0;
  5507. // For formatting call, check buffer arg.
  5508. if (!IsSizeCall) {
  5509. ExprResult Arg(TheCall->getArg(i));
  5510. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5511. Context, Context.VoidPtrTy, false);
  5512. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5513. if (Arg.isInvalid())
  5514. return true;
  5515. TheCall->setArg(i, Arg.get());
  5516. i++;
  5517. }
  5518. // Check string literal arg.
  5519. unsigned FormatIdx = i;
  5520. {
  5521. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  5522. if (Arg.isInvalid())
  5523. return true;
  5524. TheCall->setArg(i, Arg.get());
  5525. i++;
  5526. }
  5527. // Make sure variadic args are scalar.
  5528. unsigned FirstDataArg = i;
  5529. while (i < NumArgs) {
  5530. ExprResult Arg = DefaultVariadicArgumentPromotion(
  5531. TheCall->getArg(i), VariadicFunction, nullptr);
  5532. if (Arg.isInvalid())
  5533. return true;
  5534. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  5535. if (ArgSize.getQuantity() >= 0x100) {
  5536. return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
  5537. << i << (int)ArgSize.getQuantity() << 0xff
  5538. << TheCall->getSourceRange();
  5539. }
  5540. TheCall->setArg(i, Arg.get());
  5541. i++;
  5542. }
  5543. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  5544. // call to avoid duplicate diagnostics.
  5545. if (!IsSizeCall) {
  5546. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  5547. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  5548. bool Success = CheckFormatArguments(
  5549. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  5550. VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
  5551. CheckedVarArgs);
  5552. if (!Success)
  5553. return true;
  5554. }
  5555. if (IsSizeCall) {
  5556. TheCall->setType(Context.getSizeType());
  5557. } else {
  5558. TheCall->setType(Context.VoidPtrTy);
  5559. }
  5560. return false;
  5561. }
  5562. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  5563. /// TheCall is a constant expression.
  5564. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  5565. llvm::APSInt &Result) {
  5566. Expr *Arg = TheCall->getArg(ArgNum);
  5567. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5568. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  5569. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  5570. if (!Arg->isIntegerConstantExpr(Result, Context))
  5571. return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
  5572. << FDecl->getDeclName() << Arg->getSourceRange();
  5573. return false;
  5574. }
  5575. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  5576. /// TheCall is a constant expression in the range [Low, High].
  5577. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  5578. int Low, int High, bool RangeIsError) {
  5579. if (isConstantEvaluated())
  5580. return false;
  5581. llvm::APSInt Result;
  5582. // We can't check the value of a dependent argument.
  5583. Expr *Arg = TheCall->getArg(ArgNum);
  5584. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5585. return false;
  5586. // Check constant-ness first.
  5587. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5588. return true;
  5589. if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
  5590. if (RangeIsError)
  5591. return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
  5592. << Result.toString(10) << Low << High << Arg->getSourceRange();
  5593. else
  5594. // Defer the warning until we know if the code will be emitted so that
  5595. // dead code can ignore this.
  5596. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  5597. PDiag(diag::warn_argument_invalid_range)
  5598. << Result.toString(10) << Low << High
  5599. << Arg->getSourceRange());
  5600. }
  5601. return false;
  5602. }
  5603. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  5604. /// TheCall is a constant expression is a multiple of Num..
  5605. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  5606. unsigned Num) {
  5607. llvm::APSInt Result;
  5608. // We can't check the value of a dependent argument.
  5609. Expr *Arg = TheCall->getArg(ArgNum);
  5610. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5611. return false;
  5612. // Check constant-ness first.
  5613. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5614. return true;
  5615. if (Result.getSExtValue() % Num != 0)
  5616. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
  5617. << Num << Arg->getSourceRange();
  5618. return false;
  5619. }
  5620. /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
  5621. bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
  5622. if (BuiltinID == AArch64::BI__builtin_arm_irg) {
  5623. if (checkArgCount(*this, TheCall, 2))
  5624. return true;
  5625. Expr *Arg0 = TheCall->getArg(0);
  5626. Expr *Arg1 = TheCall->getArg(1);
  5627. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5628. if (FirstArg.isInvalid())
  5629. return true;
  5630. QualType FirstArgType = FirstArg.get()->getType();
  5631. if (!FirstArgType->isAnyPointerType())
  5632. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5633. << "first" << FirstArgType << Arg0->getSourceRange();
  5634. TheCall->setArg(0, FirstArg.get());
  5635. ExprResult SecArg = DefaultLvalueConversion(Arg1);
  5636. if (SecArg.isInvalid())
  5637. return true;
  5638. QualType SecArgType = SecArg.get()->getType();
  5639. if (!SecArgType->isIntegerType())
  5640. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5641. << "second" << SecArgType << Arg1->getSourceRange();
  5642. // Derive the return type from the pointer argument.
  5643. TheCall->setType(FirstArgType);
  5644. return false;
  5645. }
  5646. if (BuiltinID == AArch64::BI__builtin_arm_addg) {
  5647. if (checkArgCount(*this, TheCall, 2))
  5648. return true;
  5649. Expr *Arg0 = TheCall->getArg(0);
  5650. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5651. if (FirstArg.isInvalid())
  5652. return true;
  5653. QualType FirstArgType = FirstArg.get()->getType();
  5654. if (!FirstArgType->isAnyPointerType())
  5655. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5656. << "first" << FirstArgType << Arg0->getSourceRange();
  5657. TheCall->setArg(0, FirstArg.get());
  5658. // Derive the return type from the pointer argument.
  5659. TheCall->setType(FirstArgType);
  5660. // Second arg must be an constant in range [0,15]
  5661. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5662. }
  5663. if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
  5664. if (checkArgCount(*this, TheCall, 2))
  5665. return true;
  5666. Expr *Arg0 = TheCall->getArg(0);
  5667. Expr *Arg1 = TheCall->getArg(1);
  5668. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5669. if (FirstArg.isInvalid())
  5670. return true;
  5671. QualType FirstArgType = FirstArg.get()->getType();
  5672. if (!FirstArgType->isAnyPointerType())
  5673. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5674. << "first" << FirstArgType << Arg0->getSourceRange();
  5675. QualType SecArgType = Arg1->getType();
  5676. if (!SecArgType->isIntegerType())
  5677. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5678. << "second" << SecArgType << Arg1->getSourceRange();
  5679. TheCall->setType(Context.IntTy);
  5680. return false;
  5681. }
  5682. if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
  5683. BuiltinID == AArch64::BI__builtin_arm_stg) {
  5684. if (checkArgCount(*this, TheCall, 1))
  5685. return true;
  5686. Expr *Arg0 = TheCall->getArg(0);
  5687. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5688. if (FirstArg.isInvalid())
  5689. return true;
  5690. QualType FirstArgType = FirstArg.get()->getType();
  5691. if (!FirstArgType->isAnyPointerType())
  5692. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5693. << "first" << FirstArgType << Arg0->getSourceRange();
  5694. TheCall->setArg(0, FirstArg.get());
  5695. // Derive the return type from the pointer argument.
  5696. if (BuiltinID == AArch64::BI__builtin_arm_ldg)
  5697. TheCall->setType(FirstArgType);
  5698. return false;
  5699. }
  5700. if (BuiltinID == AArch64::BI__builtin_arm_subp) {
  5701. Expr *ArgA = TheCall->getArg(0);
  5702. Expr *ArgB = TheCall->getArg(1);
  5703. ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
  5704. ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
  5705. if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
  5706. return true;
  5707. QualType ArgTypeA = ArgExprA.get()->getType();
  5708. QualType ArgTypeB = ArgExprB.get()->getType();
  5709. auto isNull = [&] (Expr *E) -> bool {
  5710. return E->isNullPointerConstant(
  5711. Context, Expr::NPC_ValueDependentIsNotNull); };
  5712. // argument should be either a pointer or null
  5713. if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
  5714. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5715. << "first" << ArgTypeA << ArgA->getSourceRange();
  5716. if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
  5717. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5718. << "second" << ArgTypeB << ArgB->getSourceRange();
  5719. // Ensure Pointee types are compatible
  5720. if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
  5721. ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
  5722. QualType pointeeA = ArgTypeA->getPointeeType();
  5723. QualType pointeeB = ArgTypeB->getPointeeType();
  5724. if (!Context.typesAreCompatible(
  5725. Context.getCanonicalType(pointeeA).getUnqualifiedType(),
  5726. Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
  5727. return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
  5728. << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
  5729. << ArgB->getSourceRange();
  5730. }
  5731. }
  5732. // at least one argument should be pointer type
  5733. if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
  5734. return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
  5735. << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
  5736. if (isNull(ArgA)) // adopt type of the other pointer
  5737. ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
  5738. if (isNull(ArgB))
  5739. ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
  5740. TheCall->setArg(0, ArgExprA.get());
  5741. TheCall->setArg(1, ArgExprB.get());
  5742. TheCall->setType(Context.LongLongTy);
  5743. return false;
  5744. }
  5745. assert(false && "Unhandled ARM MTE intrinsic");
  5746. return true;
  5747. }
  5748. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  5749. /// TheCall is an ARM/AArch64 special register string literal.
  5750. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  5751. int ArgNum, unsigned ExpectedFieldNum,
  5752. bool AllowName) {
  5753. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  5754. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  5755. BuiltinID == ARM::BI__builtin_arm_rsr ||
  5756. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  5757. BuiltinID == ARM::BI__builtin_arm_wsr ||
  5758. BuiltinID == ARM::BI__builtin_arm_wsrp;
  5759. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  5760. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  5761. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  5762. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  5763. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  5764. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  5765. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  5766. // We can't check the value of a dependent argument.
  5767. Expr *Arg = TheCall->getArg(ArgNum);
  5768. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5769. return false;
  5770. // Check if the argument is a string literal.
  5771. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  5772. return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  5773. << Arg->getSourceRange();
  5774. // Check the type of special register given.
  5775. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  5776. SmallVector<StringRef, 6> Fields;
  5777. Reg.split(Fields, ":");
  5778. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  5779. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5780. << Arg->getSourceRange();
  5781. // If the string is the name of a register then we cannot check that it is
  5782. // valid here but if the string is of one the forms described in ACLE then we
  5783. // can check that the supplied fields are integers and within the valid
  5784. // ranges.
  5785. if (Fields.size() > 1) {
  5786. bool FiveFields = Fields.size() == 5;
  5787. bool ValidString = true;
  5788. if (IsARMBuiltin) {
  5789. ValidString &= Fields[0].startswith_lower("cp") ||
  5790. Fields[0].startswith_lower("p");
  5791. if (ValidString)
  5792. Fields[0] =
  5793. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  5794. ValidString &= Fields[2].startswith_lower("c");
  5795. if (ValidString)
  5796. Fields[2] = Fields[2].drop_front(1);
  5797. if (FiveFields) {
  5798. ValidString &= Fields[3].startswith_lower("c");
  5799. if (ValidString)
  5800. Fields[3] = Fields[3].drop_front(1);
  5801. }
  5802. }
  5803. SmallVector<int, 5> Ranges;
  5804. if (FiveFields)
  5805. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  5806. else
  5807. Ranges.append({15, 7, 15});
  5808. for (unsigned i=0; i<Fields.size(); ++i) {
  5809. int IntField;
  5810. ValidString &= !Fields[i].getAsInteger(10, IntField);
  5811. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  5812. }
  5813. if (!ValidString)
  5814. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5815. << Arg->getSourceRange();
  5816. } else if (IsAArch64Builtin && Fields.size() == 1) {
  5817. // If the register name is one of those that appear in the condition below
  5818. // and the special register builtin being used is one of the write builtins,
  5819. // then we require that the argument provided for writing to the register
  5820. // is an integer constant expression. This is because it will be lowered to
  5821. // an MSR (immediate) instruction, so we need to know the immediate at
  5822. // compile time.
  5823. if (TheCall->getNumArgs() != 2)
  5824. return false;
  5825. std::string RegLower = Reg.lower();
  5826. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  5827. RegLower != "pan" && RegLower != "uao")
  5828. return false;
  5829. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5830. }
  5831. return false;
  5832. }
  5833. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  5834. /// This checks that the target supports __builtin_longjmp and
  5835. /// that val is a constant 1.
  5836. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  5837. if (!Context.getTargetInfo().hasSjLjLowering())
  5838. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
  5839. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5840. Expr *Arg = TheCall->getArg(1);
  5841. llvm::APSInt Result;
  5842. // TODO: This is less than ideal. Overload this to take a value.
  5843. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5844. return true;
  5845. if (Result != 1)
  5846. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
  5847. << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
  5848. return false;
  5849. }
  5850. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  5851. /// This checks that the target supports __builtin_setjmp.
  5852. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  5853. if (!Context.getTargetInfo().hasSjLjLowering())
  5854. return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
  5855. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5856. return false;
  5857. }
  5858. namespace {
  5859. class UncoveredArgHandler {
  5860. enum { Unknown = -1, AllCovered = -2 };
  5861. signed FirstUncoveredArg = Unknown;
  5862. SmallVector<const Expr *, 4> DiagnosticExprs;
  5863. public:
  5864. UncoveredArgHandler() = default;
  5865. bool hasUncoveredArg() const {
  5866. return (FirstUncoveredArg >= 0);
  5867. }
  5868. unsigned getUncoveredArg() const {
  5869. assert(hasUncoveredArg() && "no uncovered argument");
  5870. return FirstUncoveredArg;
  5871. }
  5872. void setAllCovered() {
  5873. // A string has been found with all arguments covered, so clear out
  5874. // the diagnostics.
  5875. DiagnosticExprs.clear();
  5876. FirstUncoveredArg = AllCovered;
  5877. }
  5878. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  5879. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  5880. // Don't update if a previous string covers all arguments.
  5881. if (FirstUncoveredArg == AllCovered)
  5882. return;
  5883. // UncoveredArgHandler tracks the highest uncovered argument index
  5884. // and with it all the strings that match this index.
  5885. if (NewFirstUncoveredArg == FirstUncoveredArg)
  5886. DiagnosticExprs.push_back(StrExpr);
  5887. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  5888. DiagnosticExprs.clear();
  5889. DiagnosticExprs.push_back(StrExpr);
  5890. FirstUncoveredArg = NewFirstUncoveredArg;
  5891. }
  5892. }
  5893. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  5894. };
  5895. enum StringLiteralCheckType {
  5896. SLCT_NotALiteral,
  5897. SLCT_UncheckedLiteral,
  5898. SLCT_CheckedLiteral
  5899. };
  5900. } // namespace
  5901. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  5902. BinaryOperatorKind BinOpKind,
  5903. bool AddendIsRight) {
  5904. unsigned BitWidth = Offset.getBitWidth();
  5905. unsigned AddendBitWidth = Addend.getBitWidth();
  5906. // There might be negative interim results.
  5907. if (Addend.isUnsigned()) {
  5908. Addend = Addend.zext(++AddendBitWidth);
  5909. Addend.setIsSigned(true);
  5910. }
  5911. // Adjust the bit width of the APSInts.
  5912. if (AddendBitWidth > BitWidth) {
  5913. Offset = Offset.sext(AddendBitWidth);
  5914. BitWidth = AddendBitWidth;
  5915. } else if (BitWidth > AddendBitWidth) {
  5916. Addend = Addend.sext(BitWidth);
  5917. }
  5918. bool Ov = false;
  5919. llvm::APSInt ResOffset = Offset;
  5920. if (BinOpKind == BO_Add)
  5921. ResOffset = Offset.sadd_ov(Addend, Ov);
  5922. else {
  5923. assert(AddendIsRight && BinOpKind == BO_Sub &&
  5924. "operator must be add or sub with addend on the right");
  5925. ResOffset = Offset.ssub_ov(Addend, Ov);
  5926. }
  5927. // We add an offset to a pointer here so we should support an offset as big as
  5928. // possible.
  5929. if (Ov) {
  5930. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  5931. "index (intermediate) result too big");
  5932. Offset = Offset.sext(2 * BitWidth);
  5933. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  5934. return;
  5935. }
  5936. Offset = ResOffset;
  5937. }
  5938. namespace {
  5939. // This is a wrapper class around StringLiteral to support offsetted string
  5940. // literals as format strings. It takes the offset into account when returning
  5941. // the string and its length or the source locations to display notes correctly.
  5942. class FormatStringLiteral {
  5943. const StringLiteral *FExpr;
  5944. int64_t Offset;
  5945. public:
  5946. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  5947. : FExpr(fexpr), Offset(Offset) {}
  5948. StringRef getString() const {
  5949. return FExpr->getString().drop_front(Offset);
  5950. }
  5951. unsigned getByteLength() const {
  5952. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  5953. }
  5954. unsigned getLength() const { return FExpr->getLength() - Offset; }
  5955. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  5956. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  5957. QualType getType() const { return FExpr->getType(); }
  5958. bool isAscii() const { return FExpr->isAscii(); }
  5959. bool isWide() const { return FExpr->isWide(); }
  5960. bool isUTF8() const { return FExpr->isUTF8(); }
  5961. bool isUTF16() const { return FExpr->isUTF16(); }
  5962. bool isUTF32() const { return FExpr->isUTF32(); }
  5963. bool isPascal() const { return FExpr->isPascal(); }
  5964. SourceLocation getLocationOfByte(
  5965. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  5966. const TargetInfo &Target, unsigned *StartToken = nullptr,
  5967. unsigned *StartTokenByteOffset = nullptr) const {
  5968. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  5969. StartToken, StartTokenByteOffset);
  5970. }
  5971. SourceLocation getBeginLoc() const LLVM_READONLY {
  5972. return FExpr->getBeginLoc().getLocWithOffset(Offset);
  5973. }
  5974. SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
  5975. };
  5976. } // namespace
  5977. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  5978. const Expr *OrigFormatExpr,
  5979. ArrayRef<const Expr *> Args,
  5980. bool HasVAListArg, unsigned format_idx,
  5981. unsigned firstDataArg,
  5982. Sema::FormatStringType Type,
  5983. bool inFunctionCall,
  5984. Sema::VariadicCallType CallType,
  5985. llvm::SmallBitVector &CheckedVarArgs,
  5986. UncoveredArgHandler &UncoveredArg);
  5987. // Determine if an expression is a string literal or constant string.
  5988. // If this function returns false on the arguments to a function expecting a
  5989. // format string, we will usually need to emit a warning.
  5990. // True string literals are then checked by CheckFormatString.
  5991. static StringLiteralCheckType
  5992. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  5993. bool HasVAListArg, unsigned format_idx,
  5994. unsigned firstDataArg, Sema::FormatStringType Type,
  5995. Sema::VariadicCallType CallType, bool InFunctionCall,
  5996. llvm::SmallBitVector &CheckedVarArgs,
  5997. UncoveredArgHandler &UncoveredArg,
  5998. llvm::APSInt Offset) {
  5999. if (S.isConstantEvaluated())
  6000. return SLCT_NotALiteral;
  6001. tryAgain:
  6002. assert(Offset.isSigned() && "invalid offset");
  6003. if (E->isTypeDependent() || E->isValueDependent())
  6004. return SLCT_NotALiteral;
  6005. E = E->IgnoreParenCasts();
  6006. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  6007. // Technically -Wformat-nonliteral does not warn about this case.
  6008. // The behavior of printf and friends in this case is implementation
  6009. // dependent. Ideally if the format string cannot be null then
  6010. // it should have a 'nonnull' attribute in the function prototype.
  6011. return SLCT_UncheckedLiteral;
  6012. switch (E->getStmtClass()) {
  6013. case Stmt::BinaryConditionalOperatorClass:
  6014. case Stmt::ConditionalOperatorClass: {
  6015. // The expression is a literal if both sub-expressions were, and it was
  6016. // completely checked only if both sub-expressions were checked.
  6017. const AbstractConditionalOperator *C =
  6018. cast<AbstractConditionalOperator>(E);
  6019. // Determine whether it is necessary to check both sub-expressions, for
  6020. // example, because the condition expression is a constant that can be
  6021. // evaluated at compile time.
  6022. bool CheckLeft = true, CheckRight = true;
  6023. bool Cond;
  6024. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
  6025. S.isConstantEvaluated())) {
  6026. if (Cond)
  6027. CheckRight = false;
  6028. else
  6029. CheckLeft = false;
  6030. }
  6031. // We need to maintain the offsets for the right and the left hand side
  6032. // separately to check if every possible indexed expression is a valid
  6033. // string literal. They might have different offsets for different string
  6034. // literals in the end.
  6035. StringLiteralCheckType Left;
  6036. if (!CheckLeft)
  6037. Left = SLCT_UncheckedLiteral;
  6038. else {
  6039. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  6040. HasVAListArg, format_idx, firstDataArg,
  6041. Type, CallType, InFunctionCall,
  6042. CheckedVarArgs, UncoveredArg, Offset);
  6043. if (Left == SLCT_NotALiteral || !CheckRight) {
  6044. return Left;
  6045. }
  6046. }
  6047. StringLiteralCheckType Right =
  6048. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  6049. HasVAListArg, format_idx, firstDataArg,
  6050. Type, CallType, InFunctionCall, CheckedVarArgs,
  6051. UncoveredArg, Offset);
  6052. return (CheckLeft && Left < Right) ? Left : Right;
  6053. }
  6054. case Stmt::ImplicitCastExprClass:
  6055. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  6056. goto tryAgain;
  6057. case Stmt::OpaqueValueExprClass:
  6058. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  6059. E = src;
  6060. goto tryAgain;
  6061. }
  6062. return SLCT_NotALiteral;
  6063. case Stmt::PredefinedExprClass:
  6064. // While __func__, etc., are technically not string literals, they
  6065. // cannot contain format specifiers and thus are not a security
  6066. // liability.
  6067. return SLCT_UncheckedLiteral;
  6068. case Stmt::DeclRefExprClass: {
  6069. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  6070. // As an exception, do not flag errors for variables binding to
  6071. // const string literals.
  6072. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  6073. bool isConstant = false;
  6074. QualType T = DR->getType();
  6075. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  6076. isConstant = AT->getElementType().isConstant(S.Context);
  6077. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  6078. isConstant = T.isConstant(S.Context) &&
  6079. PT->getPointeeType().isConstant(S.Context);
  6080. } else if (T->isObjCObjectPointerType()) {
  6081. // In ObjC, there is usually no "const ObjectPointer" type,
  6082. // so don't check if the pointee type is constant.
  6083. isConstant = T.isConstant(S.Context);
  6084. }
  6085. if (isConstant) {
  6086. if (const Expr *Init = VD->getAnyInitializer()) {
  6087. // Look through initializers like const char c[] = { "foo" }
  6088. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  6089. if (InitList->isStringLiteralInit())
  6090. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  6091. }
  6092. return checkFormatStringExpr(S, Init, Args,
  6093. HasVAListArg, format_idx,
  6094. firstDataArg, Type, CallType,
  6095. /*InFunctionCall*/ false, CheckedVarArgs,
  6096. UncoveredArg, Offset);
  6097. }
  6098. }
  6099. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  6100. // special check to see if the format string is a function parameter
  6101. // of the function calling the printf function. If the function
  6102. // has an attribute indicating it is a printf-like function, then we
  6103. // should suppress warnings concerning non-literals being used in a call
  6104. // to a vprintf function. For example:
  6105. //
  6106. // void
  6107. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  6108. // va_list ap;
  6109. // va_start(ap, fmt);
  6110. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  6111. // ...
  6112. // }
  6113. if (HasVAListArg) {
  6114. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  6115. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  6116. int PVIndex = PV->getFunctionScopeIndex() + 1;
  6117. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  6118. // adjust for implicit parameter
  6119. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  6120. if (MD->isInstance())
  6121. ++PVIndex;
  6122. // We also check if the formats are compatible.
  6123. // We can't pass a 'scanf' string to a 'printf' function.
  6124. if (PVIndex == PVFormat->getFormatIdx() &&
  6125. Type == S.GetFormatStringType(PVFormat))
  6126. return SLCT_UncheckedLiteral;
  6127. }
  6128. }
  6129. }
  6130. }
  6131. }
  6132. return SLCT_NotALiteral;
  6133. }
  6134. case Stmt::CallExprClass:
  6135. case Stmt::CXXMemberCallExprClass: {
  6136. const CallExpr *CE = cast<CallExpr>(E);
  6137. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  6138. bool IsFirst = true;
  6139. StringLiteralCheckType CommonResult;
  6140. for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
  6141. const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
  6142. StringLiteralCheckType Result = checkFormatStringExpr(
  6143. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6144. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  6145. if (IsFirst) {
  6146. CommonResult = Result;
  6147. IsFirst = false;
  6148. }
  6149. }
  6150. if (!IsFirst)
  6151. return CommonResult;
  6152. if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
  6153. unsigned BuiltinID = FD->getBuiltinID();
  6154. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  6155. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  6156. const Expr *Arg = CE->getArg(0);
  6157. return checkFormatStringExpr(S, Arg, Args,
  6158. HasVAListArg, format_idx,
  6159. firstDataArg, Type, CallType,
  6160. InFunctionCall, CheckedVarArgs,
  6161. UncoveredArg, Offset);
  6162. }
  6163. }
  6164. }
  6165. return SLCT_NotALiteral;
  6166. }
  6167. case Stmt::ObjCMessageExprClass: {
  6168. const auto *ME = cast<ObjCMessageExpr>(E);
  6169. if (const auto *ND = ME->getMethodDecl()) {
  6170. if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
  6171. const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
  6172. return checkFormatStringExpr(
  6173. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6174. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  6175. }
  6176. }
  6177. return SLCT_NotALiteral;
  6178. }
  6179. case Stmt::ObjCStringLiteralClass:
  6180. case Stmt::StringLiteralClass: {
  6181. const StringLiteral *StrE = nullptr;
  6182. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  6183. StrE = ObjCFExpr->getString();
  6184. else
  6185. StrE = cast<StringLiteral>(E);
  6186. if (StrE) {
  6187. if (Offset.isNegative() || Offset > StrE->getLength()) {
  6188. // TODO: It would be better to have an explicit warning for out of
  6189. // bounds literals.
  6190. return SLCT_NotALiteral;
  6191. }
  6192. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  6193. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  6194. firstDataArg, Type, InFunctionCall, CallType,
  6195. CheckedVarArgs, UncoveredArg);
  6196. return SLCT_CheckedLiteral;
  6197. }
  6198. return SLCT_NotALiteral;
  6199. }
  6200. case Stmt::BinaryOperatorClass: {
  6201. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  6202. // A string literal + an int offset is still a string literal.
  6203. if (BinOp->isAdditiveOp()) {
  6204. Expr::EvalResult LResult, RResult;
  6205. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
  6206. LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  6207. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
  6208. RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  6209. if (LIsInt != RIsInt) {
  6210. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  6211. if (LIsInt) {
  6212. if (BinOpKind == BO_Add) {
  6213. sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
  6214. E = BinOp->getRHS();
  6215. goto tryAgain;
  6216. }
  6217. } else {
  6218. sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
  6219. E = BinOp->getLHS();
  6220. goto tryAgain;
  6221. }
  6222. }
  6223. }
  6224. return SLCT_NotALiteral;
  6225. }
  6226. case Stmt::UnaryOperatorClass: {
  6227. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  6228. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  6229. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  6230. Expr::EvalResult IndexResult;
  6231. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
  6232. Expr::SE_NoSideEffects,
  6233. S.isConstantEvaluated())) {
  6234. sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
  6235. /*RHS is int*/ true);
  6236. E = ASE->getBase();
  6237. goto tryAgain;
  6238. }
  6239. }
  6240. return SLCT_NotALiteral;
  6241. }
  6242. default:
  6243. return SLCT_NotALiteral;
  6244. }
  6245. }
  6246. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  6247. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  6248. .Case("scanf", FST_Scanf)
  6249. .Cases("printf", "printf0", FST_Printf)
  6250. .Cases("NSString", "CFString", FST_NSString)
  6251. .Case("strftime", FST_Strftime)
  6252. .Case("strfmon", FST_Strfmon)
  6253. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  6254. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  6255. .Case("os_trace", FST_OSLog)
  6256. .Case("os_log", FST_OSLog)
  6257. .Default(FST_Unknown);
  6258. }
  6259. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  6260. /// functions) for correct use of format strings.
  6261. /// Returns true if a format string has been fully checked.
  6262. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  6263. ArrayRef<const Expr *> Args,
  6264. bool IsCXXMember,
  6265. VariadicCallType CallType,
  6266. SourceLocation Loc, SourceRange Range,
  6267. llvm::SmallBitVector &CheckedVarArgs) {
  6268. FormatStringInfo FSI;
  6269. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  6270. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  6271. FSI.FirstDataArg, GetFormatStringType(Format),
  6272. CallType, Loc, Range, CheckedVarArgs);
  6273. return false;
  6274. }
  6275. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  6276. bool HasVAListArg, unsigned format_idx,
  6277. unsigned firstDataArg, FormatStringType Type,
  6278. VariadicCallType CallType,
  6279. SourceLocation Loc, SourceRange Range,
  6280. llvm::SmallBitVector &CheckedVarArgs) {
  6281. // CHECK: printf/scanf-like function is called with no format string.
  6282. if (format_idx >= Args.size()) {
  6283. Diag(Loc, diag::warn_missing_format_string) << Range;
  6284. return false;
  6285. }
  6286. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  6287. // CHECK: format string is not a string literal.
  6288. //
  6289. // Dynamically generated format strings are difficult to
  6290. // automatically vet at compile time. Requiring that format strings
  6291. // are string literals: (1) permits the checking of format strings by
  6292. // the compiler and thereby (2) can practically remove the source of
  6293. // many format string exploits.
  6294. // Format string can be either ObjC string (e.g. @"%d") or
  6295. // C string (e.g. "%d")
  6296. // ObjC string uses the same format specifiers as C string, so we can use
  6297. // the same format string checking logic for both ObjC and C strings.
  6298. UncoveredArgHandler UncoveredArg;
  6299. StringLiteralCheckType CT =
  6300. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  6301. format_idx, firstDataArg, Type, CallType,
  6302. /*IsFunctionCall*/ true, CheckedVarArgs,
  6303. UncoveredArg,
  6304. /*no string offset*/ llvm::APSInt(64, false) = 0);
  6305. // Generate a diagnostic where an uncovered argument is detected.
  6306. if (UncoveredArg.hasUncoveredArg()) {
  6307. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  6308. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  6309. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  6310. }
  6311. if (CT != SLCT_NotALiteral)
  6312. // Literal format string found, check done!
  6313. return CT == SLCT_CheckedLiteral;
  6314. // Strftime is particular as it always uses a single 'time' argument,
  6315. // so it is safe to pass a non-literal string.
  6316. if (Type == FST_Strftime)
  6317. return false;
  6318. // Do not emit diag when the string param is a macro expansion and the
  6319. // format is either NSString or CFString. This is a hack to prevent
  6320. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  6321. // which are usually used in place of NS and CF string literals.
  6322. SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
  6323. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  6324. return false;
  6325. // If there are no arguments specified, warn with -Wformat-security, otherwise
  6326. // warn only with -Wformat-nonliteral.
  6327. if (Args.size() == firstDataArg) {
  6328. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  6329. << OrigFormatExpr->getSourceRange();
  6330. switch (Type) {
  6331. default:
  6332. break;
  6333. case FST_Kprintf:
  6334. case FST_FreeBSDKPrintf:
  6335. case FST_Printf:
  6336. Diag(FormatLoc, diag::note_format_security_fixit)
  6337. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  6338. break;
  6339. case FST_NSString:
  6340. Diag(FormatLoc, diag::note_format_security_fixit)
  6341. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  6342. break;
  6343. }
  6344. } else {
  6345. Diag(FormatLoc, diag::warn_format_nonliteral)
  6346. << OrigFormatExpr->getSourceRange();
  6347. }
  6348. return false;
  6349. }
  6350. namespace {
  6351. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  6352. protected:
  6353. Sema &S;
  6354. const FormatStringLiteral *FExpr;
  6355. const Expr *OrigFormatExpr;
  6356. const Sema::FormatStringType FSType;
  6357. const unsigned FirstDataArg;
  6358. const unsigned NumDataArgs;
  6359. const char *Beg; // Start of format string.
  6360. const bool HasVAListArg;
  6361. ArrayRef<const Expr *> Args;
  6362. unsigned FormatIdx;
  6363. llvm::SmallBitVector CoveredArgs;
  6364. bool usesPositionalArgs = false;
  6365. bool atFirstArg = true;
  6366. bool inFunctionCall;
  6367. Sema::VariadicCallType CallType;
  6368. llvm::SmallBitVector &CheckedVarArgs;
  6369. UncoveredArgHandler &UncoveredArg;
  6370. public:
  6371. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  6372. const Expr *origFormatExpr,
  6373. const Sema::FormatStringType type, unsigned firstDataArg,
  6374. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  6375. ArrayRef<const Expr *> Args, unsigned formatIdx,
  6376. bool inFunctionCall, Sema::VariadicCallType callType,
  6377. llvm::SmallBitVector &CheckedVarArgs,
  6378. UncoveredArgHandler &UncoveredArg)
  6379. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  6380. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  6381. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  6382. inFunctionCall(inFunctionCall), CallType(callType),
  6383. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  6384. CoveredArgs.resize(numDataArgs);
  6385. CoveredArgs.reset();
  6386. }
  6387. void DoneProcessing();
  6388. void HandleIncompleteSpecifier(const char *startSpecifier,
  6389. unsigned specifierLen) override;
  6390. void HandleInvalidLengthModifier(
  6391. const analyze_format_string::FormatSpecifier &FS,
  6392. const analyze_format_string::ConversionSpecifier &CS,
  6393. const char *startSpecifier, unsigned specifierLen,
  6394. unsigned DiagID);
  6395. void HandleNonStandardLengthModifier(
  6396. const analyze_format_string::FormatSpecifier &FS,
  6397. const char *startSpecifier, unsigned specifierLen);
  6398. void HandleNonStandardConversionSpecifier(
  6399. const analyze_format_string::ConversionSpecifier &CS,
  6400. const char *startSpecifier, unsigned specifierLen);
  6401. void HandlePosition(const char *startPos, unsigned posLen) override;
  6402. void HandleInvalidPosition(const char *startSpecifier,
  6403. unsigned specifierLen,
  6404. analyze_format_string::PositionContext p) override;
  6405. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  6406. void HandleNullChar(const char *nullCharacter) override;
  6407. template <typename Range>
  6408. static void
  6409. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  6410. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  6411. bool IsStringLocation, Range StringRange,
  6412. ArrayRef<FixItHint> Fixit = None);
  6413. protected:
  6414. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  6415. const char *startSpec,
  6416. unsigned specifierLen,
  6417. const char *csStart, unsigned csLen);
  6418. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6419. const char *startSpec,
  6420. unsigned specifierLen);
  6421. SourceRange getFormatStringRange();
  6422. CharSourceRange getSpecifierRange(const char *startSpecifier,
  6423. unsigned specifierLen);
  6424. SourceLocation getLocationOfByte(const char *x);
  6425. const Expr *getDataArg(unsigned i) const;
  6426. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  6427. const analyze_format_string::ConversionSpecifier &CS,
  6428. const char *startSpecifier, unsigned specifierLen,
  6429. unsigned argIndex);
  6430. template <typename Range>
  6431. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  6432. bool IsStringLocation, Range StringRange,
  6433. ArrayRef<FixItHint> Fixit = None);
  6434. };
  6435. } // namespace
  6436. SourceRange CheckFormatHandler::getFormatStringRange() {
  6437. return OrigFormatExpr->getSourceRange();
  6438. }
  6439. CharSourceRange CheckFormatHandler::
  6440. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  6441. SourceLocation Start = getLocationOfByte(startSpecifier);
  6442. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  6443. // Advance the end SourceLocation by one due to half-open ranges.
  6444. End = End.getLocWithOffset(1);
  6445. return CharSourceRange::getCharRange(Start, End);
  6446. }
  6447. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  6448. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  6449. S.getLangOpts(), S.Context.getTargetInfo());
  6450. }
  6451. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  6452. unsigned specifierLen){
  6453. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  6454. getLocationOfByte(startSpecifier),
  6455. /*IsStringLocation*/true,
  6456. getSpecifierRange(startSpecifier, specifierLen));
  6457. }
  6458. void CheckFormatHandler::HandleInvalidLengthModifier(
  6459. const analyze_format_string::FormatSpecifier &FS,
  6460. const analyze_format_string::ConversionSpecifier &CS,
  6461. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  6462. using namespace analyze_format_string;
  6463. const LengthModifier &LM = FS.getLengthModifier();
  6464. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6465. // See if we know how to fix this length modifier.
  6466. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6467. if (FixedLM) {
  6468. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6469. getLocationOfByte(LM.getStart()),
  6470. /*IsStringLocation*/true,
  6471. getSpecifierRange(startSpecifier, specifierLen));
  6472. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6473. << FixedLM->toString()
  6474. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6475. } else {
  6476. FixItHint Hint;
  6477. if (DiagID == diag::warn_format_nonsensical_length)
  6478. Hint = FixItHint::CreateRemoval(LMRange);
  6479. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6480. getLocationOfByte(LM.getStart()),
  6481. /*IsStringLocation*/true,
  6482. getSpecifierRange(startSpecifier, specifierLen),
  6483. Hint);
  6484. }
  6485. }
  6486. void CheckFormatHandler::HandleNonStandardLengthModifier(
  6487. const analyze_format_string::FormatSpecifier &FS,
  6488. const char *startSpecifier, unsigned specifierLen) {
  6489. using namespace analyze_format_string;
  6490. const LengthModifier &LM = FS.getLengthModifier();
  6491. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6492. // See if we know how to fix this length modifier.
  6493. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6494. if (FixedLM) {
  6495. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6496. << LM.toString() << 0,
  6497. getLocationOfByte(LM.getStart()),
  6498. /*IsStringLocation*/true,
  6499. getSpecifierRange(startSpecifier, specifierLen));
  6500. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6501. << FixedLM->toString()
  6502. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6503. } else {
  6504. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6505. << LM.toString() << 0,
  6506. getLocationOfByte(LM.getStart()),
  6507. /*IsStringLocation*/true,
  6508. getSpecifierRange(startSpecifier, specifierLen));
  6509. }
  6510. }
  6511. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  6512. const analyze_format_string::ConversionSpecifier &CS,
  6513. const char *startSpecifier, unsigned specifierLen) {
  6514. using namespace analyze_format_string;
  6515. // See if we know how to fix this conversion specifier.
  6516. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  6517. if (FixedCS) {
  6518. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6519. << CS.toString() << /*conversion specifier*/1,
  6520. getLocationOfByte(CS.getStart()),
  6521. /*IsStringLocation*/true,
  6522. getSpecifierRange(startSpecifier, specifierLen));
  6523. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  6524. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  6525. << FixedCS->toString()
  6526. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  6527. } else {
  6528. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6529. << CS.toString() << /*conversion specifier*/1,
  6530. getLocationOfByte(CS.getStart()),
  6531. /*IsStringLocation*/true,
  6532. getSpecifierRange(startSpecifier, specifierLen));
  6533. }
  6534. }
  6535. void CheckFormatHandler::HandlePosition(const char *startPos,
  6536. unsigned posLen) {
  6537. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  6538. getLocationOfByte(startPos),
  6539. /*IsStringLocation*/true,
  6540. getSpecifierRange(startPos, posLen));
  6541. }
  6542. void
  6543. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  6544. analyze_format_string::PositionContext p) {
  6545. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  6546. << (unsigned) p,
  6547. getLocationOfByte(startPos), /*IsStringLocation*/true,
  6548. getSpecifierRange(startPos, posLen));
  6549. }
  6550. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  6551. unsigned posLen) {
  6552. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  6553. getLocationOfByte(startPos),
  6554. /*IsStringLocation*/true,
  6555. getSpecifierRange(startPos, posLen));
  6556. }
  6557. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  6558. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  6559. // The presence of a null character is likely an error.
  6560. EmitFormatDiagnostic(
  6561. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  6562. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  6563. getFormatStringRange());
  6564. }
  6565. }
  6566. // Note that this may return NULL if there was an error parsing or building
  6567. // one of the argument expressions.
  6568. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  6569. return Args[FirstDataArg + i];
  6570. }
  6571. void CheckFormatHandler::DoneProcessing() {
  6572. // Does the number of data arguments exceed the number of
  6573. // format conversions in the format string?
  6574. if (!HasVAListArg) {
  6575. // Find any arguments that weren't covered.
  6576. CoveredArgs.flip();
  6577. signed notCoveredArg = CoveredArgs.find_first();
  6578. if (notCoveredArg >= 0) {
  6579. assert((unsigned)notCoveredArg < NumDataArgs);
  6580. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  6581. } else {
  6582. UncoveredArg.setAllCovered();
  6583. }
  6584. }
  6585. }
  6586. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  6587. const Expr *ArgExpr) {
  6588. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  6589. "Invalid state");
  6590. if (!ArgExpr)
  6591. return;
  6592. SourceLocation Loc = ArgExpr->getBeginLoc();
  6593. if (S.getSourceManager().isInSystemMacro(Loc))
  6594. return;
  6595. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  6596. for (auto E : DiagnosticExprs)
  6597. PDiag << E->getSourceRange();
  6598. CheckFormatHandler::EmitFormatDiagnostic(
  6599. S, IsFunctionCall, DiagnosticExprs[0],
  6600. PDiag, Loc, /*IsStringLocation*/false,
  6601. DiagnosticExprs[0]->getSourceRange());
  6602. }
  6603. bool
  6604. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  6605. SourceLocation Loc,
  6606. const char *startSpec,
  6607. unsigned specifierLen,
  6608. const char *csStart,
  6609. unsigned csLen) {
  6610. bool keepGoing = true;
  6611. if (argIndex < NumDataArgs) {
  6612. // Consider the argument coverered, even though the specifier doesn't
  6613. // make sense.
  6614. CoveredArgs.set(argIndex);
  6615. }
  6616. else {
  6617. // If argIndex exceeds the number of data arguments we
  6618. // don't issue a warning because that is just a cascade of warnings (and
  6619. // they may have intended '%%' anyway). We don't want to continue processing
  6620. // the format string after this point, however, as we will like just get
  6621. // gibberish when trying to match arguments.
  6622. keepGoing = false;
  6623. }
  6624. StringRef Specifier(csStart, csLen);
  6625. // If the specifier in non-printable, it could be the first byte of a UTF-8
  6626. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  6627. // hex value.
  6628. std::string CodePointStr;
  6629. if (!llvm::sys::locale::isPrint(*csStart)) {
  6630. llvm::UTF32 CodePoint;
  6631. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  6632. const llvm::UTF8 *E =
  6633. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  6634. llvm::ConversionResult Result =
  6635. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  6636. if (Result != llvm::conversionOK) {
  6637. unsigned char FirstChar = *csStart;
  6638. CodePoint = (llvm::UTF32)FirstChar;
  6639. }
  6640. llvm::raw_string_ostream OS(CodePointStr);
  6641. if (CodePoint < 256)
  6642. OS << "\\x" << llvm::format("%02x", CodePoint);
  6643. else if (CodePoint <= 0xFFFF)
  6644. OS << "\\u" << llvm::format("%04x", CodePoint);
  6645. else
  6646. OS << "\\U" << llvm::format("%08x", CodePoint);
  6647. OS.flush();
  6648. Specifier = CodePointStr;
  6649. }
  6650. EmitFormatDiagnostic(
  6651. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  6652. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  6653. return keepGoing;
  6654. }
  6655. void
  6656. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6657. const char *startSpec,
  6658. unsigned specifierLen) {
  6659. EmitFormatDiagnostic(
  6660. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  6661. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  6662. }
  6663. bool
  6664. CheckFormatHandler::CheckNumArgs(
  6665. const analyze_format_string::FormatSpecifier &FS,
  6666. const analyze_format_string::ConversionSpecifier &CS,
  6667. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  6668. if (argIndex >= NumDataArgs) {
  6669. PartialDiagnostic PDiag = FS.usesPositionalArg()
  6670. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  6671. << (argIndex+1) << NumDataArgs)
  6672. : S.PDiag(diag::warn_printf_insufficient_data_args);
  6673. EmitFormatDiagnostic(
  6674. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  6675. getSpecifierRange(startSpecifier, specifierLen));
  6676. // Since more arguments than conversion tokens are given, by extension
  6677. // all arguments are covered, so mark this as so.
  6678. UncoveredArg.setAllCovered();
  6679. return false;
  6680. }
  6681. return true;
  6682. }
  6683. template<typename Range>
  6684. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  6685. SourceLocation Loc,
  6686. bool IsStringLocation,
  6687. Range StringRange,
  6688. ArrayRef<FixItHint> FixIt) {
  6689. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  6690. Loc, IsStringLocation, StringRange, FixIt);
  6691. }
  6692. /// If the format string is not within the function call, emit a note
  6693. /// so that the function call and string are in diagnostic messages.
  6694. ///
  6695. /// \param InFunctionCall if true, the format string is within the function
  6696. /// call and only one diagnostic message will be produced. Otherwise, an
  6697. /// extra note will be emitted pointing to location of the format string.
  6698. ///
  6699. /// \param ArgumentExpr the expression that is passed as the format string
  6700. /// argument in the function call. Used for getting locations when two
  6701. /// diagnostics are emitted.
  6702. ///
  6703. /// \param PDiag the callee should already have provided any strings for the
  6704. /// diagnostic message. This function only adds locations and fixits
  6705. /// to diagnostics.
  6706. ///
  6707. /// \param Loc primary location for diagnostic. If two diagnostics are
  6708. /// required, one will be at Loc and a new SourceLocation will be created for
  6709. /// the other one.
  6710. ///
  6711. /// \param IsStringLocation if true, Loc points to the format string should be
  6712. /// used for the note. Otherwise, Loc points to the argument list and will
  6713. /// be used with PDiag.
  6714. ///
  6715. /// \param StringRange some or all of the string to highlight. This is
  6716. /// templated so it can accept either a CharSourceRange or a SourceRange.
  6717. ///
  6718. /// \param FixIt optional fix it hint for the format string.
  6719. template <typename Range>
  6720. void CheckFormatHandler::EmitFormatDiagnostic(
  6721. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  6722. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  6723. Range StringRange, ArrayRef<FixItHint> FixIt) {
  6724. if (InFunctionCall) {
  6725. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  6726. D << StringRange;
  6727. D << FixIt;
  6728. } else {
  6729. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  6730. << ArgumentExpr->getSourceRange();
  6731. const Sema::SemaDiagnosticBuilder &Note =
  6732. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  6733. diag::note_format_string_defined);
  6734. Note << StringRange;
  6735. Note << FixIt;
  6736. }
  6737. }
  6738. //===--- CHECK: Printf format string checking ------------------------------===//
  6739. namespace {
  6740. class CheckPrintfHandler : public CheckFormatHandler {
  6741. public:
  6742. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  6743. const Expr *origFormatExpr,
  6744. const Sema::FormatStringType type, unsigned firstDataArg,
  6745. unsigned numDataArgs, bool isObjC, const char *beg,
  6746. bool hasVAListArg, ArrayRef<const Expr *> Args,
  6747. unsigned formatIdx, bool inFunctionCall,
  6748. Sema::VariadicCallType CallType,
  6749. llvm::SmallBitVector &CheckedVarArgs,
  6750. UncoveredArgHandler &UncoveredArg)
  6751. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  6752. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  6753. inFunctionCall, CallType, CheckedVarArgs,
  6754. UncoveredArg) {}
  6755. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  6756. /// Returns true if '%@' specifiers are allowed in the format string.
  6757. bool allowsObjCArg() const {
  6758. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  6759. FSType == Sema::FST_OSTrace;
  6760. }
  6761. bool HandleInvalidPrintfConversionSpecifier(
  6762. const analyze_printf::PrintfSpecifier &FS,
  6763. const char *startSpecifier,
  6764. unsigned specifierLen) override;
  6765. void handleInvalidMaskType(StringRef MaskType) override;
  6766. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  6767. const char *startSpecifier,
  6768. unsigned specifierLen) override;
  6769. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  6770. const char *StartSpecifier,
  6771. unsigned SpecifierLen,
  6772. const Expr *E);
  6773. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  6774. const char *startSpecifier, unsigned specifierLen);
  6775. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  6776. const analyze_printf::OptionalAmount &Amt,
  6777. unsigned type,
  6778. const char *startSpecifier, unsigned specifierLen);
  6779. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6780. const analyze_printf::OptionalFlag &flag,
  6781. const char *startSpecifier, unsigned specifierLen);
  6782. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  6783. const analyze_printf::OptionalFlag &ignoredFlag,
  6784. const analyze_printf::OptionalFlag &flag,
  6785. const char *startSpecifier, unsigned specifierLen);
  6786. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  6787. const Expr *E);
  6788. void HandleEmptyObjCModifierFlag(const char *startFlag,
  6789. unsigned flagLen) override;
  6790. void HandleInvalidObjCModifierFlag(const char *startFlag,
  6791. unsigned flagLen) override;
  6792. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  6793. const char *flagsEnd,
  6794. const char *conversionPosition)
  6795. override;
  6796. };
  6797. } // namespace
  6798. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  6799. const analyze_printf::PrintfSpecifier &FS,
  6800. const char *startSpecifier,
  6801. unsigned specifierLen) {
  6802. const analyze_printf::PrintfConversionSpecifier &CS =
  6803. FS.getConversionSpecifier();
  6804. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  6805. getLocationOfByte(CS.getStart()),
  6806. startSpecifier, specifierLen,
  6807. CS.getStart(), CS.getLength());
  6808. }
  6809. void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
  6810. S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
  6811. }
  6812. bool CheckPrintfHandler::HandleAmount(
  6813. const analyze_format_string::OptionalAmount &Amt,
  6814. unsigned k, const char *startSpecifier,
  6815. unsigned specifierLen) {
  6816. if (Amt.hasDataArgument()) {
  6817. if (!HasVAListArg) {
  6818. unsigned argIndex = Amt.getArgIndex();
  6819. if (argIndex >= NumDataArgs) {
  6820. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  6821. << k,
  6822. getLocationOfByte(Amt.getStart()),
  6823. /*IsStringLocation*/true,
  6824. getSpecifierRange(startSpecifier, specifierLen));
  6825. // Don't do any more checking. We will just emit
  6826. // spurious errors.
  6827. return false;
  6828. }
  6829. // Type check the data argument. It should be an 'int'.
  6830. // Although not in conformance with C99, we also allow the argument to be
  6831. // an 'unsigned int' as that is a reasonably safe case. GCC also
  6832. // doesn't emit a warning for that case.
  6833. CoveredArgs.set(argIndex);
  6834. const Expr *Arg = getDataArg(argIndex);
  6835. if (!Arg)
  6836. return false;
  6837. QualType T = Arg->getType();
  6838. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  6839. assert(AT.isValid());
  6840. if (!AT.matchesType(S.Context, T)) {
  6841. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  6842. << k << AT.getRepresentativeTypeName(S.Context)
  6843. << T << Arg->getSourceRange(),
  6844. getLocationOfByte(Amt.getStart()),
  6845. /*IsStringLocation*/true,
  6846. getSpecifierRange(startSpecifier, specifierLen));
  6847. // Don't do any more checking. We will just emit
  6848. // spurious errors.
  6849. return false;
  6850. }
  6851. }
  6852. }
  6853. return true;
  6854. }
  6855. void CheckPrintfHandler::HandleInvalidAmount(
  6856. const analyze_printf::PrintfSpecifier &FS,
  6857. const analyze_printf::OptionalAmount &Amt,
  6858. unsigned type,
  6859. const char *startSpecifier,
  6860. unsigned specifierLen) {
  6861. const analyze_printf::PrintfConversionSpecifier &CS =
  6862. FS.getConversionSpecifier();
  6863. FixItHint fixit =
  6864. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  6865. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  6866. Amt.getConstantLength()))
  6867. : FixItHint();
  6868. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  6869. << type << CS.toString(),
  6870. getLocationOfByte(Amt.getStart()),
  6871. /*IsStringLocation*/true,
  6872. getSpecifierRange(startSpecifier, specifierLen),
  6873. fixit);
  6874. }
  6875. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6876. const analyze_printf::OptionalFlag &flag,
  6877. const char *startSpecifier,
  6878. unsigned specifierLen) {
  6879. // Warn about pointless flag with a fixit removal.
  6880. const analyze_printf::PrintfConversionSpecifier &CS =
  6881. FS.getConversionSpecifier();
  6882. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  6883. << flag.toString() << CS.toString(),
  6884. getLocationOfByte(flag.getPosition()),
  6885. /*IsStringLocation*/true,
  6886. getSpecifierRange(startSpecifier, specifierLen),
  6887. FixItHint::CreateRemoval(
  6888. getSpecifierRange(flag.getPosition(), 1)));
  6889. }
  6890. void CheckPrintfHandler::HandleIgnoredFlag(
  6891. const analyze_printf::PrintfSpecifier &FS,
  6892. const analyze_printf::OptionalFlag &ignoredFlag,
  6893. const analyze_printf::OptionalFlag &flag,
  6894. const char *startSpecifier,
  6895. unsigned specifierLen) {
  6896. // Warn about ignored flag with a fixit removal.
  6897. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  6898. << ignoredFlag.toString() << flag.toString(),
  6899. getLocationOfByte(ignoredFlag.getPosition()),
  6900. /*IsStringLocation*/true,
  6901. getSpecifierRange(startSpecifier, specifierLen),
  6902. FixItHint::CreateRemoval(
  6903. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  6904. }
  6905. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  6906. unsigned flagLen) {
  6907. // Warn about an empty flag.
  6908. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  6909. getLocationOfByte(startFlag),
  6910. /*IsStringLocation*/true,
  6911. getSpecifierRange(startFlag, flagLen));
  6912. }
  6913. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  6914. unsigned flagLen) {
  6915. // Warn about an invalid flag.
  6916. auto Range = getSpecifierRange(startFlag, flagLen);
  6917. StringRef flag(startFlag, flagLen);
  6918. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  6919. getLocationOfByte(startFlag),
  6920. /*IsStringLocation*/true,
  6921. Range, FixItHint::CreateRemoval(Range));
  6922. }
  6923. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  6924. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  6925. // Warn about using '[...]' without a '@' conversion.
  6926. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  6927. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  6928. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  6929. getLocationOfByte(conversionPosition),
  6930. /*IsStringLocation*/true,
  6931. Range, FixItHint::CreateRemoval(Range));
  6932. }
  6933. // Determines if the specified is a C++ class or struct containing
  6934. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  6935. // "c_str()").
  6936. template<typename MemberKind>
  6937. static llvm::SmallPtrSet<MemberKind*, 1>
  6938. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  6939. const RecordType *RT = Ty->getAs<RecordType>();
  6940. llvm::SmallPtrSet<MemberKind*, 1> Results;
  6941. if (!RT)
  6942. return Results;
  6943. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  6944. if (!RD || !RD->getDefinition())
  6945. return Results;
  6946. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  6947. Sema::LookupMemberName);
  6948. R.suppressDiagnostics();
  6949. // We just need to include all members of the right kind turned up by the
  6950. // filter, at this point.
  6951. if (S.LookupQualifiedName(R, RT->getDecl()))
  6952. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  6953. NamedDecl *decl = (*I)->getUnderlyingDecl();
  6954. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  6955. Results.insert(FK);
  6956. }
  6957. return Results;
  6958. }
  6959. /// Check if we could call '.c_str()' on an object.
  6960. ///
  6961. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  6962. /// allow the call, or if it would be ambiguous).
  6963. bool Sema::hasCStrMethod(const Expr *E) {
  6964. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6965. MethodSet Results =
  6966. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  6967. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6968. MI != ME; ++MI)
  6969. if ((*MI)->getMinRequiredArguments() == 0)
  6970. return true;
  6971. return false;
  6972. }
  6973. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  6974. // better diagnostic if so. AT is assumed to be valid.
  6975. // Returns true when a c_str() conversion method is found.
  6976. bool CheckPrintfHandler::checkForCStrMembers(
  6977. const analyze_printf::ArgType &AT, const Expr *E) {
  6978. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6979. MethodSet Results =
  6980. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  6981. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6982. MI != ME; ++MI) {
  6983. const CXXMethodDecl *Method = *MI;
  6984. if (Method->getMinRequiredArguments() == 0 &&
  6985. AT.matchesType(S.Context, Method->getReturnType())) {
  6986. // FIXME: Suggest parens if the expression needs them.
  6987. SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
  6988. S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
  6989. << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  6990. return true;
  6991. }
  6992. }
  6993. return false;
  6994. }
  6995. bool
  6996. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  6997. &FS,
  6998. const char *startSpecifier,
  6999. unsigned specifierLen) {
  7000. using namespace analyze_format_string;
  7001. using namespace analyze_printf;
  7002. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  7003. if (FS.consumesDataArgument()) {
  7004. if (atFirstArg) {
  7005. atFirstArg = false;
  7006. usesPositionalArgs = FS.usesPositionalArg();
  7007. }
  7008. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7009. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7010. startSpecifier, specifierLen);
  7011. return false;
  7012. }
  7013. }
  7014. // First check if the field width, precision, and conversion specifier
  7015. // have matching data arguments.
  7016. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  7017. startSpecifier, specifierLen)) {
  7018. return false;
  7019. }
  7020. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  7021. startSpecifier, specifierLen)) {
  7022. return false;
  7023. }
  7024. if (!CS.consumesDataArgument()) {
  7025. // FIXME: Technically specifying a precision or field width here
  7026. // makes no sense. Worth issuing a warning at some point.
  7027. return true;
  7028. }
  7029. // Consume the argument.
  7030. unsigned argIndex = FS.getArgIndex();
  7031. if (argIndex < NumDataArgs) {
  7032. // The check to see if the argIndex is valid will come later.
  7033. // We set the bit here because we may exit early from this
  7034. // function if we encounter some other error.
  7035. CoveredArgs.set(argIndex);
  7036. }
  7037. // FreeBSD kernel extensions.
  7038. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  7039. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  7040. // We need at least two arguments.
  7041. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  7042. return false;
  7043. // Claim the second argument.
  7044. CoveredArgs.set(argIndex + 1);
  7045. // Type check the first argument (int for %b, pointer for %D)
  7046. const Expr *Ex = getDataArg(argIndex);
  7047. const analyze_printf::ArgType &AT =
  7048. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  7049. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  7050. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  7051. EmitFormatDiagnostic(
  7052. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7053. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  7054. << false << Ex->getSourceRange(),
  7055. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7056. getSpecifierRange(startSpecifier, specifierLen));
  7057. // Type check the second argument (char * for both %b and %D)
  7058. Ex = getDataArg(argIndex + 1);
  7059. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  7060. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  7061. EmitFormatDiagnostic(
  7062. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7063. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  7064. << false << Ex->getSourceRange(),
  7065. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7066. getSpecifierRange(startSpecifier, specifierLen));
  7067. return true;
  7068. }
  7069. // Check for using an Objective-C specific conversion specifier
  7070. // in a non-ObjC literal.
  7071. if (!allowsObjCArg() && CS.isObjCArg()) {
  7072. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7073. specifierLen);
  7074. }
  7075. // %P can only be used with os_log.
  7076. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  7077. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7078. specifierLen);
  7079. }
  7080. // %n is not allowed with os_log.
  7081. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  7082. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  7083. getLocationOfByte(CS.getStart()),
  7084. /*IsStringLocation*/ false,
  7085. getSpecifierRange(startSpecifier, specifierLen));
  7086. return true;
  7087. }
  7088. // Only scalars are allowed for os_trace.
  7089. if (FSType == Sema::FST_OSTrace &&
  7090. (CS.getKind() == ConversionSpecifier::PArg ||
  7091. CS.getKind() == ConversionSpecifier::sArg ||
  7092. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  7093. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7094. specifierLen);
  7095. }
  7096. // Check for use of public/private annotation outside of os_log().
  7097. if (FSType != Sema::FST_OSLog) {
  7098. if (FS.isPublic().isSet()) {
  7099. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7100. << "public",
  7101. getLocationOfByte(FS.isPublic().getPosition()),
  7102. /*IsStringLocation*/ false,
  7103. getSpecifierRange(startSpecifier, specifierLen));
  7104. }
  7105. if (FS.isPrivate().isSet()) {
  7106. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7107. << "private",
  7108. getLocationOfByte(FS.isPrivate().getPosition()),
  7109. /*IsStringLocation*/ false,
  7110. getSpecifierRange(startSpecifier, specifierLen));
  7111. }
  7112. }
  7113. // Check for invalid use of field width
  7114. if (!FS.hasValidFieldWidth()) {
  7115. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  7116. startSpecifier, specifierLen);
  7117. }
  7118. // Check for invalid use of precision
  7119. if (!FS.hasValidPrecision()) {
  7120. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  7121. startSpecifier, specifierLen);
  7122. }
  7123. // Precision is mandatory for %P specifier.
  7124. if (CS.getKind() == ConversionSpecifier::PArg &&
  7125. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  7126. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  7127. getLocationOfByte(startSpecifier),
  7128. /*IsStringLocation*/ false,
  7129. getSpecifierRange(startSpecifier, specifierLen));
  7130. }
  7131. // Check each flag does not conflict with any other component.
  7132. if (!FS.hasValidThousandsGroupingPrefix())
  7133. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  7134. if (!FS.hasValidLeadingZeros())
  7135. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  7136. if (!FS.hasValidPlusPrefix())
  7137. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  7138. if (!FS.hasValidSpacePrefix())
  7139. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  7140. if (!FS.hasValidAlternativeForm())
  7141. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  7142. if (!FS.hasValidLeftJustified())
  7143. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  7144. // Check that flags are not ignored by another flag
  7145. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  7146. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  7147. startSpecifier, specifierLen);
  7148. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  7149. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  7150. startSpecifier, specifierLen);
  7151. // Check the length modifier is valid with the given conversion specifier.
  7152. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7153. S.getLangOpts()))
  7154. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7155. diag::warn_format_nonsensical_length);
  7156. else if (!FS.hasStandardLengthModifier())
  7157. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7158. else if (!FS.hasStandardLengthConversionCombination())
  7159. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7160. diag::warn_format_non_standard_conversion_spec);
  7161. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7162. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7163. // The remaining checks depend on the data arguments.
  7164. if (HasVAListArg)
  7165. return true;
  7166. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7167. return false;
  7168. const Expr *Arg = getDataArg(argIndex);
  7169. if (!Arg)
  7170. return true;
  7171. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  7172. }
  7173. static bool requiresParensToAddCast(const Expr *E) {
  7174. // FIXME: We should have a general way to reason about operator
  7175. // precedence and whether parens are actually needed here.
  7176. // Take care of a few common cases where they aren't.
  7177. const Expr *Inside = E->IgnoreImpCasts();
  7178. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  7179. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  7180. switch (Inside->getStmtClass()) {
  7181. case Stmt::ArraySubscriptExprClass:
  7182. case Stmt::CallExprClass:
  7183. case Stmt::CharacterLiteralClass:
  7184. case Stmt::CXXBoolLiteralExprClass:
  7185. case Stmt::DeclRefExprClass:
  7186. case Stmt::FloatingLiteralClass:
  7187. case Stmt::IntegerLiteralClass:
  7188. case Stmt::MemberExprClass:
  7189. case Stmt::ObjCArrayLiteralClass:
  7190. case Stmt::ObjCBoolLiteralExprClass:
  7191. case Stmt::ObjCBoxedExprClass:
  7192. case Stmt::ObjCDictionaryLiteralClass:
  7193. case Stmt::ObjCEncodeExprClass:
  7194. case Stmt::ObjCIvarRefExprClass:
  7195. case Stmt::ObjCMessageExprClass:
  7196. case Stmt::ObjCPropertyRefExprClass:
  7197. case Stmt::ObjCStringLiteralClass:
  7198. case Stmt::ObjCSubscriptRefExprClass:
  7199. case Stmt::ParenExprClass:
  7200. case Stmt::StringLiteralClass:
  7201. case Stmt::UnaryOperatorClass:
  7202. return false;
  7203. default:
  7204. return true;
  7205. }
  7206. }
  7207. static std::pair<QualType, StringRef>
  7208. shouldNotPrintDirectly(const ASTContext &Context,
  7209. QualType IntendedTy,
  7210. const Expr *E) {
  7211. // Use a 'while' to peel off layers of typedefs.
  7212. QualType TyTy = IntendedTy;
  7213. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  7214. StringRef Name = UserTy->getDecl()->getName();
  7215. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  7216. .Case("CFIndex", Context.getNSIntegerType())
  7217. .Case("NSInteger", Context.getNSIntegerType())
  7218. .Case("NSUInteger", Context.getNSUIntegerType())
  7219. .Case("SInt32", Context.IntTy)
  7220. .Case("UInt32", Context.UnsignedIntTy)
  7221. .Default(QualType());
  7222. if (!CastTy.isNull())
  7223. return std::make_pair(CastTy, Name);
  7224. TyTy = UserTy->desugar();
  7225. }
  7226. // Strip parens if necessary.
  7227. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  7228. return shouldNotPrintDirectly(Context,
  7229. PE->getSubExpr()->getType(),
  7230. PE->getSubExpr());
  7231. // If this is a conditional expression, then its result type is constructed
  7232. // via usual arithmetic conversions and thus there might be no necessary
  7233. // typedef sugar there. Recurse to operands to check for NSInteger &
  7234. // Co. usage condition.
  7235. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  7236. QualType TrueTy, FalseTy;
  7237. StringRef TrueName, FalseName;
  7238. std::tie(TrueTy, TrueName) =
  7239. shouldNotPrintDirectly(Context,
  7240. CO->getTrueExpr()->getType(),
  7241. CO->getTrueExpr());
  7242. std::tie(FalseTy, FalseName) =
  7243. shouldNotPrintDirectly(Context,
  7244. CO->getFalseExpr()->getType(),
  7245. CO->getFalseExpr());
  7246. if (TrueTy == FalseTy)
  7247. return std::make_pair(TrueTy, TrueName);
  7248. else if (TrueTy.isNull())
  7249. return std::make_pair(FalseTy, FalseName);
  7250. else if (FalseTy.isNull())
  7251. return std::make_pair(TrueTy, TrueName);
  7252. }
  7253. return std::make_pair(QualType(), StringRef());
  7254. }
  7255. /// Return true if \p ICE is an implicit argument promotion of an arithmetic
  7256. /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
  7257. /// type do not count.
  7258. static bool
  7259. isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
  7260. QualType From = ICE->getSubExpr()->getType();
  7261. QualType To = ICE->getType();
  7262. // It's an integer promotion if the destination type is the promoted
  7263. // source type.
  7264. if (ICE->getCastKind() == CK_IntegralCast &&
  7265. From->isPromotableIntegerType() &&
  7266. S.Context.getPromotedIntegerType(From) == To)
  7267. return true;
  7268. // Look through vector types, since we do default argument promotion for
  7269. // those in OpenCL.
  7270. if (const auto *VecTy = From->getAs<ExtVectorType>())
  7271. From = VecTy->getElementType();
  7272. if (const auto *VecTy = To->getAs<ExtVectorType>())
  7273. To = VecTy->getElementType();
  7274. // It's a floating promotion if the source type is a lower rank.
  7275. return ICE->getCastKind() == CK_FloatingCast &&
  7276. S.Context.getFloatingTypeOrder(From, To) < 0;
  7277. }
  7278. bool
  7279. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  7280. const char *StartSpecifier,
  7281. unsigned SpecifierLen,
  7282. const Expr *E) {
  7283. using namespace analyze_format_string;
  7284. using namespace analyze_printf;
  7285. // Now type check the data expression that matches the
  7286. // format specifier.
  7287. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  7288. if (!AT.isValid())
  7289. return true;
  7290. QualType ExprTy = E->getType();
  7291. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  7292. ExprTy = TET->getUnderlyingExpr()->getType();
  7293. }
  7294. const analyze_printf::ArgType::MatchKind Match =
  7295. AT.matchesType(S.Context, ExprTy);
  7296. bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
  7297. if (Match == analyze_printf::ArgType::Match)
  7298. return true;
  7299. // Look through argument promotions for our error message's reported type.
  7300. // This includes the integral and floating promotions, but excludes array
  7301. // and function pointer decay (seeing that an argument intended to be a
  7302. // string has type 'char [6]' is probably more confusing than 'char *') and
  7303. // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
  7304. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  7305. if (isArithmeticArgumentPromotion(S, ICE)) {
  7306. E = ICE->getSubExpr();
  7307. ExprTy = E->getType();
  7308. // Check if we didn't match because of an implicit cast from a 'char'
  7309. // or 'short' to an 'int'. This is done because printf is a varargs
  7310. // function.
  7311. if (ICE->getType() == S.Context.IntTy ||
  7312. ICE->getType() == S.Context.UnsignedIntTy) {
  7313. // All further checking is done on the subexpression.
  7314. if (AT.matchesType(S.Context, ExprTy))
  7315. return true;
  7316. }
  7317. }
  7318. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  7319. // Special case for 'a', which has type 'int' in C.
  7320. // Note, however, that we do /not/ want to treat multibyte constants like
  7321. // 'MooV' as characters! This form is deprecated but still exists.
  7322. if (ExprTy == S.Context.IntTy)
  7323. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  7324. ExprTy = S.Context.CharTy;
  7325. }
  7326. // Look through enums to their underlying type.
  7327. bool IsEnum = false;
  7328. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  7329. ExprTy = EnumTy->getDecl()->getIntegerType();
  7330. IsEnum = true;
  7331. }
  7332. // %C in an Objective-C context prints a unichar, not a wchar_t.
  7333. // If the argument is an integer of some kind, believe the %C and suggest
  7334. // a cast instead of changing the conversion specifier.
  7335. QualType IntendedTy = ExprTy;
  7336. if (isObjCContext() &&
  7337. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  7338. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  7339. !ExprTy->isCharType()) {
  7340. // 'unichar' is defined as a typedef of unsigned short, but we should
  7341. // prefer using the typedef if it is visible.
  7342. IntendedTy = S.Context.UnsignedShortTy;
  7343. // While we are here, check if the value is an IntegerLiteral that happens
  7344. // to be within the valid range.
  7345. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  7346. const llvm::APInt &V = IL->getValue();
  7347. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  7348. return true;
  7349. }
  7350. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
  7351. Sema::LookupOrdinaryName);
  7352. if (S.LookupName(Result, S.getCurScope())) {
  7353. NamedDecl *ND = Result.getFoundDecl();
  7354. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  7355. if (TD->getUnderlyingType() == IntendedTy)
  7356. IntendedTy = S.Context.getTypedefType(TD);
  7357. }
  7358. }
  7359. }
  7360. // Special-case some of Darwin's platform-independence types by suggesting
  7361. // casts to primitive types that are known to be large enough.
  7362. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  7363. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  7364. QualType CastTy;
  7365. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  7366. if (!CastTy.isNull()) {
  7367. // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
  7368. // (long in ASTContext). Only complain to pedants.
  7369. if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
  7370. (AT.isSizeT() || AT.isPtrdiffT()) &&
  7371. AT.matchesType(S.Context, CastTy))
  7372. Pedantic = true;
  7373. IntendedTy = CastTy;
  7374. ShouldNotPrintDirectly = true;
  7375. }
  7376. }
  7377. // We may be able to offer a FixItHint if it is a supported type.
  7378. PrintfSpecifier fixedFS = FS;
  7379. bool Success =
  7380. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  7381. if (Success) {
  7382. // Get the fix string from the fixed format specifier
  7383. SmallString<16> buf;
  7384. llvm::raw_svector_ostream os(buf);
  7385. fixedFS.toString(os);
  7386. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  7387. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  7388. unsigned Diag =
  7389. Pedantic
  7390. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7391. : diag::warn_format_conversion_argument_type_mismatch;
  7392. // In this case, the specifier is wrong and should be changed to match
  7393. // the argument.
  7394. EmitFormatDiagnostic(S.PDiag(Diag)
  7395. << AT.getRepresentativeTypeName(S.Context)
  7396. << IntendedTy << IsEnum << E->getSourceRange(),
  7397. E->getBeginLoc(),
  7398. /*IsStringLocation*/ false, SpecRange,
  7399. FixItHint::CreateReplacement(SpecRange, os.str()));
  7400. } else {
  7401. // The canonical type for formatting this value is different from the
  7402. // actual type of the expression. (This occurs, for example, with Darwin's
  7403. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  7404. // should be printed as 'long' for 64-bit compatibility.)
  7405. // Rather than emitting a normal format/argument mismatch, we want to
  7406. // add a cast to the recommended type (and correct the format string
  7407. // if necessary).
  7408. SmallString<16> CastBuf;
  7409. llvm::raw_svector_ostream CastFix(CastBuf);
  7410. CastFix << "(";
  7411. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  7412. CastFix << ")";
  7413. SmallVector<FixItHint,4> Hints;
  7414. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  7415. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  7416. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  7417. // If there's already a cast present, just replace it.
  7418. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  7419. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  7420. } else if (!requiresParensToAddCast(E)) {
  7421. // If the expression has high enough precedence,
  7422. // just write the C-style cast.
  7423. Hints.push_back(
  7424. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7425. } else {
  7426. // Otherwise, add parens around the expression as well as the cast.
  7427. CastFix << "(";
  7428. Hints.push_back(
  7429. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7430. SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
  7431. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  7432. }
  7433. if (ShouldNotPrintDirectly) {
  7434. // The expression has a type that should not be printed directly.
  7435. // We extract the name from the typedef because we don't want to show
  7436. // the underlying type in the diagnostic.
  7437. StringRef Name;
  7438. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  7439. Name = TypedefTy->getDecl()->getName();
  7440. else
  7441. Name = CastTyName;
  7442. unsigned Diag = Pedantic
  7443. ? diag::warn_format_argument_needs_cast_pedantic
  7444. : diag::warn_format_argument_needs_cast;
  7445. EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
  7446. << E->getSourceRange(),
  7447. E->getBeginLoc(), /*IsStringLocation=*/false,
  7448. SpecRange, Hints);
  7449. } else {
  7450. // In this case, the expression could be printed using a different
  7451. // specifier, but we've decided that the specifier is probably correct
  7452. // and we should cast instead. Just use the normal warning message.
  7453. EmitFormatDiagnostic(
  7454. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7455. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  7456. << E->getSourceRange(),
  7457. E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
  7458. }
  7459. }
  7460. } else {
  7461. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  7462. SpecifierLen);
  7463. // Since the warning for passing non-POD types to variadic functions
  7464. // was deferred until now, we emit a warning for non-POD
  7465. // arguments here.
  7466. switch (S.isValidVarArgType(ExprTy)) {
  7467. case Sema::VAK_Valid:
  7468. case Sema::VAK_ValidInCXX11: {
  7469. unsigned Diag =
  7470. Pedantic
  7471. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7472. : diag::warn_format_conversion_argument_type_mismatch;
  7473. EmitFormatDiagnostic(
  7474. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  7475. << IsEnum << CSR << E->getSourceRange(),
  7476. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7477. break;
  7478. }
  7479. case Sema::VAK_Undefined:
  7480. case Sema::VAK_MSVCUndefined:
  7481. EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  7482. << S.getLangOpts().CPlusPlus11 << ExprTy
  7483. << CallType
  7484. << AT.getRepresentativeTypeName(S.Context) << CSR
  7485. << E->getSourceRange(),
  7486. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7487. checkForCStrMembers(AT, E);
  7488. break;
  7489. case Sema::VAK_Invalid:
  7490. if (ExprTy->isObjCObjectType())
  7491. EmitFormatDiagnostic(
  7492. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  7493. << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
  7494. << AT.getRepresentativeTypeName(S.Context) << CSR
  7495. << E->getSourceRange(),
  7496. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7497. else
  7498. // FIXME: If this is an initializer list, suggest removing the braces
  7499. // or inserting a cast to the target type.
  7500. S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
  7501. << isa<InitListExpr>(E) << ExprTy << CallType
  7502. << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
  7503. break;
  7504. }
  7505. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  7506. "format string specifier index out of range");
  7507. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  7508. }
  7509. return true;
  7510. }
  7511. //===--- CHECK: Scanf format string checking ------------------------------===//
  7512. namespace {
  7513. class CheckScanfHandler : public CheckFormatHandler {
  7514. public:
  7515. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  7516. const Expr *origFormatExpr, Sema::FormatStringType type,
  7517. unsigned firstDataArg, unsigned numDataArgs,
  7518. const char *beg, bool hasVAListArg,
  7519. ArrayRef<const Expr *> Args, unsigned formatIdx,
  7520. bool inFunctionCall, Sema::VariadicCallType CallType,
  7521. llvm::SmallBitVector &CheckedVarArgs,
  7522. UncoveredArgHandler &UncoveredArg)
  7523. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  7524. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  7525. inFunctionCall, CallType, CheckedVarArgs,
  7526. UncoveredArg) {}
  7527. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  7528. const char *startSpecifier,
  7529. unsigned specifierLen) override;
  7530. bool HandleInvalidScanfConversionSpecifier(
  7531. const analyze_scanf::ScanfSpecifier &FS,
  7532. const char *startSpecifier,
  7533. unsigned specifierLen) override;
  7534. void HandleIncompleteScanList(const char *start, const char *end) override;
  7535. };
  7536. } // namespace
  7537. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  7538. const char *end) {
  7539. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  7540. getLocationOfByte(end), /*IsStringLocation*/true,
  7541. getSpecifierRange(start, end - start));
  7542. }
  7543. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  7544. const analyze_scanf::ScanfSpecifier &FS,
  7545. const char *startSpecifier,
  7546. unsigned specifierLen) {
  7547. const analyze_scanf::ScanfConversionSpecifier &CS =
  7548. FS.getConversionSpecifier();
  7549. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  7550. getLocationOfByte(CS.getStart()),
  7551. startSpecifier, specifierLen,
  7552. CS.getStart(), CS.getLength());
  7553. }
  7554. bool CheckScanfHandler::HandleScanfSpecifier(
  7555. const analyze_scanf::ScanfSpecifier &FS,
  7556. const char *startSpecifier,
  7557. unsigned specifierLen) {
  7558. using namespace analyze_scanf;
  7559. using namespace analyze_format_string;
  7560. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  7561. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  7562. // be used to decide if we are using positional arguments consistently.
  7563. if (FS.consumesDataArgument()) {
  7564. if (atFirstArg) {
  7565. atFirstArg = false;
  7566. usesPositionalArgs = FS.usesPositionalArg();
  7567. }
  7568. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7569. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7570. startSpecifier, specifierLen);
  7571. return false;
  7572. }
  7573. }
  7574. // Check if the field with is non-zero.
  7575. const OptionalAmount &Amt = FS.getFieldWidth();
  7576. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  7577. if (Amt.getConstantAmount() == 0) {
  7578. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  7579. Amt.getConstantLength());
  7580. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  7581. getLocationOfByte(Amt.getStart()),
  7582. /*IsStringLocation*/true, R,
  7583. FixItHint::CreateRemoval(R));
  7584. }
  7585. }
  7586. if (!FS.consumesDataArgument()) {
  7587. // FIXME: Technically specifying a precision or field width here
  7588. // makes no sense. Worth issuing a warning at some point.
  7589. return true;
  7590. }
  7591. // Consume the argument.
  7592. unsigned argIndex = FS.getArgIndex();
  7593. if (argIndex < NumDataArgs) {
  7594. // The check to see if the argIndex is valid will come later.
  7595. // We set the bit here because we may exit early from this
  7596. // function if we encounter some other error.
  7597. CoveredArgs.set(argIndex);
  7598. }
  7599. // Check the length modifier is valid with the given conversion specifier.
  7600. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7601. S.getLangOpts()))
  7602. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7603. diag::warn_format_nonsensical_length);
  7604. else if (!FS.hasStandardLengthModifier())
  7605. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7606. else if (!FS.hasStandardLengthConversionCombination())
  7607. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7608. diag::warn_format_non_standard_conversion_spec);
  7609. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7610. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7611. // The remaining checks depend on the data arguments.
  7612. if (HasVAListArg)
  7613. return true;
  7614. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7615. return false;
  7616. // Check that the argument type matches the format specifier.
  7617. const Expr *Ex = getDataArg(argIndex);
  7618. if (!Ex)
  7619. return true;
  7620. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  7621. if (!AT.isValid()) {
  7622. return true;
  7623. }
  7624. analyze_format_string::ArgType::MatchKind Match =
  7625. AT.matchesType(S.Context, Ex->getType());
  7626. bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
  7627. if (Match == analyze_format_string::ArgType::Match)
  7628. return true;
  7629. ScanfSpecifier fixedFS = FS;
  7630. bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  7631. S.getLangOpts(), S.Context);
  7632. unsigned Diag =
  7633. Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7634. : diag::warn_format_conversion_argument_type_mismatch;
  7635. if (Success) {
  7636. // Get the fix string from the fixed format specifier.
  7637. SmallString<128> buf;
  7638. llvm::raw_svector_ostream os(buf);
  7639. fixedFS.toString(os);
  7640. EmitFormatDiagnostic(
  7641. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
  7642. << Ex->getType() << false << Ex->getSourceRange(),
  7643. Ex->getBeginLoc(),
  7644. /*IsStringLocation*/ false,
  7645. getSpecifierRange(startSpecifier, specifierLen),
  7646. FixItHint::CreateReplacement(
  7647. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  7648. } else {
  7649. EmitFormatDiagnostic(S.PDiag(Diag)
  7650. << AT.getRepresentativeTypeName(S.Context)
  7651. << Ex->getType() << false << Ex->getSourceRange(),
  7652. Ex->getBeginLoc(),
  7653. /*IsStringLocation*/ false,
  7654. getSpecifierRange(startSpecifier, specifierLen));
  7655. }
  7656. return true;
  7657. }
  7658. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  7659. const Expr *OrigFormatExpr,
  7660. ArrayRef<const Expr *> Args,
  7661. bool HasVAListArg, unsigned format_idx,
  7662. unsigned firstDataArg,
  7663. Sema::FormatStringType Type,
  7664. bool inFunctionCall,
  7665. Sema::VariadicCallType CallType,
  7666. llvm::SmallBitVector &CheckedVarArgs,
  7667. UncoveredArgHandler &UncoveredArg) {
  7668. // CHECK: is the format string a wide literal?
  7669. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  7670. CheckFormatHandler::EmitFormatDiagnostic(
  7671. S, inFunctionCall, Args[format_idx],
  7672. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
  7673. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7674. return;
  7675. }
  7676. // Str - The format string. NOTE: this is NOT null-terminated!
  7677. StringRef StrRef = FExpr->getString();
  7678. const char *Str = StrRef.data();
  7679. // Account for cases where the string literal is truncated in a declaration.
  7680. const ConstantArrayType *T =
  7681. S.Context.getAsConstantArrayType(FExpr->getType());
  7682. assert(T && "String literal not of constant array type!");
  7683. size_t TypeSize = T->getSize().getZExtValue();
  7684. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7685. const unsigned numDataArgs = Args.size() - firstDataArg;
  7686. // Emit a warning if the string literal is truncated and does not contain an
  7687. // embedded null character.
  7688. if (TypeSize <= StrRef.size() &&
  7689. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  7690. CheckFormatHandler::EmitFormatDiagnostic(
  7691. S, inFunctionCall, Args[format_idx],
  7692. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  7693. FExpr->getBeginLoc(),
  7694. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  7695. return;
  7696. }
  7697. // CHECK: empty format string?
  7698. if (StrLen == 0 && numDataArgs > 0) {
  7699. CheckFormatHandler::EmitFormatDiagnostic(
  7700. S, inFunctionCall, Args[format_idx],
  7701. S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
  7702. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7703. return;
  7704. }
  7705. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  7706. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  7707. Type == Sema::FST_OSTrace) {
  7708. CheckPrintfHandler H(
  7709. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  7710. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  7711. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  7712. CheckedVarArgs, UncoveredArg);
  7713. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  7714. S.getLangOpts(),
  7715. S.Context.getTargetInfo(),
  7716. Type == Sema::FST_FreeBSDKPrintf))
  7717. H.DoneProcessing();
  7718. } else if (Type == Sema::FST_Scanf) {
  7719. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  7720. numDataArgs, Str, HasVAListArg, Args, format_idx,
  7721. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  7722. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  7723. S.getLangOpts(),
  7724. S.Context.getTargetInfo()))
  7725. H.DoneProcessing();
  7726. } // TODO: handle other formats
  7727. }
  7728. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  7729. // Str - The format string. NOTE: this is NOT null-terminated!
  7730. StringRef StrRef = FExpr->getString();
  7731. const char *Str = StrRef.data();
  7732. // Account for cases where the string literal is truncated in a declaration.
  7733. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  7734. assert(T && "String literal not of constant array type!");
  7735. size_t TypeSize = T->getSize().getZExtValue();
  7736. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7737. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  7738. getLangOpts(),
  7739. Context.getTargetInfo());
  7740. }
  7741. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  7742. // Returns the related absolute value function that is larger, of 0 if one
  7743. // does not exist.
  7744. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  7745. switch (AbsFunction) {
  7746. default:
  7747. return 0;
  7748. case Builtin::BI__builtin_abs:
  7749. return Builtin::BI__builtin_labs;
  7750. case Builtin::BI__builtin_labs:
  7751. return Builtin::BI__builtin_llabs;
  7752. case Builtin::BI__builtin_llabs:
  7753. return 0;
  7754. case Builtin::BI__builtin_fabsf:
  7755. return Builtin::BI__builtin_fabs;
  7756. case Builtin::BI__builtin_fabs:
  7757. return Builtin::BI__builtin_fabsl;
  7758. case Builtin::BI__builtin_fabsl:
  7759. return 0;
  7760. case Builtin::BI__builtin_cabsf:
  7761. return Builtin::BI__builtin_cabs;
  7762. case Builtin::BI__builtin_cabs:
  7763. return Builtin::BI__builtin_cabsl;
  7764. case Builtin::BI__builtin_cabsl:
  7765. return 0;
  7766. case Builtin::BIabs:
  7767. return Builtin::BIlabs;
  7768. case Builtin::BIlabs:
  7769. return Builtin::BIllabs;
  7770. case Builtin::BIllabs:
  7771. return 0;
  7772. case Builtin::BIfabsf:
  7773. return Builtin::BIfabs;
  7774. case Builtin::BIfabs:
  7775. return Builtin::BIfabsl;
  7776. case Builtin::BIfabsl:
  7777. return 0;
  7778. case Builtin::BIcabsf:
  7779. return Builtin::BIcabs;
  7780. case Builtin::BIcabs:
  7781. return Builtin::BIcabsl;
  7782. case Builtin::BIcabsl:
  7783. return 0;
  7784. }
  7785. }
  7786. // Returns the argument type of the absolute value function.
  7787. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  7788. unsigned AbsType) {
  7789. if (AbsType == 0)
  7790. return QualType();
  7791. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  7792. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  7793. if (Error != ASTContext::GE_None)
  7794. return QualType();
  7795. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  7796. if (!FT)
  7797. return QualType();
  7798. if (FT->getNumParams() != 1)
  7799. return QualType();
  7800. return FT->getParamType(0);
  7801. }
  7802. // Returns the best absolute value function, or zero, based on type and
  7803. // current absolute value function.
  7804. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  7805. unsigned AbsFunctionKind) {
  7806. unsigned BestKind = 0;
  7807. uint64_t ArgSize = Context.getTypeSize(ArgType);
  7808. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  7809. Kind = getLargerAbsoluteValueFunction(Kind)) {
  7810. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  7811. if (Context.getTypeSize(ParamType) >= ArgSize) {
  7812. if (BestKind == 0)
  7813. BestKind = Kind;
  7814. else if (Context.hasSameType(ParamType, ArgType)) {
  7815. BestKind = Kind;
  7816. break;
  7817. }
  7818. }
  7819. }
  7820. return BestKind;
  7821. }
  7822. enum AbsoluteValueKind {
  7823. AVK_Integer,
  7824. AVK_Floating,
  7825. AVK_Complex
  7826. };
  7827. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  7828. if (T->isIntegralOrEnumerationType())
  7829. return AVK_Integer;
  7830. if (T->isRealFloatingType())
  7831. return AVK_Floating;
  7832. if (T->isAnyComplexType())
  7833. return AVK_Complex;
  7834. llvm_unreachable("Type not integer, floating, or complex");
  7835. }
  7836. // Changes the absolute value function to a different type. Preserves whether
  7837. // the function is a builtin.
  7838. static unsigned changeAbsFunction(unsigned AbsKind,
  7839. AbsoluteValueKind ValueKind) {
  7840. switch (ValueKind) {
  7841. case AVK_Integer:
  7842. switch (AbsKind) {
  7843. default:
  7844. return 0;
  7845. case Builtin::BI__builtin_fabsf:
  7846. case Builtin::BI__builtin_fabs:
  7847. case Builtin::BI__builtin_fabsl:
  7848. case Builtin::BI__builtin_cabsf:
  7849. case Builtin::BI__builtin_cabs:
  7850. case Builtin::BI__builtin_cabsl:
  7851. return Builtin::BI__builtin_abs;
  7852. case Builtin::BIfabsf:
  7853. case Builtin::BIfabs:
  7854. case Builtin::BIfabsl:
  7855. case Builtin::BIcabsf:
  7856. case Builtin::BIcabs:
  7857. case Builtin::BIcabsl:
  7858. return Builtin::BIabs;
  7859. }
  7860. case AVK_Floating:
  7861. switch (AbsKind) {
  7862. default:
  7863. return 0;
  7864. case Builtin::BI__builtin_abs:
  7865. case Builtin::BI__builtin_labs:
  7866. case Builtin::BI__builtin_llabs:
  7867. case Builtin::BI__builtin_cabsf:
  7868. case Builtin::BI__builtin_cabs:
  7869. case Builtin::BI__builtin_cabsl:
  7870. return Builtin::BI__builtin_fabsf;
  7871. case Builtin::BIabs:
  7872. case Builtin::BIlabs:
  7873. case Builtin::BIllabs:
  7874. case Builtin::BIcabsf:
  7875. case Builtin::BIcabs:
  7876. case Builtin::BIcabsl:
  7877. return Builtin::BIfabsf;
  7878. }
  7879. case AVK_Complex:
  7880. switch (AbsKind) {
  7881. default:
  7882. return 0;
  7883. case Builtin::BI__builtin_abs:
  7884. case Builtin::BI__builtin_labs:
  7885. case Builtin::BI__builtin_llabs:
  7886. case Builtin::BI__builtin_fabsf:
  7887. case Builtin::BI__builtin_fabs:
  7888. case Builtin::BI__builtin_fabsl:
  7889. return Builtin::BI__builtin_cabsf;
  7890. case Builtin::BIabs:
  7891. case Builtin::BIlabs:
  7892. case Builtin::BIllabs:
  7893. case Builtin::BIfabsf:
  7894. case Builtin::BIfabs:
  7895. case Builtin::BIfabsl:
  7896. return Builtin::BIcabsf;
  7897. }
  7898. }
  7899. llvm_unreachable("Unable to convert function");
  7900. }
  7901. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  7902. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  7903. if (!FnInfo)
  7904. return 0;
  7905. switch (FDecl->getBuiltinID()) {
  7906. default:
  7907. return 0;
  7908. case Builtin::BI__builtin_abs:
  7909. case Builtin::BI__builtin_fabs:
  7910. case Builtin::BI__builtin_fabsf:
  7911. case Builtin::BI__builtin_fabsl:
  7912. case Builtin::BI__builtin_labs:
  7913. case Builtin::BI__builtin_llabs:
  7914. case Builtin::BI__builtin_cabs:
  7915. case Builtin::BI__builtin_cabsf:
  7916. case Builtin::BI__builtin_cabsl:
  7917. case Builtin::BIabs:
  7918. case Builtin::BIlabs:
  7919. case Builtin::BIllabs:
  7920. case Builtin::BIfabs:
  7921. case Builtin::BIfabsf:
  7922. case Builtin::BIfabsl:
  7923. case Builtin::BIcabs:
  7924. case Builtin::BIcabsf:
  7925. case Builtin::BIcabsl:
  7926. return FDecl->getBuiltinID();
  7927. }
  7928. llvm_unreachable("Unknown Builtin type");
  7929. }
  7930. // If the replacement is valid, emit a note with replacement function.
  7931. // Additionally, suggest including the proper header if not already included.
  7932. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  7933. unsigned AbsKind, QualType ArgType) {
  7934. bool EmitHeaderHint = true;
  7935. const char *HeaderName = nullptr;
  7936. const char *FunctionName = nullptr;
  7937. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  7938. FunctionName = "std::abs";
  7939. if (ArgType->isIntegralOrEnumerationType()) {
  7940. HeaderName = "cstdlib";
  7941. } else if (ArgType->isRealFloatingType()) {
  7942. HeaderName = "cmath";
  7943. } else {
  7944. llvm_unreachable("Invalid Type");
  7945. }
  7946. // Lookup all std::abs
  7947. if (NamespaceDecl *Std = S.getStdNamespace()) {
  7948. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  7949. R.suppressDiagnostics();
  7950. S.LookupQualifiedName(R, Std);
  7951. for (const auto *I : R) {
  7952. const FunctionDecl *FDecl = nullptr;
  7953. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  7954. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  7955. } else {
  7956. FDecl = dyn_cast<FunctionDecl>(I);
  7957. }
  7958. if (!FDecl)
  7959. continue;
  7960. // Found std::abs(), check that they are the right ones.
  7961. if (FDecl->getNumParams() != 1)
  7962. continue;
  7963. // Check that the parameter type can handle the argument.
  7964. QualType ParamType = FDecl->getParamDecl(0)->getType();
  7965. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  7966. S.Context.getTypeSize(ArgType) <=
  7967. S.Context.getTypeSize(ParamType)) {
  7968. // Found a function, don't need the header hint.
  7969. EmitHeaderHint = false;
  7970. break;
  7971. }
  7972. }
  7973. }
  7974. } else {
  7975. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  7976. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  7977. if (HeaderName) {
  7978. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  7979. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  7980. R.suppressDiagnostics();
  7981. S.LookupName(R, S.getCurScope());
  7982. if (R.isSingleResult()) {
  7983. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  7984. if (FD && FD->getBuiltinID() == AbsKind) {
  7985. EmitHeaderHint = false;
  7986. } else {
  7987. return;
  7988. }
  7989. } else if (!R.empty()) {
  7990. return;
  7991. }
  7992. }
  7993. }
  7994. S.Diag(Loc, diag::note_replace_abs_function)
  7995. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  7996. if (!HeaderName)
  7997. return;
  7998. if (!EmitHeaderHint)
  7999. return;
  8000. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  8001. << FunctionName;
  8002. }
  8003. template <std::size_t StrLen>
  8004. static bool IsStdFunction(const FunctionDecl *FDecl,
  8005. const char (&Str)[StrLen]) {
  8006. if (!FDecl)
  8007. return false;
  8008. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  8009. return false;
  8010. if (!FDecl->isInStdNamespace())
  8011. return false;
  8012. return true;
  8013. }
  8014. // Warn when using the wrong abs() function.
  8015. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  8016. const FunctionDecl *FDecl) {
  8017. if (Call->getNumArgs() != 1)
  8018. return;
  8019. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  8020. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  8021. if (AbsKind == 0 && !IsStdAbs)
  8022. return;
  8023. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8024. QualType ParamType = Call->getArg(0)->getType();
  8025. // Unsigned types cannot be negative. Suggest removing the absolute value
  8026. // function call.
  8027. if (ArgType->isUnsignedIntegerType()) {
  8028. const char *FunctionName =
  8029. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  8030. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  8031. Diag(Call->getExprLoc(), diag::note_remove_abs)
  8032. << FunctionName
  8033. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  8034. return;
  8035. }
  8036. // Taking the absolute value of a pointer is very suspicious, they probably
  8037. // wanted to index into an array, dereference a pointer, call a function, etc.
  8038. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  8039. unsigned DiagType = 0;
  8040. if (ArgType->isFunctionType())
  8041. DiagType = 1;
  8042. else if (ArgType->isArrayType())
  8043. DiagType = 2;
  8044. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  8045. return;
  8046. }
  8047. // std::abs has overloads which prevent most of the absolute value problems
  8048. // from occurring.
  8049. if (IsStdAbs)
  8050. return;
  8051. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  8052. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  8053. // The argument and parameter are the same kind. Check if they are the right
  8054. // size.
  8055. if (ArgValueKind == ParamValueKind) {
  8056. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  8057. return;
  8058. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  8059. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  8060. << FDecl << ArgType << ParamType;
  8061. if (NewAbsKind == 0)
  8062. return;
  8063. emitReplacement(*this, Call->getExprLoc(),
  8064. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8065. return;
  8066. }
  8067. // ArgValueKind != ParamValueKind
  8068. // The wrong type of absolute value function was used. Attempt to find the
  8069. // proper one.
  8070. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  8071. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  8072. if (NewAbsKind == 0)
  8073. return;
  8074. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  8075. << FDecl << ParamValueKind << ArgValueKind;
  8076. emitReplacement(*this, Call->getExprLoc(),
  8077. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8078. }
  8079. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  8080. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  8081. const FunctionDecl *FDecl) {
  8082. if (!Call || !FDecl) return;
  8083. // Ignore template specializations and macros.
  8084. if (inTemplateInstantiation()) return;
  8085. if (Call->getExprLoc().isMacroID()) return;
  8086. // Only care about the one template argument, two function parameter std::max
  8087. if (Call->getNumArgs() != 2) return;
  8088. if (!IsStdFunction(FDecl, "max")) return;
  8089. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  8090. if (!ArgList) return;
  8091. if (ArgList->size() != 1) return;
  8092. // Check that template type argument is unsigned integer.
  8093. const auto& TA = ArgList->get(0);
  8094. if (TA.getKind() != TemplateArgument::Type) return;
  8095. QualType ArgType = TA.getAsType();
  8096. if (!ArgType->isUnsignedIntegerType()) return;
  8097. // See if either argument is a literal zero.
  8098. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  8099. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  8100. if (!MTE) return false;
  8101. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  8102. if (!Num) return false;
  8103. if (Num->getValue() != 0) return false;
  8104. return true;
  8105. };
  8106. const Expr *FirstArg = Call->getArg(0);
  8107. const Expr *SecondArg = Call->getArg(1);
  8108. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  8109. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  8110. // Only warn when exactly one argument is zero.
  8111. if (IsFirstArgZero == IsSecondArgZero) return;
  8112. SourceRange FirstRange = FirstArg->getSourceRange();
  8113. SourceRange SecondRange = SecondArg->getSourceRange();
  8114. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  8115. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  8116. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  8117. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  8118. SourceRange RemovalRange;
  8119. if (IsFirstArgZero) {
  8120. RemovalRange = SourceRange(FirstRange.getBegin(),
  8121. SecondRange.getBegin().getLocWithOffset(-1));
  8122. } else {
  8123. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  8124. SecondRange.getEnd());
  8125. }
  8126. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  8127. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  8128. << FixItHint::CreateRemoval(RemovalRange);
  8129. }
  8130. //===--- CHECK: Standard memory functions ---------------------------------===//
  8131. /// Takes the expression passed to the size_t parameter of functions
  8132. /// such as memcmp, strncat, etc and warns if it's a comparison.
  8133. ///
  8134. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  8135. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  8136. IdentifierInfo *FnName,
  8137. SourceLocation FnLoc,
  8138. SourceLocation RParenLoc) {
  8139. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  8140. if (!Size)
  8141. return false;
  8142. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  8143. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  8144. return false;
  8145. SourceRange SizeRange = Size->getSourceRange();
  8146. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  8147. << SizeRange << FnName;
  8148. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  8149. << FnName
  8150. << FixItHint::CreateInsertion(
  8151. S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
  8152. << FixItHint::CreateRemoval(RParenLoc);
  8153. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  8154. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  8155. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  8156. ")");
  8157. return true;
  8158. }
  8159. /// Determine whether the given type is or contains a dynamic class type
  8160. /// (e.g., whether it has a vtable).
  8161. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  8162. bool &IsContained) {
  8163. // Look through array types while ignoring qualifiers.
  8164. const Type *Ty = T->getBaseElementTypeUnsafe();
  8165. IsContained = false;
  8166. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  8167. RD = RD ? RD->getDefinition() : nullptr;
  8168. if (!RD || RD->isInvalidDecl())
  8169. return nullptr;
  8170. if (RD->isDynamicClass())
  8171. return RD;
  8172. // Check all the fields. If any bases were dynamic, the class is dynamic.
  8173. // It's impossible for a class to transitively contain itself by value, so
  8174. // infinite recursion is impossible.
  8175. for (auto *FD : RD->fields()) {
  8176. bool SubContained;
  8177. if (const CXXRecordDecl *ContainedRD =
  8178. getContainedDynamicClass(FD->getType(), SubContained)) {
  8179. IsContained = true;
  8180. return ContainedRD;
  8181. }
  8182. }
  8183. return nullptr;
  8184. }
  8185. static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
  8186. if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  8187. if (Unary->getKind() == UETT_SizeOf)
  8188. return Unary;
  8189. return nullptr;
  8190. }
  8191. /// If E is a sizeof expression, returns its argument expression,
  8192. /// otherwise returns NULL.
  8193. static const Expr *getSizeOfExprArg(const Expr *E) {
  8194. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8195. if (!SizeOf->isArgumentType())
  8196. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  8197. return nullptr;
  8198. }
  8199. /// If E is a sizeof expression, returns its argument type.
  8200. static QualType getSizeOfArgType(const Expr *E) {
  8201. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8202. return SizeOf->getTypeOfArgument();
  8203. return QualType();
  8204. }
  8205. namespace {
  8206. struct SearchNonTrivialToInitializeField
  8207. : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
  8208. using Super =
  8209. DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
  8210. SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
  8211. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
  8212. SourceLocation SL) {
  8213. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8214. asDerived().visitArray(PDIK, AT, SL);
  8215. return;
  8216. }
  8217. Super::visitWithKind(PDIK, FT, SL);
  8218. }
  8219. void visitARCStrong(QualType FT, SourceLocation SL) {
  8220. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8221. }
  8222. void visitARCWeak(QualType FT, SourceLocation SL) {
  8223. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8224. }
  8225. void visitStruct(QualType FT, SourceLocation SL) {
  8226. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8227. visit(FD->getType(), FD->getLocation());
  8228. }
  8229. void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
  8230. const ArrayType *AT, SourceLocation SL) {
  8231. visit(getContext().getBaseElementType(AT), SL);
  8232. }
  8233. void visitTrivial(QualType FT, SourceLocation SL) {}
  8234. static void diag(QualType RT, const Expr *E, Sema &S) {
  8235. SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
  8236. }
  8237. ASTContext &getContext() { return S.getASTContext(); }
  8238. const Expr *E;
  8239. Sema &S;
  8240. };
  8241. struct SearchNonTrivialToCopyField
  8242. : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
  8243. using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
  8244. SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
  8245. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
  8246. SourceLocation SL) {
  8247. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8248. asDerived().visitArray(PCK, AT, SL);
  8249. return;
  8250. }
  8251. Super::visitWithKind(PCK, FT, SL);
  8252. }
  8253. void visitARCStrong(QualType FT, SourceLocation SL) {
  8254. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8255. }
  8256. void visitARCWeak(QualType FT, SourceLocation SL) {
  8257. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8258. }
  8259. void visitStruct(QualType FT, SourceLocation SL) {
  8260. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8261. visit(FD->getType(), FD->getLocation());
  8262. }
  8263. void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
  8264. SourceLocation SL) {
  8265. visit(getContext().getBaseElementType(AT), SL);
  8266. }
  8267. void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
  8268. SourceLocation SL) {}
  8269. void visitTrivial(QualType FT, SourceLocation SL) {}
  8270. void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
  8271. static void diag(QualType RT, const Expr *E, Sema &S) {
  8272. SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
  8273. }
  8274. ASTContext &getContext() { return S.getASTContext(); }
  8275. const Expr *E;
  8276. Sema &S;
  8277. };
  8278. }
  8279. /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
  8280. static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
  8281. SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
  8282. if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
  8283. if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
  8284. return false;
  8285. return doesExprLikelyComputeSize(BO->getLHS()) ||
  8286. doesExprLikelyComputeSize(BO->getRHS());
  8287. }
  8288. return getAsSizeOfExpr(SizeofExpr) != nullptr;
  8289. }
  8290. /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
  8291. ///
  8292. /// \code
  8293. /// #define MACRO 0
  8294. /// foo(MACRO);
  8295. /// foo(0);
  8296. /// \endcode
  8297. ///
  8298. /// This should return true for the first call to foo, but not for the second
  8299. /// (regardless of whether foo is a macro or function).
  8300. static bool isArgumentExpandedFromMacro(SourceManager &SM,
  8301. SourceLocation CallLoc,
  8302. SourceLocation ArgLoc) {
  8303. if (!CallLoc.isMacroID())
  8304. return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
  8305. return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
  8306. SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
  8307. }
  8308. /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
  8309. /// last two arguments transposed.
  8310. static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
  8311. if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
  8312. return;
  8313. const Expr *SizeArg =
  8314. Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
  8315. auto isLiteralZero = [](const Expr *E) {
  8316. return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
  8317. };
  8318. // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
  8319. SourceLocation CallLoc = Call->getRParenLoc();
  8320. SourceManager &SM = S.getSourceManager();
  8321. if (isLiteralZero(SizeArg) &&
  8322. !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
  8323. SourceLocation DiagLoc = SizeArg->getExprLoc();
  8324. // Some platforms #define bzero to __builtin_memset. See if this is the
  8325. // case, and if so, emit a better diagnostic.
  8326. if (BId == Builtin::BIbzero ||
  8327. (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
  8328. CallLoc, SM, S.getLangOpts()) == "bzero")) {
  8329. S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
  8330. S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
  8331. } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
  8332. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
  8333. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
  8334. }
  8335. return;
  8336. }
  8337. // If the second argument to a memset is a sizeof expression and the third
  8338. // isn't, this is also likely an error. This should catch
  8339. // 'memset(buf, sizeof(buf), 0xff)'.
  8340. if (BId == Builtin::BImemset &&
  8341. doesExprLikelyComputeSize(Call->getArg(1)) &&
  8342. !doesExprLikelyComputeSize(Call->getArg(2))) {
  8343. SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
  8344. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
  8345. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
  8346. return;
  8347. }
  8348. }
  8349. /// Check for dangerous or invalid arguments to memset().
  8350. ///
  8351. /// This issues warnings on known problematic, dangerous or unspecified
  8352. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  8353. /// function calls.
  8354. ///
  8355. /// \param Call The call expression to diagnose.
  8356. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  8357. unsigned BId,
  8358. IdentifierInfo *FnName) {
  8359. assert(BId != 0);
  8360. // It is possible to have a non-standard definition of memset. Validate
  8361. // we have enough arguments, and if not, abort further checking.
  8362. unsigned ExpectedNumArgs =
  8363. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  8364. if (Call->getNumArgs() < ExpectedNumArgs)
  8365. return;
  8366. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  8367. BId == Builtin::BIstrndup ? 1 : 2);
  8368. unsigned LenArg =
  8369. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  8370. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  8371. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  8372. Call->getBeginLoc(), Call->getRParenLoc()))
  8373. return;
  8374. // Catch cases like 'memset(buf, sizeof(buf), 0)'.
  8375. CheckMemaccessSize(*this, BId, Call);
  8376. // We have special checking when the length is a sizeof expression.
  8377. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  8378. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  8379. llvm::FoldingSetNodeID SizeOfArgID;
  8380. // Although widely used, 'bzero' is not a standard function. Be more strict
  8381. // with the argument types before allowing diagnostics and only allow the
  8382. // form bzero(ptr, sizeof(...)).
  8383. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8384. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  8385. return;
  8386. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  8387. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  8388. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  8389. QualType DestTy = Dest->getType();
  8390. QualType PointeeTy;
  8391. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  8392. PointeeTy = DestPtrTy->getPointeeType();
  8393. // Never warn about void type pointers. This can be used to suppress
  8394. // false positives.
  8395. if (PointeeTy->isVoidType())
  8396. continue;
  8397. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  8398. // actually comparing the expressions for equality. Because computing the
  8399. // expression IDs can be expensive, we only do this if the diagnostic is
  8400. // enabled.
  8401. if (SizeOfArg &&
  8402. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  8403. SizeOfArg->getExprLoc())) {
  8404. // We only compute IDs for expressions if the warning is enabled, and
  8405. // cache the sizeof arg's ID.
  8406. if (SizeOfArgID == llvm::FoldingSetNodeID())
  8407. SizeOfArg->Profile(SizeOfArgID, Context, true);
  8408. llvm::FoldingSetNodeID DestID;
  8409. Dest->Profile(DestID, Context, true);
  8410. if (DestID == SizeOfArgID) {
  8411. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  8412. // over sizeof(src) as well.
  8413. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  8414. StringRef ReadableName = FnName->getName();
  8415. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  8416. if (UnaryOp->getOpcode() == UO_AddrOf)
  8417. ActionIdx = 1; // If its an address-of operator, just remove it.
  8418. if (!PointeeTy->isIncompleteType() &&
  8419. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  8420. ActionIdx = 2; // If the pointee's size is sizeof(char),
  8421. // suggest an explicit length.
  8422. // If the function is defined as a builtin macro, do not show macro
  8423. // expansion.
  8424. SourceLocation SL = SizeOfArg->getExprLoc();
  8425. SourceRange DSR = Dest->getSourceRange();
  8426. SourceRange SSR = SizeOfArg->getSourceRange();
  8427. SourceManager &SM = getSourceManager();
  8428. if (SM.isMacroArgExpansion(SL)) {
  8429. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  8430. SL = SM.getSpellingLoc(SL);
  8431. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  8432. SM.getSpellingLoc(DSR.getEnd()));
  8433. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  8434. SM.getSpellingLoc(SSR.getEnd()));
  8435. }
  8436. DiagRuntimeBehavior(SL, SizeOfArg,
  8437. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  8438. << ReadableName
  8439. << PointeeTy
  8440. << DestTy
  8441. << DSR
  8442. << SSR);
  8443. DiagRuntimeBehavior(SL, SizeOfArg,
  8444. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  8445. << ActionIdx
  8446. << SSR);
  8447. break;
  8448. }
  8449. }
  8450. // Also check for cases where the sizeof argument is the exact same
  8451. // type as the memory argument, and where it points to a user-defined
  8452. // record type.
  8453. if (SizeOfArgTy != QualType()) {
  8454. if (PointeeTy->isRecordType() &&
  8455. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  8456. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  8457. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  8458. << FnName << SizeOfArgTy << ArgIdx
  8459. << PointeeTy << Dest->getSourceRange()
  8460. << LenExpr->getSourceRange());
  8461. break;
  8462. }
  8463. }
  8464. } else if (DestTy->isArrayType()) {
  8465. PointeeTy = DestTy;
  8466. }
  8467. if (PointeeTy == QualType())
  8468. continue;
  8469. // Always complain about dynamic classes.
  8470. bool IsContained;
  8471. if (const CXXRecordDecl *ContainedRD =
  8472. getContainedDynamicClass(PointeeTy, IsContained)) {
  8473. unsigned OperationType = 0;
  8474. const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
  8475. // "overwritten" if we're warning about the destination for any call
  8476. // but memcmp; otherwise a verb appropriate to the call.
  8477. if (ArgIdx != 0 || IsCmp) {
  8478. if (BId == Builtin::BImemcpy)
  8479. OperationType = 1;
  8480. else if(BId == Builtin::BImemmove)
  8481. OperationType = 2;
  8482. else if (IsCmp)
  8483. OperationType = 3;
  8484. }
  8485. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8486. PDiag(diag::warn_dyn_class_memaccess)
  8487. << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
  8488. << IsContained << ContainedRD << OperationType
  8489. << Call->getCallee()->getSourceRange());
  8490. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  8491. BId != Builtin::BImemset)
  8492. DiagRuntimeBehavior(
  8493. Dest->getExprLoc(), Dest,
  8494. PDiag(diag::warn_arc_object_memaccess)
  8495. << ArgIdx << FnName << PointeeTy
  8496. << Call->getCallee()->getSourceRange());
  8497. else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
  8498. if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
  8499. RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
  8500. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8501. PDiag(diag::warn_cstruct_memaccess)
  8502. << ArgIdx << FnName << PointeeTy << 0);
  8503. SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
  8504. } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  8505. RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
  8506. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8507. PDiag(diag::warn_cstruct_memaccess)
  8508. << ArgIdx << FnName << PointeeTy << 1);
  8509. SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
  8510. } else {
  8511. continue;
  8512. }
  8513. } else
  8514. continue;
  8515. DiagRuntimeBehavior(
  8516. Dest->getExprLoc(), Dest,
  8517. PDiag(diag::note_bad_memaccess_silence)
  8518. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  8519. break;
  8520. }
  8521. }
  8522. // A little helper routine: ignore addition and subtraction of integer literals.
  8523. // This intentionally does not ignore all integer constant expressions because
  8524. // we don't want to remove sizeof().
  8525. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  8526. Ex = Ex->IgnoreParenCasts();
  8527. while (true) {
  8528. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  8529. if (!BO || !BO->isAdditiveOp())
  8530. break;
  8531. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  8532. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  8533. if (isa<IntegerLiteral>(RHS))
  8534. Ex = LHS;
  8535. else if (isa<IntegerLiteral>(LHS))
  8536. Ex = RHS;
  8537. else
  8538. break;
  8539. }
  8540. return Ex;
  8541. }
  8542. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  8543. ASTContext &Context) {
  8544. // Only handle constant-sized or VLAs, but not flexible members.
  8545. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  8546. // Only issue the FIXIT for arrays of size > 1.
  8547. if (CAT->getSize().getSExtValue() <= 1)
  8548. return false;
  8549. } else if (!Ty->isVariableArrayType()) {
  8550. return false;
  8551. }
  8552. return true;
  8553. }
  8554. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  8555. // be the size of the source, instead of the destination.
  8556. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  8557. IdentifierInfo *FnName) {
  8558. // Don't crash if the user has the wrong number of arguments
  8559. unsigned NumArgs = Call->getNumArgs();
  8560. if ((NumArgs != 3) && (NumArgs != 4))
  8561. return;
  8562. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  8563. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  8564. const Expr *CompareWithSrc = nullptr;
  8565. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  8566. Call->getBeginLoc(), Call->getRParenLoc()))
  8567. return;
  8568. // Look for 'strlcpy(dst, x, sizeof(x))'
  8569. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  8570. CompareWithSrc = Ex;
  8571. else {
  8572. // Look for 'strlcpy(dst, x, strlen(x))'
  8573. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  8574. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  8575. SizeCall->getNumArgs() == 1)
  8576. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  8577. }
  8578. }
  8579. if (!CompareWithSrc)
  8580. return;
  8581. // Determine if the argument to sizeof/strlen is equal to the source
  8582. // argument. In principle there's all kinds of things you could do
  8583. // here, for instance creating an == expression and evaluating it with
  8584. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  8585. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  8586. if (!SrcArgDRE)
  8587. return;
  8588. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  8589. if (!CompareWithSrcDRE ||
  8590. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  8591. return;
  8592. const Expr *OriginalSizeArg = Call->getArg(2);
  8593. Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
  8594. << OriginalSizeArg->getSourceRange() << FnName;
  8595. // Output a FIXIT hint if the destination is an array (rather than a
  8596. // pointer to an array). This could be enhanced to handle some
  8597. // pointers if we know the actual size, like if DstArg is 'array+2'
  8598. // we could say 'sizeof(array)-2'.
  8599. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  8600. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  8601. return;
  8602. SmallString<128> sizeString;
  8603. llvm::raw_svector_ostream OS(sizeString);
  8604. OS << "sizeof(";
  8605. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8606. OS << ")";
  8607. Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
  8608. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  8609. OS.str());
  8610. }
  8611. /// Check if two expressions refer to the same declaration.
  8612. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  8613. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  8614. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  8615. return D1->getDecl() == D2->getDecl();
  8616. return false;
  8617. }
  8618. static const Expr *getStrlenExprArg(const Expr *E) {
  8619. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8620. const FunctionDecl *FD = CE->getDirectCallee();
  8621. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  8622. return nullptr;
  8623. return CE->getArg(0)->IgnoreParenCasts();
  8624. }
  8625. return nullptr;
  8626. }
  8627. // Warn on anti-patterns as the 'size' argument to strncat.
  8628. // The correct size argument should look like following:
  8629. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  8630. void Sema::CheckStrncatArguments(const CallExpr *CE,
  8631. IdentifierInfo *FnName) {
  8632. // Don't crash if the user has the wrong number of arguments.
  8633. if (CE->getNumArgs() < 3)
  8634. return;
  8635. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  8636. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  8637. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  8638. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
  8639. CE->getRParenLoc()))
  8640. return;
  8641. // Identify common expressions, which are wrongly used as the size argument
  8642. // to strncat and may lead to buffer overflows.
  8643. unsigned PatternType = 0;
  8644. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  8645. // - sizeof(dst)
  8646. if (referToTheSameDecl(SizeOfArg, DstArg))
  8647. PatternType = 1;
  8648. // - sizeof(src)
  8649. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  8650. PatternType = 2;
  8651. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  8652. if (BE->getOpcode() == BO_Sub) {
  8653. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  8654. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  8655. // - sizeof(dst) - strlen(dst)
  8656. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  8657. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  8658. PatternType = 1;
  8659. // - sizeof(src) - (anything)
  8660. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  8661. PatternType = 2;
  8662. }
  8663. }
  8664. if (PatternType == 0)
  8665. return;
  8666. // Generate the diagnostic.
  8667. SourceLocation SL = LenArg->getBeginLoc();
  8668. SourceRange SR = LenArg->getSourceRange();
  8669. SourceManager &SM = getSourceManager();
  8670. // If the function is defined as a builtin macro, do not show macro expansion.
  8671. if (SM.isMacroArgExpansion(SL)) {
  8672. SL = SM.getSpellingLoc(SL);
  8673. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  8674. SM.getSpellingLoc(SR.getEnd()));
  8675. }
  8676. // Check if the destination is an array (rather than a pointer to an array).
  8677. QualType DstTy = DstArg->getType();
  8678. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  8679. Context);
  8680. if (!isKnownSizeArray) {
  8681. if (PatternType == 1)
  8682. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  8683. else
  8684. Diag(SL, diag::warn_strncat_src_size) << SR;
  8685. return;
  8686. }
  8687. if (PatternType == 1)
  8688. Diag(SL, diag::warn_strncat_large_size) << SR;
  8689. else
  8690. Diag(SL, diag::warn_strncat_src_size) << SR;
  8691. SmallString<128> sizeString;
  8692. llvm::raw_svector_ostream OS(sizeString);
  8693. OS << "sizeof(";
  8694. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8695. OS << ") - ";
  8696. OS << "strlen(";
  8697. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8698. OS << ") - 1";
  8699. Diag(SL, diag::note_strncat_wrong_size)
  8700. << FixItHint::CreateReplacement(SR, OS.str());
  8701. }
  8702. void
  8703. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  8704. SourceLocation ReturnLoc,
  8705. bool isObjCMethod,
  8706. const AttrVec *Attrs,
  8707. const FunctionDecl *FD) {
  8708. // Check if the return value is null but should not be.
  8709. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  8710. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  8711. CheckNonNullExpr(*this, RetValExp))
  8712. Diag(ReturnLoc, diag::warn_null_ret)
  8713. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  8714. // C++11 [basic.stc.dynamic.allocation]p4:
  8715. // If an allocation function declared with a non-throwing
  8716. // exception-specification fails to allocate storage, it shall return
  8717. // a null pointer. Any other allocation function that fails to allocate
  8718. // storage shall indicate failure only by throwing an exception [...]
  8719. if (FD) {
  8720. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  8721. if (Op == OO_New || Op == OO_Array_New) {
  8722. const FunctionProtoType *Proto
  8723. = FD->getType()->castAs<FunctionProtoType>();
  8724. if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
  8725. CheckNonNullExpr(*this, RetValExp))
  8726. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  8727. << FD << getLangOpts().CPlusPlus11;
  8728. }
  8729. }
  8730. }
  8731. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  8732. /// Check for comparisons of floating point operands using != and ==.
  8733. /// Issue a warning if these are no self-comparisons, as they are not likely
  8734. /// to do what the programmer intended.
  8735. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  8736. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  8737. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  8738. // Special case: check for x == x (which is OK).
  8739. // Do not emit warnings for such cases.
  8740. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  8741. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  8742. if (DRL->getDecl() == DRR->getDecl())
  8743. return;
  8744. // Special case: check for comparisons against literals that can be exactly
  8745. // represented by APFloat. In such cases, do not emit a warning. This
  8746. // is a heuristic: often comparison against such literals are used to
  8747. // detect if a value in a variable has not changed. This clearly can
  8748. // lead to false negatives.
  8749. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  8750. if (FLL->isExact())
  8751. return;
  8752. } else
  8753. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  8754. if (FLR->isExact())
  8755. return;
  8756. // Check for comparisons with builtin types.
  8757. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  8758. if (CL->getBuiltinCallee())
  8759. return;
  8760. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  8761. if (CR->getBuiltinCallee())
  8762. return;
  8763. // Emit the diagnostic.
  8764. Diag(Loc, diag::warn_floatingpoint_eq)
  8765. << LHS->getSourceRange() << RHS->getSourceRange();
  8766. }
  8767. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  8768. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  8769. namespace {
  8770. /// Structure recording the 'active' range of an integer-valued
  8771. /// expression.
  8772. struct IntRange {
  8773. /// The number of bits active in the int.
  8774. unsigned Width;
  8775. /// True if the int is known not to have negative values.
  8776. bool NonNegative;
  8777. IntRange(unsigned Width, bool NonNegative)
  8778. : Width(Width), NonNegative(NonNegative) {}
  8779. /// Returns the range of the bool type.
  8780. static IntRange forBoolType() {
  8781. return IntRange(1, true);
  8782. }
  8783. /// Returns the range of an opaque value of the given integral type.
  8784. static IntRange forValueOfType(ASTContext &C, QualType T) {
  8785. return forValueOfCanonicalType(C,
  8786. T->getCanonicalTypeInternal().getTypePtr());
  8787. }
  8788. /// Returns the range of an opaque value of a canonical integral type.
  8789. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  8790. assert(T->isCanonicalUnqualified());
  8791. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8792. T = VT->getElementType().getTypePtr();
  8793. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8794. T = CT->getElementType().getTypePtr();
  8795. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8796. T = AT->getValueType().getTypePtr();
  8797. if (!C.getLangOpts().CPlusPlus) {
  8798. // For enum types in C code, use the underlying datatype.
  8799. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8800. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  8801. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  8802. // For enum types in C++, use the known bit width of the enumerators.
  8803. EnumDecl *Enum = ET->getDecl();
  8804. // In C++11, enums can have a fixed underlying type. Use this type to
  8805. // compute the range.
  8806. if (Enum->isFixed()) {
  8807. return IntRange(C.getIntWidth(QualType(T, 0)),
  8808. !ET->isSignedIntegerOrEnumerationType());
  8809. }
  8810. unsigned NumPositive = Enum->getNumPositiveBits();
  8811. unsigned NumNegative = Enum->getNumNegativeBits();
  8812. if (NumNegative == 0)
  8813. return IntRange(NumPositive, true/*NonNegative*/);
  8814. else
  8815. return IntRange(std::max(NumPositive + 1, NumNegative),
  8816. false/*NonNegative*/);
  8817. }
  8818. const BuiltinType *BT = cast<BuiltinType>(T);
  8819. assert(BT->isInteger());
  8820. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8821. }
  8822. /// Returns the "target" range of a canonical integral type, i.e.
  8823. /// the range of values expressible in the type.
  8824. ///
  8825. /// This matches forValueOfCanonicalType except that enums have the
  8826. /// full range of their type, not the range of their enumerators.
  8827. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  8828. assert(T->isCanonicalUnqualified());
  8829. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8830. T = VT->getElementType().getTypePtr();
  8831. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8832. T = CT->getElementType().getTypePtr();
  8833. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8834. T = AT->getValueType().getTypePtr();
  8835. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8836. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  8837. const BuiltinType *BT = cast<BuiltinType>(T);
  8838. assert(BT->isInteger());
  8839. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8840. }
  8841. /// Returns the supremum of two ranges: i.e. their conservative merge.
  8842. static IntRange join(IntRange L, IntRange R) {
  8843. return IntRange(std::max(L.Width, R.Width),
  8844. L.NonNegative && R.NonNegative);
  8845. }
  8846. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  8847. static IntRange meet(IntRange L, IntRange R) {
  8848. return IntRange(std::min(L.Width, R.Width),
  8849. L.NonNegative || R.NonNegative);
  8850. }
  8851. };
  8852. } // namespace
  8853. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  8854. unsigned MaxWidth) {
  8855. if (value.isSigned() && value.isNegative())
  8856. return IntRange(value.getMinSignedBits(), false);
  8857. if (value.getBitWidth() > MaxWidth)
  8858. value = value.trunc(MaxWidth);
  8859. // isNonNegative() just checks the sign bit without considering
  8860. // signedness.
  8861. return IntRange(value.getActiveBits(), true);
  8862. }
  8863. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  8864. unsigned MaxWidth) {
  8865. if (result.isInt())
  8866. return GetValueRange(C, result.getInt(), MaxWidth);
  8867. if (result.isVector()) {
  8868. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  8869. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  8870. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  8871. R = IntRange::join(R, El);
  8872. }
  8873. return R;
  8874. }
  8875. if (result.isComplexInt()) {
  8876. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  8877. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  8878. return IntRange::join(R, I);
  8879. }
  8880. // This can happen with lossless casts to intptr_t of "based" lvalues.
  8881. // Assume it might use arbitrary bits.
  8882. // FIXME: The only reason we need to pass the type in here is to get
  8883. // the sign right on this one case. It would be nice if APValue
  8884. // preserved this.
  8885. assert(result.isLValue() || result.isAddrLabelDiff());
  8886. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  8887. }
  8888. static QualType GetExprType(const Expr *E) {
  8889. QualType Ty = E->getType();
  8890. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  8891. Ty = AtomicRHS->getValueType();
  8892. return Ty;
  8893. }
  8894. /// Pseudo-evaluate the given integer expression, estimating the
  8895. /// range of values it might take.
  8896. ///
  8897. /// \param MaxWidth - the width to which the value will be truncated
  8898. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
  8899. bool InConstantContext) {
  8900. E = E->IgnoreParens();
  8901. // Try a full evaluation first.
  8902. Expr::EvalResult result;
  8903. if (E->EvaluateAsRValue(result, C, InConstantContext))
  8904. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  8905. // I think we only want to look through implicit casts here; if the
  8906. // user has an explicit widening cast, we should treat the value as
  8907. // being of the new, wider type.
  8908. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  8909. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  8910. return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
  8911. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  8912. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  8913. CE->getCastKind() == CK_BooleanToSignedIntegral;
  8914. // Assume that non-integer casts can span the full range of the type.
  8915. if (!isIntegerCast)
  8916. return OutputTypeRange;
  8917. IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
  8918. std::min(MaxWidth, OutputTypeRange.Width),
  8919. InConstantContext);
  8920. // Bail out if the subexpr's range is as wide as the cast type.
  8921. if (SubRange.Width >= OutputTypeRange.Width)
  8922. return OutputTypeRange;
  8923. // Otherwise, we take the smaller width, and we're non-negative if
  8924. // either the output type or the subexpr is.
  8925. return IntRange(SubRange.Width,
  8926. SubRange.NonNegative || OutputTypeRange.NonNegative);
  8927. }
  8928. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  8929. // If we can fold the condition, just take that operand.
  8930. bool CondResult;
  8931. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  8932. return GetExprRange(C,
  8933. CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
  8934. MaxWidth, InConstantContext);
  8935. // Otherwise, conservatively merge.
  8936. IntRange L =
  8937. GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
  8938. IntRange R =
  8939. GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
  8940. return IntRange::join(L, R);
  8941. }
  8942. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  8943. switch (BO->getOpcode()) {
  8944. case BO_Cmp:
  8945. llvm_unreachable("builtin <=> should have class type");
  8946. // Boolean-valued operations are single-bit and positive.
  8947. case BO_LAnd:
  8948. case BO_LOr:
  8949. case BO_LT:
  8950. case BO_GT:
  8951. case BO_LE:
  8952. case BO_GE:
  8953. case BO_EQ:
  8954. case BO_NE:
  8955. return IntRange::forBoolType();
  8956. // The type of the assignments is the type of the LHS, so the RHS
  8957. // is not necessarily the same type.
  8958. case BO_MulAssign:
  8959. case BO_DivAssign:
  8960. case BO_RemAssign:
  8961. case BO_AddAssign:
  8962. case BO_SubAssign:
  8963. case BO_XorAssign:
  8964. case BO_OrAssign:
  8965. // TODO: bitfields?
  8966. return IntRange::forValueOfType(C, GetExprType(E));
  8967. // Simple assignments just pass through the RHS, which will have
  8968. // been coerced to the LHS type.
  8969. case BO_Assign:
  8970. // TODO: bitfields?
  8971. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  8972. // Operations with opaque sources are black-listed.
  8973. case BO_PtrMemD:
  8974. case BO_PtrMemI:
  8975. return IntRange::forValueOfType(C, GetExprType(E));
  8976. // Bitwise-and uses the *infinum* of the two source ranges.
  8977. case BO_And:
  8978. case BO_AndAssign:
  8979. return IntRange::meet(
  8980. GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
  8981. GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
  8982. // Left shift gets black-listed based on a judgement call.
  8983. case BO_Shl:
  8984. // ...except that we want to treat '1 << (blah)' as logically
  8985. // positive. It's an important idiom.
  8986. if (IntegerLiteral *I
  8987. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  8988. if (I->getValue() == 1) {
  8989. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  8990. return IntRange(R.Width, /*NonNegative*/ true);
  8991. }
  8992. }
  8993. LLVM_FALLTHROUGH;
  8994. case BO_ShlAssign:
  8995. return IntRange::forValueOfType(C, GetExprType(E));
  8996. // Right shift by a constant can narrow its left argument.
  8997. case BO_Shr:
  8998. case BO_ShrAssign: {
  8999. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
  9000. // If the shift amount is a positive constant, drop the width by
  9001. // that much.
  9002. llvm::APSInt shift;
  9003. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  9004. shift.isNonNegative()) {
  9005. unsigned zext = shift.getZExtValue();
  9006. if (zext >= L.Width)
  9007. L.Width = (L.NonNegative ? 0 : 1);
  9008. else
  9009. L.Width -= zext;
  9010. }
  9011. return L;
  9012. }
  9013. // Comma acts as its right operand.
  9014. case BO_Comma:
  9015. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  9016. // Black-list pointer subtractions.
  9017. case BO_Sub:
  9018. if (BO->getLHS()->getType()->isPointerType())
  9019. return IntRange::forValueOfType(C, GetExprType(E));
  9020. break;
  9021. // The width of a division result is mostly determined by the size
  9022. // of the LHS.
  9023. case BO_Div: {
  9024. // Don't 'pre-truncate' the operands.
  9025. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9026. IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
  9027. // If the divisor is constant, use that.
  9028. llvm::APSInt divisor;
  9029. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  9030. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  9031. if (log2 >= L.Width)
  9032. L.Width = (L.NonNegative ? 0 : 1);
  9033. else
  9034. L.Width = std::min(L.Width - log2, MaxWidth);
  9035. return L;
  9036. }
  9037. // Otherwise, just use the LHS's width.
  9038. IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
  9039. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  9040. }
  9041. // The result of a remainder can't be larger than the result of
  9042. // either side.
  9043. case BO_Rem: {
  9044. // Don't 'pre-truncate' the operands.
  9045. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9046. IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
  9047. IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
  9048. IntRange meet = IntRange::meet(L, R);
  9049. meet.Width = std::min(meet.Width, MaxWidth);
  9050. return meet;
  9051. }
  9052. // The default behavior is okay for these.
  9053. case BO_Mul:
  9054. case BO_Add:
  9055. case BO_Xor:
  9056. case BO_Or:
  9057. break;
  9058. }
  9059. // The default case is to treat the operation as if it were closed
  9060. // on the narrowest type that encompasses both operands.
  9061. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
  9062. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  9063. return IntRange::join(L, R);
  9064. }
  9065. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  9066. switch (UO->getOpcode()) {
  9067. // Boolean-valued operations are white-listed.
  9068. case UO_LNot:
  9069. return IntRange::forBoolType();
  9070. // Operations with opaque sources are black-listed.
  9071. case UO_Deref:
  9072. case UO_AddrOf: // should be impossible
  9073. return IntRange::forValueOfType(C, GetExprType(E));
  9074. default:
  9075. return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
  9076. }
  9077. }
  9078. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  9079. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
  9080. if (const auto *BitField = E->getSourceBitField())
  9081. return IntRange(BitField->getBitWidthValue(C),
  9082. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  9083. return IntRange::forValueOfType(C, GetExprType(E));
  9084. }
  9085. static IntRange GetExprRange(ASTContext &C, const Expr *E,
  9086. bool InConstantContext) {
  9087. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
  9088. }
  9089. /// Checks whether the given value, which currently has the given
  9090. /// source semantics, has the same value when coerced through the
  9091. /// target semantics.
  9092. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  9093. const llvm::fltSemantics &Src,
  9094. const llvm::fltSemantics &Tgt) {
  9095. llvm::APFloat truncated = value;
  9096. bool ignored;
  9097. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9098. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9099. return truncated.bitwiseIsEqual(value);
  9100. }
  9101. /// Checks whether the given value, which currently has the given
  9102. /// source semantics, has the same value when coerced through the
  9103. /// target semantics.
  9104. ///
  9105. /// The value might be a vector of floats (or a complex number).
  9106. static bool IsSameFloatAfterCast(const APValue &value,
  9107. const llvm::fltSemantics &Src,
  9108. const llvm::fltSemantics &Tgt) {
  9109. if (value.isFloat())
  9110. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  9111. if (value.isVector()) {
  9112. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  9113. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  9114. return false;
  9115. return true;
  9116. }
  9117. assert(value.isComplexFloat());
  9118. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  9119. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  9120. }
  9121. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  9122. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  9123. // Suppress cases where we are comparing against an enum constant.
  9124. if (const DeclRefExpr *DR =
  9125. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  9126. if (isa<EnumConstantDecl>(DR->getDecl()))
  9127. return true;
  9128. // Suppress cases where the '0' value is expanded from a macro.
  9129. if (E->getBeginLoc().isMacroID())
  9130. return true;
  9131. return false;
  9132. }
  9133. static bool isKnownToHaveUnsignedValue(Expr *E) {
  9134. return E->getType()->isIntegerType() &&
  9135. (!E->getType()->isSignedIntegerType() ||
  9136. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  9137. }
  9138. namespace {
  9139. /// The promoted range of values of a type. In general this has the
  9140. /// following structure:
  9141. ///
  9142. /// |-----------| . . . |-----------|
  9143. /// ^ ^ ^ ^
  9144. /// Min HoleMin HoleMax Max
  9145. ///
  9146. /// ... where there is only a hole if a signed type is promoted to unsigned
  9147. /// (in which case Min and Max are the smallest and largest representable
  9148. /// values).
  9149. struct PromotedRange {
  9150. // Min, or HoleMax if there is a hole.
  9151. llvm::APSInt PromotedMin;
  9152. // Max, or HoleMin if there is a hole.
  9153. llvm::APSInt PromotedMax;
  9154. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  9155. if (R.Width == 0)
  9156. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  9157. else if (R.Width >= BitWidth && !Unsigned) {
  9158. // Promotion made the type *narrower*. This happens when promoting
  9159. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  9160. // Treat all values of 'signed int' as being in range for now.
  9161. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  9162. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  9163. } else {
  9164. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  9165. .extOrTrunc(BitWidth);
  9166. PromotedMin.setIsUnsigned(Unsigned);
  9167. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  9168. .extOrTrunc(BitWidth);
  9169. PromotedMax.setIsUnsigned(Unsigned);
  9170. }
  9171. }
  9172. // Determine whether this range is contiguous (has no hole).
  9173. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  9174. // Where a constant value is within the range.
  9175. enum ComparisonResult {
  9176. LT = 0x1,
  9177. LE = 0x2,
  9178. GT = 0x4,
  9179. GE = 0x8,
  9180. EQ = 0x10,
  9181. NE = 0x20,
  9182. InRangeFlag = 0x40,
  9183. Less = LE | LT | NE,
  9184. Min = LE | InRangeFlag,
  9185. InRange = InRangeFlag,
  9186. Max = GE | InRangeFlag,
  9187. Greater = GE | GT | NE,
  9188. OnlyValue = LE | GE | EQ | InRangeFlag,
  9189. InHole = NE
  9190. };
  9191. ComparisonResult compare(const llvm::APSInt &Value) const {
  9192. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  9193. Value.isUnsigned() == PromotedMin.isUnsigned());
  9194. if (!isContiguous()) {
  9195. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  9196. if (Value.isMinValue()) return Min;
  9197. if (Value.isMaxValue()) return Max;
  9198. if (Value >= PromotedMin) return InRange;
  9199. if (Value <= PromotedMax) return InRange;
  9200. return InHole;
  9201. }
  9202. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  9203. case -1: return Less;
  9204. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  9205. case 1:
  9206. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  9207. case -1: return InRange;
  9208. case 0: return Max;
  9209. case 1: return Greater;
  9210. }
  9211. }
  9212. llvm_unreachable("impossible compare result");
  9213. }
  9214. static llvm::Optional<StringRef>
  9215. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  9216. if (Op == BO_Cmp) {
  9217. ComparisonResult LTFlag = LT, GTFlag = GT;
  9218. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  9219. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  9220. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  9221. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  9222. return llvm::None;
  9223. }
  9224. ComparisonResult TrueFlag, FalseFlag;
  9225. if (Op == BO_EQ) {
  9226. TrueFlag = EQ;
  9227. FalseFlag = NE;
  9228. } else if (Op == BO_NE) {
  9229. TrueFlag = NE;
  9230. FalseFlag = EQ;
  9231. } else {
  9232. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  9233. TrueFlag = LT;
  9234. FalseFlag = GE;
  9235. } else {
  9236. TrueFlag = GT;
  9237. FalseFlag = LE;
  9238. }
  9239. if (Op == BO_GE || Op == BO_LE)
  9240. std::swap(TrueFlag, FalseFlag);
  9241. }
  9242. if (R & TrueFlag)
  9243. return StringRef("true");
  9244. if (R & FalseFlag)
  9245. return StringRef("false");
  9246. return llvm::None;
  9247. }
  9248. };
  9249. }
  9250. static bool HasEnumType(Expr *E) {
  9251. // Strip off implicit integral promotions.
  9252. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  9253. if (ICE->getCastKind() != CK_IntegralCast &&
  9254. ICE->getCastKind() != CK_NoOp)
  9255. break;
  9256. E = ICE->getSubExpr();
  9257. }
  9258. return E->getType()->isEnumeralType();
  9259. }
  9260. static int classifyConstantValue(Expr *Constant) {
  9261. // The values of this enumeration are used in the diagnostics
  9262. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  9263. enum ConstantValueKind {
  9264. Miscellaneous = 0,
  9265. LiteralTrue,
  9266. LiteralFalse
  9267. };
  9268. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  9269. return BL->getValue() ? ConstantValueKind::LiteralTrue
  9270. : ConstantValueKind::LiteralFalse;
  9271. return ConstantValueKind::Miscellaneous;
  9272. }
  9273. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  9274. Expr *Constant, Expr *Other,
  9275. const llvm::APSInt &Value,
  9276. bool RhsConstant) {
  9277. if (S.inTemplateInstantiation())
  9278. return false;
  9279. Expr *OriginalOther = Other;
  9280. Constant = Constant->IgnoreParenImpCasts();
  9281. Other = Other->IgnoreParenImpCasts();
  9282. // Suppress warnings on tautological comparisons between values of the same
  9283. // enumeration type. There are only two ways we could warn on this:
  9284. // - If the constant is outside the range of representable values of
  9285. // the enumeration. In such a case, we should warn about the cast
  9286. // to enumeration type, not about the comparison.
  9287. // - If the constant is the maximum / minimum in-range value. For an
  9288. // enumeratin type, such comparisons can be meaningful and useful.
  9289. if (Constant->getType()->isEnumeralType() &&
  9290. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  9291. return false;
  9292. // TODO: Investigate using GetExprRange() to get tighter bounds
  9293. // on the bit ranges.
  9294. QualType OtherT = Other->getType();
  9295. if (const auto *AT = OtherT->getAs<AtomicType>())
  9296. OtherT = AT->getValueType();
  9297. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  9298. // Whether we're treating Other as being a bool because of the form of
  9299. // expression despite it having another type (typically 'int' in C).
  9300. bool OtherIsBooleanDespiteType =
  9301. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  9302. if (OtherIsBooleanDespiteType)
  9303. OtherRange = IntRange::forBoolType();
  9304. // Determine the promoted range of the other type and see if a comparison of
  9305. // the constant against that range is tautological.
  9306. PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
  9307. Value.isUnsigned());
  9308. auto Cmp = OtherPromotedRange.compare(Value);
  9309. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  9310. if (!Result)
  9311. return false;
  9312. // Suppress the diagnostic for an in-range comparison if the constant comes
  9313. // from a macro or enumerator. We don't want to diagnose
  9314. //
  9315. // some_long_value <= INT_MAX
  9316. //
  9317. // when sizeof(int) == sizeof(long).
  9318. bool InRange = Cmp & PromotedRange::InRangeFlag;
  9319. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  9320. return false;
  9321. // If this is a comparison to an enum constant, include that
  9322. // constant in the diagnostic.
  9323. const EnumConstantDecl *ED = nullptr;
  9324. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  9325. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  9326. // Should be enough for uint128 (39 decimal digits)
  9327. SmallString<64> PrettySourceValue;
  9328. llvm::raw_svector_ostream OS(PrettySourceValue);
  9329. if (ED)
  9330. OS << '\'' << *ED << "' (" << Value << ")";
  9331. else
  9332. OS << Value;
  9333. // FIXME: We use a somewhat different formatting for the in-range cases and
  9334. // cases involving boolean values for historical reasons. We should pick a
  9335. // consistent way of presenting these diagnostics.
  9336. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  9337. S.DiagRuntimeBehavior(
  9338. E->getOperatorLoc(), E,
  9339. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  9340. : diag::warn_tautological_bool_compare)
  9341. << OS.str() << classifyConstantValue(Constant) << OtherT
  9342. << OtherIsBooleanDespiteType << *Result
  9343. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  9344. } else {
  9345. unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  9346. ? (HasEnumType(OriginalOther)
  9347. ? diag::warn_unsigned_enum_always_true_comparison
  9348. : diag::warn_unsigned_always_true_comparison)
  9349. : diag::warn_tautological_constant_compare;
  9350. S.Diag(E->getOperatorLoc(), Diag)
  9351. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  9352. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  9353. }
  9354. return true;
  9355. }
  9356. /// Analyze the operands of the given comparison. Implements the
  9357. /// fallback case from AnalyzeComparison.
  9358. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  9359. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9360. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9361. }
  9362. /// Implements -Wsign-compare.
  9363. ///
  9364. /// \param E the binary operator to check for warnings
  9365. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  9366. // The type the comparison is being performed in.
  9367. QualType T = E->getLHS()->getType();
  9368. // Only analyze comparison operators where both sides have been converted to
  9369. // the same type.
  9370. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  9371. return AnalyzeImpConvsInComparison(S, E);
  9372. // Don't analyze value-dependent comparisons directly.
  9373. if (E->isValueDependent())
  9374. return AnalyzeImpConvsInComparison(S, E);
  9375. Expr *LHS = E->getLHS();
  9376. Expr *RHS = E->getRHS();
  9377. if (T->isIntegralType(S.Context)) {
  9378. llvm::APSInt RHSValue;
  9379. llvm::APSInt LHSValue;
  9380. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  9381. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  9382. // We don't care about expressions whose result is a constant.
  9383. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  9384. return AnalyzeImpConvsInComparison(S, E);
  9385. // We only care about expressions where just one side is literal
  9386. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  9387. // Is the constant on the RHS or LHS?
  9388. const bool RhsConstant = IsRHSIntegralLiteral;
  9389. Expr *Const = RhsConstant ? RHS : LHS;
  9390. Expr *Other = RhsConstant ? LHS : RHS;
  9391. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  9392. // Check whether an integer constant comparison results in a value
  9393. // of 'true' or 'false'.
  9394. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  9395. return AnalyzeImpConvsInComparison(S, E);
  9396. }
  9397. }
  9398. if (!T->hasUnsignedIntegerRepresentation()) {
  9399. // We don't do anything special if this isn't an unsigned integral
  9400. // comparison: we're only interested in integral comparisons, and
  9401. // signed comparisons only happen in cases we don't care to warn about.
  9402. return AnalyzeImpConvsInComparison(S, E);
  9403. }
  9404. LHS = LHS->IgnoreParenImpCasts();
  9405. RHS = RHS->IgnoreParenImpCasts();
  9406. if (!S.getLangOpts().CPlusPlus) {
  9407. // Avoid warning about comparison of integers with different signs when
  9408. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  9409. // the type of `E`.
  9410. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  9411. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9412. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  9413. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9414. }
  9415. // Check to see if one of the (unmodified) operands is of different
  9416. // signedness.
  9417. Expr *signedOperand, *unsignedOperand;
  9418. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  9419. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  9420. "unsigned comparison between two signed integer expressions?");
  9421. signedOperand = LHS;
  9422. unsignedOperand = RHS;
  9423. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  9424. signedOperand = RHS;
  9425. unsignedOperand = LHS;
  9426. } else {
  9427. return AnalyzeImpConvsInComparison(S, E);
  9428. }
  9429. // Otherwise, calculate the effective range of the signed operand.
  9430. IntRange signedRange =
  9431. GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
  9432. // Go ahead and analyze implicit conversions in the operands. Note
  9433. // that we skip the implicit conversions on both sides.
  9434. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  9435. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  9436. // If the signed range is non-negative, -Wsign-compare won't fire.
  9437. if (signedRange.NonNegative)
  9438. return;
  9439. // For (in)equality comparisons, if the unsigned operand is a
  9440. // constant which cannot collide with a overflowed signed operand,
  9441. // then reinterpreting the signed operand as unsigned will not
  9442. // change the result of the comparison.
  9443. if (E->isEqualityOp()) {
  9444. unsigned comparisonWidth = S.Context.getIntWidth(T);
  9445. IntRange unsignedRange =
  9446. GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
  9447. // We should never be unable to prove that the unsigned operand is
  9448. // non-negative.
  9449. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  9450. if (unsignedRange.Width < comparisonWidth)
  9451. return;
  9452. }
  9453. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9454. S.PDiag(diag::warn_mixed_sign_comparison)
  9455. << LHS->getType() << RHS->getType()
  9456. << LHS->getSourceRange() << RHS->getSourceRange());
  9457. }
  9458. /// Analyzes an attempt to assign the given value to a bitfield.
  9459. ///
  9460. /// Returns true if there was something fishy about the attempt.
  9461. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  9462. SourceLocation InitLoc) {
  9463. assert(Bitfield->isBitField());
  9464. if (Bitfield->isInvalidDecl())
  9465. return false;
  9466. // White-list bool bitfields.
  9467. QualType BitfieldType = Bitfield->getType();
  9468. if (BitfieldType->isBooleanType())
  9469. return false;
  9470. if (BitfieldType->isEnumeralType()) {
  9471. EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
  9472. // If the underlying enum type was not explicitly specified as an unsigned
  9473. // type and the enum contain only positive values, MSVC++ will cause an
  9474. // inconsistency by storing this as a signed type.
  9475. if (S.getLangOpts().CPlusPlus11 &&
  9476. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  9477. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  9478. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  9479. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  9480. << BitfieldEnumDecl->getNameAsString();
  9481. }
  9482. }
  9483. if (Bitfield->getType()->isBooleanType())
  9484. return false;
  9485. // Ignore value- or type-dependent expressions.
  9486. if (Bitfield->getBitWidth()->isValueDependent() ||
  9487. Bitfield->getBitWidth()->isTypeDependent() ||
  9488. Init->isValueDependent() ||
  9489. Init->isTypeDependent())
  9490. return false;
  9491. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  9492. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  9493. Expr::EvalResult Result;
  9494. if (!OriginalInit->EvaluateAsInt(Result, S.Context,
  9495. Expr::SE_AllowSideEffects)) {
  9496. // The RHS is not constant. If the RHS has an enum type, make sure the
  9497. // bitfield is wide enough to hold all the values of the enum without
  9498. // truncation.
  9499. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  9500. EnumDecl *ED = EnumTy->getDecl();
  9501. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  9502. // Enum types are implicitly signed on Windows, so check if there are any
  9503. // negative enumerators to see if the enum was intended to be signed or
  9504. // not.
  9505. bool SignedEnum = ED->getNumNegativeBits() > 0;
  9506. // Check for surprising sign changes when assigning enum values to a
  9507. // bitfield of different signedness. If the bitfield is signed and we
  9508. // have exactly the right number of bits to store this unsigned enum,
  9509. // suggest changing the enum to an unsigned type. This typically happens
  9510. // on Windows where unfixed enums always use an underlying type of 'int'.
  9511. unsigned DiagID = 0;
  9512. if (SignedEnum && !SignedBitfield) {
  9513. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  9514. } else if (SignedBitfield && !SignedEnum &&
  9515. ED->getNumPositiveBits() == FieldWidth) {
  9516. DiagID = diag::warn_signed_bitfield_enum_conversion;
  9517. }
  9518. if (DiagID) {
  9519. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  9520. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  9521. SourceRange TypeRange =
  9522. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  9523. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  9524. << SignedEnum << TypeRange;
  9525. }
  9526. // Compute the required bitwidth. If the enum has negative values, we need
  9527. // one more bit than the normal number of positive bits to represent the
  9528. // sign bit.
  9529. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  9530. ED->getNumNegativeBits())
  9531. : ED->getNumPositiveBits();
  9532. // Check the bitwidth.
  9533. if (BitsNeeded > FieldWidth) {
  9534. Expr *WidthExpr = Bitfield->getBitWidth();
  9535. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  9536. << Bitfield << ED;
  9537. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  9538. << BitsNeeded << ED << WidthExpr->getSourceRange();
  9539. }
  9540. }
  9541. return false;
  9542. }
  9543. llvm::APSInt Value = Result.Val.getInt();
  9544. unsigned OriginalWidth = Value.getBitWidth();
  9545. if (!Value.isSigned() || Value.isNegative())
  9546. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  9547. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  9548. OriginalWidth = Value.getMinSignedBits();
  9549. if (OriginalWidth <= FieldWidth)
  9550. return false;
  9551. // Compute the value which the bitfield will contain.
  9552. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  9553. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  9554. // Check whether the stored value is equal to the original value.
  9555. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  9556. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  9557. return false;
  9558. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  9559. // therefore don't strictly fit into a signed bitfield of width 1.
  9560. if (FieldWidth == 1 && Value == 1)
  9561. return false;
  9562. std::string PrettyValue = Value.toString(10);
  9563. std::string PrettyTrunc = TruncatedValue.toString(10);
  9564. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  9565. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  9566. << Init->getSourceRange();
  9567. return true;
  9568. }
  9569. /// Analyze the given simple or compound assignment for warning-worthy
  9570. /// operations.
  9571. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  9572. // Just recurse on the LHS.
  9573. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9574. // We want to recurse on the RHS as normal unless we're assigning to
  9575. // a bitfield.
  9576. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  9577. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  9578. E->getOperatorLoc())) {
  9579. // Recurse, ignoring any implicit conversions on the RHS.
  9580. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  9581. E->getOperatorLoc());
  9582. }
  9583. }
  9584. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9585. // Diagnose implicitly sequentially-consistent atomic assignment.
  9586. if (E->getLHS()->getType()->isAtomicType())
  9587. S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  9588. }
  9589. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9590. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  9591. SourceLocation CContext, unsigned diag,
  9592. bool pruneControlFlow = false) {
  9593. if (pruneControlFlow) {
  9594. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9595. S.PDiag(diag)
  9596. << SourceType << T << E->getSourceRange()
  9597. << SourceRange(CContext));
  9598. return;
  9599. }
  9600. S.Diag(E->getExprLoc(), diag)
  9601. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  9602. }
  9603. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9604. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  9605. SourceLocation CContext,
  9606. unsigned diag, bool pruneControlFlow = false) {
  9607. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  9608. }
  9609. /// Diagnose an implicit cast from a floating point value to an integer value.
  9610. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  9611. SourceLocation CContext) {
  9612. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  9613. const bool PruneWarnings = S.inTemplateInstantiation();
  9614. Expr *InnerE = E->IgnoreParenImpCasts();
  9615. // We also want to warn on, e.g., "int i = -1.234"
  9616. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  9617. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  9618. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  9619. const bool IsLiteral =
  9620. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  9621. llvm::APFloat Value(0.0);
  9622. bool IsConstant =
  9623. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  9624. if (!IsConstant) {
  9625. return DiagnoseImpCast(S, E, T, CContext,
  9626. diag::warn_impcast_float_integer, PruneWarnings);
  9627. }
  9628. bool isExact = false;
  9629. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  9630. T->hasUnsignedIntegerRepresentation());
  9631. llvm::APFloat::opStatus Result = Value.convertToInteger(
  9632. IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
  9633. if (Result == llvm::APFloat::opOK && isExact) {
  9634. if (IsLiteral) return;
  9635. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  9636. PruneWarnings);
  9637. }
  9638. // Conversion of a floating-point value to a non-bool integer where the
  9639. // integral part cannot be represented by the integer type is undefined.
  9640. if (!IsBool && Result == llvm::APFloat::opInvalidOp)
  9641. return DiagnoseImpCast(
  9642. S, E, T, CContext,
  9643. IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
  9644. : diag::warn_impcast_float_to_integer_out_of_range,
  9645. PruneWarnings);
  9646. unsigned DiagID = 0;
  9647. if (IsLiteral) {
  9648. // Warn on floating point literal to integer.
  9649. DiagID = diag::warn_impcast_literal_float_to_integer;
  9650. } else if (IntegerValue == 0) {
  9651. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  9652. return DiagnoseImpCast(S, E, T, CContext,
  9653. diag::warn_impcast_float_integer, PruneWarnings);
  9654. }
  9655. // Warn on non-zero to zero conversion.
  9656. DiagID = diag::warn_impcast_float_to_integer_zero;
  9657. } else {
  9658. if (IntegerValue.isUnsigned()) {
  9659. if (!IntegerValue.isMaxValue()) {
  9660. return DiagnoseImpCast(S, E, T, CContext,
  9661. diag::warn_impcast_float_integer, PruneWarnings);
  9662. }
  9663. } else { // IntegerValue.isSigned()
  9664. if (!IntegerValue.isMaxSignedValue() &&
  9665. !IntegerValue.isMinSignedValue()) {
  9666. return DiagnoseImpCast(S, E, T, CContext,
  9667. diag::warn_impcast_float_integer, PruneWarnings);
  9668. }
  9669. }
  9670. // Warn on evaluatable floating point expression to integer conversion.
  9671. DiagID = diag::warn_impcast_float_to_integer;
  9672. }
  9673. // FIXME: Force the precision of the source value down so we don't print
  9674. // digits which are usually useless (we don't really care here if we
  9675. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  9676. // would automatically print the shortest representation, but it's a bit
  9677. // tricky to implement.
  9678. SmallString<16> PrettySourceValue;
  9679. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  9680. precision = (precision * 59 + 195) / 196;
  9681. Value.toString(PrettySourceValue, precision);
  9682. SmallString<16> PrettyTargetValue;
  9683. if (IsBool)
  9684. PrettyTargetValue = Value.isZero() ? "false" : "true";
  9685. else
  9686. IntegerValue.toString(PrettyTargetValue);
  9687. if (PruneWarnings) {
  9688. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9689. S.PDiag(DiagID)
  9690. << E->getType() << T.getUnqualifiedType()
  9691. << PrettySourceValue << PrettyTargetValue
  9692. << E->getSourceRange() << SourceRange(CContext));
  9693. } else {
  9694. S.Diag(E->getExprLoc(), DiagID)
  9695. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  9696. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  9697. }
  9698. }
  9699. /// Analyze the given compound assignment for the possible losing of
  9700. /// floating-point precision.
  9701. static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
  9702. assert(isa<CompoundAssignOperator>(E) &&
  9703. "Must be compound assignment operation");
  9704. // Recurse on the LHS and RHS in here
  9705. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9706. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9707. if (E->getLHS()->getType()->isAtomicType())
  9708. S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
  9709. // Now check the outermost expression
  9710. const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
  9711. const auto *RBT = cast<CompoundAssignOperator>(E)
  9712. ->getComputationResultType()
  9713. ->getAs<BuiltinType>();
  9714. // The below checks assume source is floating point.
  9715. if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
  9716. // If source is floating point but target is an integer.
  9717. if (ResultBT->isInteger())
  9718. return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
  9719. E->getExprLoc(), diag::warn_impcast_float_integer);
  9720. if (!ResultBT->isFloatingPoint())
  9721. return;
  9722. // If both source and target are floating points, warn about losing precision.
  9723. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  9724. QualType(ResultBT, 0), QualType(RBT, 0));
  9725. if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
  9726. // warn about dropping FP rank.
  9727. DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
  9728. diag::warn_impcast_float_result_precision);
  9729. }
  9730. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  9731. IntRange Range) {
  9732. if (!Range.Width) return "0";
  9733. llvm::APSInt ValueInRange = Value;
  9734. ValueInRange.setIsSigned(!Range.NonNegative);
  9735. ValueInRange = ValueInRange.trunc(Range.Width);
  9736. return ValueInRange.toString(10);
  9737. }
  9738. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  9739. if (!isa<ImplicitCastExpr>(Ex))
  9740. return false;
  9741. Expr *InnerE = Ex->IgnoreParenImpCasts();
  9742. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  9743. const Type *Source =
  9744. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  9745. if (Target->isDependentType())
  9746. return false;
  9747. const BuiltinType *FloatCandidateBT =
  9748. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  9749. const Type *BoolCandidateType = ToBool ? Target : Source;
  9750. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  9751. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  9752. }
  9753. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  9754. SourceLocation CC) {
  9755. unsigned NumArgs = TheCall->getNumArgs();
  9756. for (unsigned i = 0; i < NumArgs; ++i) {
  9757. Expr *CurrA = TheCall->getArg(i);
  9758. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  9759. continue;
  9760. bool IsSwapped = ((i > 0) &&
  9761. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  9762. IsSwapped |= ((i < (NumArgs - 1)) &&
  9763. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  9764. if (IsSwapped) {
  9765. // Warn on this floating-point to bool conversion.
  9766. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  9767. CurrA->getType(), CC,
  9768. diag::warn_impcast_floating_point_to_bool);
  9769. }
  9770. }
  9771. }
  9772. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  9773. SourceLocation CC) {
  9774. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  9775. E->getExprLoc()))
  9776. return;
  9777. // Don't warn on functions which have return type nullptr_t.
  9778. if (isa<CallExpr>(E))
  9779. return;
  9780. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  9781. const Expr::NullPointerConstantKind NullKind =
  9782. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  9783. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  9784. return;
  9785. // Return if target type is a safe conversion.
  9786. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  9787. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  9788. return;
  9789. SourceLocation Loc = E->getSourceRange().getBegin();
  9790. // Venture through the macro stacks to get to the source of macro arguments.
  9791. // The new location is a better location than the complete location that was
  9792. // passed in.
  9793. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  9794. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  9795. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  9796. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  9797. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  9798. Loc, S.SourceMgr, S.getLangOpts());
  9799. if (MacroName == "NULL")
  9800. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
  9801. }
  9802. // Only warn if the null and context location are in the same macro expansion.
  9803. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  9804. return;
  9805. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  9806. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  9807. << FixItHint::CreateReplacement(Loc,
  9808. S.getFixItZeroLiteralForType(T, Loc));
  9809. }
  9810. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9811. ObjCArrayLiteral *ArrayLiteral);
  9812. static void
  9813. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9814. ObjCDictionaryLiteral *DictionaryLiteral);
  9815. /// Check a single element within a collection literal against the
  9816. /// target element type.
  9817. static void checkObjCCollectionLiteralElement(Sema &S,
  9818. QualType TargetElementType,
  9819. Expr *Element,
  9820. unsigned ElementKind) {
  9821. // Skip a bitcast to 'id' or qualified 'id'.
  9822. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  9823. if (ICE->getCastKind() == CK_BitCast &&
  9824. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  9825. Element = ICE->getSubExpr();
  9826. }
  9827. QualType ElementType = Element->getType();
  9828. ExprResult ElementResult(Element);
  9829. if (ElementType->getAs<ObjCObjectPointerType>() &&
  9830. S.CheckSingleAssignmentConstraints(TargetElementType,
  9831. ElementResult,
  9832. false, false)
  9833. != Sema::Compatible) {
  9834. S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
  9835. << ElementType << ElementKind << TargetElementType
  9836. << Element->getSourceRange();
  9837. }
  9838. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  9839. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  9840. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  9841. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  9842. }
  9843. /// Check an Objective-C array literal being converted to the given
  9844. /// target type.
  9845. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9846. ObjCArrayLiteral *ArrayLiteral) {
  9847. if (!S.NSArrayDecl)
  9848. return;
  9849. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9850. if (!TargetObjCPtr)
  9851. return;
  9852. if (TargetObjCPtr->isUnspecialized() ||
  9853. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9854. != S.NSArrayDecl->getCanonicalDecl())
  9855. return;
  9856. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9857. if (TypeArgs.size() != 1)
  9858. return;
  9859. QualType TargetElementType = TypeArgs[0];
  9860. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  9861. checkObjCCollectionLiteralElement(S, TargetElementType,
  9862. ArrayLiteral->getElement(I),
  9863. 0);
  9864. }
  9865. }
  9866. /// Check an Objective-C dictionary literal being converted to the given
  9867. /// target type.
  9868. static void
  9869. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9870. ObjCDictionaryLiteral *DictionaryLiteral) {
  9871. if (!S.NSDictionaryDecl)
  9872. return;
  9873. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9874. if (!TargetObjCPtr)
  9875. return;
  9876. if (TargetObjCPtr->isUnspecialized() ||
  9877. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9878. != S.NSDictionaryDecl->getCanonicalDecl())
  9879. return;
  9880. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9881. if (TypeArgs.size() != 2)
  9882. return;
  9883. QualType TargetKeyType = TypeArgs[0];
  9884. QualType TargetObjectType = TypeArgs[1];
  9885. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  9886. auto Element = DictionaryLiteral->getKeyValueElement(I);
  9887. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  9888. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  9889. }
  9890. }
  9891. // Helper function to filter out cases for constant width constant conversion.
  9892. // Don't warn on char array initialization or for non-decimal values.
  9893. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  9894. SourceLocation CC) {
  9895. // If initializing from a constant, and the constant starts with '0',
  9896. // then it is a binary, octal, or hexadecimal. Allow these constants
  9897. // to fill all the bits, even if there is a sign change.
  9898. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  9899. const char FirstLiteralCharacter =
  9900. S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
  9901. if (FirstLiteralCharacter == '0')
  9902. return false;
  9903. }
  9904. // If the CC location points to a '{', and the type is char, then assume
  9905. // assume it is an array initialization.
  9906. if (CC.isValid() && T->isCharType()) {
  9907. const char FirstContextCharacter =
  9908. S.getSourceManager().getCharacterData(CC)[0];
  9909. if (FirstContextCharacter == '{')
  9910. return false;
  9911. }
  9912. return true;
  9913. }
  9914. static void
  9915. CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
  9916. bool *ICContext = nullptr) {
  9917. if (E->isTypeDependent() || E->isValueDependent()) return;
  9918. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  9919. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  9920. if (Source == Target) return;
  9921. if (Target->isDependentType()) return;
  9922. // If the conversion context location is invalid don't complain. We also
  9923. // don't want to emit a warning if the issue occurs from the expansion of
  9924. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  9925. // delay this check as long as possible. Once we detect we are in that
  9926. // scenario, we just return.
  9927. if (CC.isInvalid())
  9928. return;
  9929. if (Source->isAtomicType())
  9930. S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
  9931. // Diagnose implicit casts to bool.
  9932. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  9933. if (isa<StringLiteral>(E))
  9934. // Warn on string literal to bool. Checks for string literals in logical
  9935. // and expressions, for instance, assert(0 && "error here"), are
  9936. // prevented by a check in AnalyzeImplicitConversions().
  9937. return DiagnoseImpCast(S, E, T, CC,
  9938. diag::warn_impcast_string_literal_to_bool);
  9939. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  9940. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  9941. // This covers the literal expressions that evaluate to Objective-C
  9942. // objects.
  9943. return DiagnoseImpCast(S, E, T, CC,
  9944. diag::warn_impcast_objective_c_literal_to_bool);
  9945. }
  9946. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  9947. // Warn on pointer to bool conversion that is always true.
  9948. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  9949. SourceRange(CC));
  9950. }
  9951. }
  9952. // Check implicit casts from Objective-C collection literals to specialized
  9953. // collection types, e.g., NSArray<NSString *> *.
  9954. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  9955. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  9956. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  9957. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  9958. // Strip vector types.
  9959. if (isa<VectorType>(Source)) {
  9960. if (!isa<VectorType>(Target)) {
  9961. if (S.SourceMgr.isInSystemMacro(CC))
  9962. return;
  9963. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  9964. }
  9965. // If the vector cast is cast between two vectors of the same size, it is
  9966. // a bitcast, not a conversion.
  9967. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  9968. return;
  9969. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  9970. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  9971. }
  9972. if (auto VecTy = dyn_cast<VectorType>(Target))
  9973. Target = VecTy->getElementType().getTypePtr();
  9974. // Strip complex types.
  9975. if (isa<ComplexType>(Source)) {
  9976. if (!isa<ComplexType>(Target)) {
  9977. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  9978. return;
  9979. return DiagnoseImpCast(S, E, T, CC,
  9980. S.getLangOpts().CPlusPlus
  9981. ? diag::err_impcast_complex_scalar
  9982. : diag::warn_impcast_complex_scalar);
  9983. }
  9984. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  9985. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  9986. }
  9987. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  9988. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  9989. // If the source is floating point...
  9990. if (SourceBT && SourceBT->isFloatingPoint()) {
  9991. // ...and the target is floating point...
  9992. if (TargetBT && TargetBT->isFloatingPoint()) {
  9993. // ...then warn if we're dropping FP rank.
  9994. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  9995. QualType(SourceBT, 0), QualType(TargetBT, 0));
  9996. if (Order > 0) {
  9997. // Don't warn about float constants that are precisely
  9998. // representable in the target type.
  9999. Expr::EvalResult result;
  10000. if (E->EvaluateAsRValue(result, S.Context)) {
  10001. // Value might be a float, a float vector, or a float complex.
  10002. if (IsSameFloatAfterCast(result.Val,
  10003. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  10004. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  10005. return;
  10006. }
  10007. if (S.SourceMgr.isInSystemMacro(CC))
  10008. return;
  10009. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  10010. }
  10011. // ... or possibly if we're increasing rank, too
  10012. else if (Order < 0) {
  10013. if (S.SourceMgr.isInSystemMacro(CC))
  10014. return;
  10015. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  10016. }
  10017. return;
  10018. }
  10019. // If the target is integral, always warn.
  10020. if (TargetBT && TargetBT->isInteger()) {
  10021. if (S.SourceMgr.isInSystemMacro(CC))
  10022. return;
  10023. DiagnoseFloatingImpCast(S, E, T, CC);
  10024. }
  10025. // Detect the case where a call result is converted from floating-point to
  10026. // to bool, and the final argument to the call is converted from bool, to
  10027. // discover this typo:
  10028. //
  10029. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  10030. //
  10031. // FIXME: This is an incredibly special case; is there some more general
  10032. // way to detect this class of misplaced-parentheses bug?
  10033. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  10034. // Check last argument of function call to see if it is an
  10035. // implicit cast from a type matching the type the result
  10036. // is being cast to.
  10037. CallExpr *CEx = cast<CallExpr>(E);
  10038. if (unsigned NumArgs = CEx->getNumArgs()) {
  10039. Expr *LastA = CEx->getArg(NumArgs - 1);
  10040. Expr *InnerE = LastA->IgnoreParenImpCasts();
  10041. if (isa<ImplicitCastExpr>(LastA) &&
  10042. InnerE->getType()->isBooleanType()) {
  10043. // Warn on this floating-point to bool conversion
  10044. DiagnoseImpCast(S, E, T, CC,
  10045. diag::warn_impcast_floating_point_to_bool);
  10046. }
  10047. }
  10048. }
  10049. return;
  10050. }
  10051. // Valid casts involving fixed point types should be accounted for here.
  10052. if (Source->isFixedPointType()) {
  10053. if (Target->isUnsaturatedFixedPointType()) {
  10054. Expr::EvalResult Result;
  10055. if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
  10056. S.isConstantEvaluated())) {
  10057. APFixedPoint Value = Result.Val.getFixedPoint();
  10058. APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
  10059. APFixedPoint MinVal = S.Context.getFixedPointMin(T);
  10060. if (Value > MaxVal || Value < MinVal) {
  10061. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10062. S.PDiag(diag::warn_impcast_fixed_point_range)
  10063. << Value.toString() << T
  10064. << E->getSourceRange()
  10065. << clang::SourceRange(CC));
  10066. return;
  10067. }
  10068. }
  10069. } else if (Target->isIntegerType()) {
  10070. Expr::EvalResult Result;
  10071. if (!S.isConstantEvaluated() &&
  10072. E->EvaluateAsFixedPoint(Result, S.Context,
  10073. Expr::SE_AllowSideEffects)) {
  10074. APFixedPoint FXResult = Result.Val.getFixedPoint();
  10075. bool Overflowed;
  10076. llvm::APSInt IntResult = FXResult.convertToInt(
  10077. S.Context.getIntWidth(T),
  10078. Target->isSignedIntegerOrEnumerationType(), &Overflowed);
  10079. if (Overflowed) {
  10080. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10081. S.PDiag(diag::warn_impcast_fixed_point_range)
  10082. << FXResult.toString() << T
  10083. << E->getSourceRange()
  10084. << clang::SourceRange(CC));
  10085. return;
  10086. }
  10087. }
  10088. }
  10089. } else if (Target->isUnsaturatedFixedPointType()) {
  10090. if (Source->isIntegerType()) {
  10091. Expr::EvalResult Result;
  10092. if (!S.isConstantEvaluated() &&
  10093. E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
  10094. llvm::APSInt Value = Result.Val.getInt();
  10095. bool Overflowed;
  10096. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  10097. Value, S.Context.getFixedPointSemantics(T), &Overflowed);
  10098. if (Overflowed) {
  10099. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10100. S.PDiag(diag::warn_impcast_fixed_point_range)
  10101. << Value.toString(/*radix=*/10) << T
  10102. << E->getSourceRange()
  10103. << clang::SourceRange(CC));
  10104. return;
  10105. }
  10106. }
  10107. }
  10108. }
  10109. DiagnoseNullConversion(S, E, T, CC);
  10110. S.DiscardMisalignedMemberAddress(Target, E);
  10111. if (!Source->isIntegerType() || !Target->isIntegerType())
  10112. return;
  10113. // TODO: remove this early return once the false positives for constant->bool
  10114. // in templates, macros, etc, are reduced or removed.
  10115. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  10116. return;
  10117. IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
  10118. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  10119. if (SourceRange.Width > TargetRange.Width) {
  10120. // If the source is a constant, use a default-on diagnostic.
  10121. // TODO: this should happen for bitfield stores, too.
  10122. Expr::EvalResult Result;
  10123. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
  10124. S.isConstantEvaluated())) {
  10125. llvm::APSInt Value(32);
  10126. Value = Result.Val.getInt();
  10127. if (S.SourceMgr.isInSystemMacro(CC))
  10128. return;
  10129. std::string PrettySourceValue = Value.toString(10);
  10130. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10131. S.DiagRuntimeBehavior(
  10132. E->getExprLoc(), E,
  10133. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10134. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10135. << E->getSourceRange() << clang::SourceRange(CC));
  10136. return;
  10137. }
  10138. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  10139. if (S.SourceMgr.isInSystemMacro(CC))
  10140. return;
  10141. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  10142. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  10143. /* pruneControlFlow */ true);
  10144. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  10145. }
  10146. if (TargetRange.Width > SourceRange.Width) {
  10147. if (auto *UO = dyn_cast<UnaryOperator>(E))
  10148. if (UO->getOpcode() == UO_Minus)
  10149. if (Source->isUnsignedIntegerType()) {
  10150. if (Target->isUnsignedIntegerType())
  10151. return DiagnoseImpCast(S, E, T, CC,
  10152. diag::warn_impcast_high_order_zero_bits);
  10153. if (Target->isSignedIntegerType())
  10154. return DiagnoseImpCast(S, E, T, CC,
  10155. diag::warn_impcast_nonnegative_result);
  10156. }
  10157. }
  10158. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  10159. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  10160. // Warn when doing a signed to signed conversion, warn if the positive
  10161. // source value is exactly the width of the target type, which will
  10162. // cause a negative value to be stored.
  10163. Expr::EvalResult Result;
  10164. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
  10165. !S.SourceMgr.isInSystemMacro(CC)) {
  10166. llvm::APSInt Value = Result.Val.getInt();
  10167. if (isSameWidthConstantConversion(S, E, T, CC)) {
  10168. std::string PrettySourceValue = Value.toString(10);
  10169. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10170. S.DiagRuntimeBehavior(
  10171. E->getExprLoc(), E,
  10172. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10173. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10174. << E->getSourceRange() << clang::SourceRange(CC));
  10175. return;
  10176. }
  10177. }
  10178. // Fall through for non-constants to give a sign conversion warning.
  10179. }
  10180. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  10181. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  10182. SourceRange.Width == TargetRange.Width)) {
  10183. if (S.SourceMgr.isInSystemMacro(CC))
  10184. return;
  10185. unsigned DiagID = diag::warn_impcast_integer_sign;
  10186. // Traditionally, gcc has warned about this under -Wsign-compare.
  10187. // We also want to warn about it in -Wconversion.
  10188. // So if -Wconversion is off, use a completely identical diagnostic
  10189. // in the sign-compare group.
  10190. // The conditional-checking code will
  10191. if (ICContext) {
  10192. DiagID = diag::warn_impcast_integer_sign_conditional;
  10193. *ICContext = true;
  10194. }
  10195. return DiagnoseImpCast(S, E, T, CC, DiagID);
  10196. }
  10197. // Diagnose conversions between different enumeration types.
  10198. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  10199. // type, to give us better diagnostics.
  10200. QualType SourceType = E->getType();
  10201. if (!S.getLangOpts().CPlusPlus) {
  10202. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10203. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  10204. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  10205. SourceType = S.Context.getTypeDeclType(Enum);
  10206. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  10207. }
  10208. }
  10209. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  10210. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  10211. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  10212. TargetEnum->getDecl()->hasNameForLinkage() &&
  10213. SourceEnum != TargetEnum) {
  10214. if (S.SourceMgr.isInSystemMacro(CC))
  10215. return;
  10216. return DiagnoseImpCast(S, E, SourceType, T, CC,
  10217. diag::warn_impcast_different_enum_types);
  10218. }
  10219. }
  10220. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10221. SourceLocation CC, QualType T);
  10222. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  10223. SourceLocation CC, bool &ICContext) {
  10224. E = E->IgnoreParenImpCasts();
  10225. if (isa<ConditionalOperator>(E))
  10226. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  10227. AnalyzeImplicitConversions(S, E, CC);
  10228. if (E->getType() != T)
  10229. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  10230. }
  10231. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10232. SourceLocation CC, QualType T) {
  10233. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  10234. bool Suspicious = false;
  10235. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  10236. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  10237. // If -Wconversion would have warned about either of the candidates
  10238. // for a signedness conversion to the context type...
  10239. if (!Suspicious) return;
  10240. // ...but it's currently ignored...
  10241. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  10242. return;
  10243. // ...then check whether it would have warned about either of the
  10244. // candidates for a signedness conversion to the condition type.
  10245. if (E->getType() == T) return;
  10246. Suspicious = false;
  10247. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  10248. E->getType(), CC, &Suspicious);
  10249. if (!Suspicious)
  10250. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  10251. E->getType(), CC, &Suspicious);
  10252. }
  10253. /// Check conversion of given expression to boolean.
  10254. /// Input argument E is a logical expression.
  10255. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  10256. if (S.getLangOpts().Bool)
  10257. return;
  10258. if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
  10259. return;
  10260. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  10261. }
  10262. /// AnalyzeImplicitConversions - Find and report any interesting
  10263. /// implicit conversions in the given expression. There are a couple
  10264. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  10265. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
  10266. SourceLocation CC) {
  10267. QualType T = OrigE->getType();
  10268. Expr *E = OrigE->IgnoreParenImpCasts();
  10269. if (E->isTypeDependent() || E->isValueDependent())
  10270. return;
  10271. // For conditional operators, we analyze the arguments as if they
  10272. // were being fed directly into the output.
  10273. if (isa<ConditionalOperator>(E)) {
  10274. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  10275. CheckConditionalOperator(S, CO, CC, T);
  10276. return;
  10277. }
  10278. // Check implicit argument conversions for function calls.
  10279. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  10280. CheckImplicitArgumentConversions(S, Call, CC);
  10281. // Go ahead and check any implicit conversions we might have skipped.
  10282. // The non-canonical typecheck is just an optimization;
  10283. // CheckImplicitConversion will filter out dead implicit conversions.
  10284. if (E->getType() != T)
  10285. CheckImplicitConversion(S, E, T, CC);
  10286. // Now continue drilling into this expression.
  10287. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  10288. // The bound subexpressions in a PseudoObjectExpr are not reachable
  10289. // as transitive children.
  10290. // FIXME: Use a more uniform representation for this.
  10291. for (auto *SE : POE->semantics())
  10292. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  10293. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  10294. }
  10295. // Skip past explicit casts.
  10296. if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
  10297. E = CE->getSubExpr()->IgnoreParenImpCasts();
  10298. if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
  10299. S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  10300. return AnalyzeImplicitConversions(S, E, CC);
  10301. }
  10302. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10303. // Do a somewhat different check with comparison operators.
  10304. if (BO->isComparisonOp())
  10305. return AnalyzeComparison(S, BO);
  10306. // And with simple assignments.
  10307. if (BO->getOpcode() == BO_Assign)
  10308. return AnalyzeAssignment(S, BO);
  10309. // And with compound assignments.
  10310. if (BO->isAssignmentOp())
  10311. return AnalyzeCompoundAssignment(S, BO);
  10312. }
  10313. // These break the otherwise-useful invariant below. Fortunately,
  10314. // we don't really need to recurse into them, because any internal
  10315. // expressions should have been analyzed already when they were
  10316. // built into statements.
  10317. if (isa<StmtExpr>(E)) return;
  10318. // Don't descend into unevaluated contexts.
  10319. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  10320. // Now just recurse over the expression's children.
  10321. CC = E->getExprLoc();
  10322. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  10323. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  10324. for (Stmt *SubStmt : E->children()) {
  10325. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  10326. if (!ChildExpr)
  10327. continue;
  10328. if (IsLogicalAndOperator &&
  10329. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  10330. // Ignore checking string literals that are in logical and operators.
  10331. // This is a common pattern for asserts.
  10332. continue;
  10333. AnalyzeImplicitConversions(S, ChildExpr, CC);
  10334. }
  10335. if (BO && BO->isLogicalOp()) {
  10336. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  10337. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10338. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10339. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  10340. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10341. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10342. }
  10343. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  10344. if (U->getOpcode() == UO_LNot) {
  10345. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  10346. } else if (U->getOpcode() != UO_AddrOf) {
  10347. if (U->getSubExpr()->getType()->isAtomicType())
  10348. S.Diag(U->getSubExpr()->getBeginLoc(),
  10349. diag::warn_atomic_implicit_seq_cst);
  10350. }
  10351. }
  10352. }
  10353. /// Diagnose integer type and any valid implicit conversion to it.
  10354. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  10355. // Taking into account implicit conversions,
  10356. // allow any integer.
  10357. if (!E->getType()->isIntegerType()) {
  10358. S.Diag(E->getBeginLoc(),
  10359. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  10360. return true;
  10361. }
  10362. // Potentially emit standard warnings for implicit conversions if enabled
  10363. // using -Wconversion.
  10364. CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
  10365. return false;
  10366. }
  10367. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  10368. // Returns true when emitting a warning about taking the address of a reference.
  10369. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  10370. const PartialDiagnostic &PD) {
  10371. E = E->IgnoreParenImpCasts();
  10372. const FunctionDecl *FD = nullptr;
  10373. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  10374. if (!DRE->getDecl()->getType()->isReferenceType())
  10375. return false;
  10376. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10377. if (!M->getMemberDecl()->getType()->isReferenceType())
  10378. return false;
  10379. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  10380. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  10381. return false;
  10382. FD = Call->getDirectCallee();
  10383. } else {
  10384. return false;
  10385. }
  10386. SemaRef.Diag(E->getExprLoc(), PD);
  10387. // If possible, point to location of function.
  10388. if (FD) {
  10389. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  10390. }
  10391. return true;
  10392. }
  10393. // Returns true if the SourceLocation is expanded from any macro body.
  10394. // Returns false if the SourceLocation is invalid, is from not in a macro
  10395. // expansion, or is from expanded from a top-level macro argument.
  10396. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  10397. if (Loc.isInvalid())
  10398. return false;
  10399. while (Loc.isMacroID()) {
  10400. if (SM.isMacroBodyExpansion(Loc))
  10401. return true;
  10402. Loc = SM.getImmediateMacroCallerLoc(Loc);
  10403. }
  10404. return false;
  10405. }
  10406. /// Diagnose pointers that are always non-null.
  10407. /// \param E the expression containing the pointer
  10408. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  10409. /// compared to a null pointer
  10410. /// \param IsEqual True when the comparison is equal to a null pointer
  10411. /// \param Range Extra SourceRange to highlight in the diagnostic
  10412. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  10413. Expr::NullPointerConstantKind NullKind,
  10414. bool IsEqual, SourceRange Range) {
  10415. if (!E)
  10416. return;
  10417. // Don't warn inside macros.
  10418. if (E->getExprLoc().isMacroID()) {
  10419. const SourceManager &SM = getSourceManager();
  10420. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  10421. IsInAnyMacroBody(SM, Range.getBegin()))
  10422. return;
  10423. }
  10424. E = E->IgnoreImpCasts();
  10425. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  10426. if (isa<CXXThisExpr>(E)) {
  10427. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  10428. : diag::warn_this_bool_conversion;
  10429. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  10430. return;
  10431. }
  10432. bool IsAddressOf = false;
  10433. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10434. if (UO->getOpcode() != UO_AddrOf)
  10435. return;
  10436. IsAddressOf = true;
  10437. E = UO->getSubExpr();
  10438. }
  10439. if (IsAddressOf) {
  10440. unsigned DiagID = IsCompare
  10441. ? diag::warn_address_of_reference_null_compare
  10442. : diag::warn_address_of_reference_bool_conversion;
  10443. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  10444. << IsEqual;
  10445. if (CheckForReference(*this, E, PD)) {
  10446. return;
  10447. }
  10448. }
  10449. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  10450. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  10451. std::string Str;
  10452. llvm::raw_string_ostream S(Str);
  10453. E->printPretty(S, nullptr, getPrintingPolicy());
  10454. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  10455. : diag::warn_cast_nonnull_to_bool;
  10456. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  10457. << E->getSourceRange() << Range << IsEqual;
  10458. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  10459. };
  10460. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  10461. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  10462. if (auto *Callee = Call->getDirectCallee()) {
  10463. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  10464. ComplainAboutNonnullParamOrCall(A);
  10465. return;
  10466. }
  10467. }
  10468. }
  10469. // Expect to find a single Decl. Skip anything more complicated.
  10470. ValueDecl *D = nullptr;
  10471. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  10472. D = R->getDecl();
  10473. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10474. D = M->getMemberDecl();
  10475. }
  10476. // Weak Decls can be null.
  10477. if (!D || D->isWeak())
  10478. return;
  10479. // Check for parameter decl with nonnull attribute
  10480. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  10481. if (getCurFunction() &&
  10482. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  10483. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  10484. ComplainAboutNonnullParamOrCall(A);
  10485. return;
  10486. }
  10487. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  10488. // Skip function template not specialized yet.
  10489. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  10490. return;
  10491. auto ParamIter = llvm::find(FD->parameters(), PV);
  10492. assert(ParamIter != FD->param_end());
  10493. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  10494. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  10495. if (!NonNull->args_size()) {
  10496. ComplainAboutNonnullParamOrCall(NonNull);
  10497. return;
  10498. }
  10499. for (const ParamIdx &ArgNo : NonNull->args()) {
  10500. if (ArgNo.getASTIndex() == ParamNo) {
  10501. ComplainAboutNonnullParamOrCall(NonNull);
  10502. return;
  10503. }
  10504. }
  10505. }
  10506. }
  10507. }
  10508. }
  10509. QualType T = D->getType();
  10510. const bool IsArray = T->isArrayType();
  10511. const bool IsFunction = T->isFunctionType();
  10512. // Address of function is used to silence the function warning.
  10513. if (IsAddressOf && IsFunction) {
  10514. return;
  10515. }
  10516. // Found nothing.
  10517. if (!IsAddressOf && !IsFunction && !IsArray)
  10518. return;
  10519. // Pretty print the expression for the diagnostic.
  10520. std::string Str;
  10521. llvm::raw_string_ostream S(Str);
  10522. E->printPretty(S, nullptr, getPrintingPolicy());
  10523. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  10524. : diag::warn_impcast_pointer_to_bool;
  10525. enum {
  10526. AddressOf,
  10527. FunctionPointer,
  10528. ArrayPointer
  10529. } DiagType;
  10530. if (IsAddressOf)
  10531. DiagType = AddressOf;
  10532. else if (IsFunction)
  10533. DiagType = FunctionPointer;
  10534. else if (IsArray)
  10535. DiagType = ArrayPointer;
  10536. else
  10537. llvm_unreachable("Could not determine diagnostic.");
  10538. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  10539. << Range << IsEqual;
  10540. if (!IsFunction)
  10541. return;
  10542. // Suggest '&' to silence the function warning.
  10543. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  10544. << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
  10545. // Check to see if '()' fixit should be emitted.
  10546. QualType ReturnType;
  10547. UnresolvedSet<4> NonTemplateOverloads;
  10548. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  10549. if (ReturnType.isNull())
  10550. return;
  10551. if (IsCompare) {
  10552. // There are two cases here. If there is null constant, the only suggest
  10553. // for a pointer return type. If the null is 0, then suggest if the return
  10554. // type is a pointer or an integer type.
  10555. if (!ReturnType->isPointerType()) {
  10556. if (NullKind == Expr::NPCK_ZeroExpression ||
  10557. NullKind == Expr::NPCK_ZeroLiteral) {
  10558. if (!ReturnType->isIntegerType())
  10559. return;
  10560. } else {
  10561. return;
  10562. }
  10563. }
  10564. } else { // !IsCompare
  10565. // For function to bool, only suggest if the function pointer has bool
  10566. // return type.
  10567. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  10568. return;
  10569. }
  10570. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  10571. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
  10572. }
  10573. /// Diagnoses "dangerous" implicit conversions within the given
  10574. /// expression (which is a full expression). Implements -Wconversion
  10575. /// and -Wsign-compare.
  10576. ///
  10577. /// \param CC the "context" location of the implicit conversion, i.e.
  10578. /// the most location of the syntactic entity requiring the implicit
  10579. /// conversion
  10580. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  10581. // Don't diagnose in unevaluated contexts.
  10582. if (isUnevaluatedContext())
  10583. return;
  10584. // Don't diagnose for value- or type-dependent expressions.
  10585. if (E->isTypeDependent() || E->isValueDependent())
  10586. return;
  10587. // Check for array bounds violations in cases where the check isn't triggered
  10588. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  10589. // ArraySubscriptExpr is on the RHS of a variable initialization.
  10590. CheckArrayAccess(E);
  10591. // This is not the right CC for (e.g.) a variable initialization.
  10592. AnalyzeImplicitConversions(*this, E, CC);
  10593. }
  10594. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  10595. /// Input argument E is a logical expression.
  10596. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  10597. ::CheckBoolLikeConversion(*this, E, CC);
  10598. }
  10599. /// Diagnose when expression is an integer constant expression and its evaluation
  10600. /// results in integer overflow
  10601. void Sema::CheckForIntOverflow (Expr *E) {
  10602. // Use a work list to deal with nested struct initializers.
  10603. SmallVector<Expr *, 2> Exprs(1, E);
  10604. do {
  10605. Expr *OriginalE = Exprs.pop_back_val();
  10606. Expr *E = OriginalE->IgnoreParenCasts();
  10607. if (isa<BinaryOperator>(E)) {
  10608. E->EvaluateForOverflow(Context);
  10609. continue;
  10610. }
  10611. if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
  10612. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  10613. else if (isa<ObjCBoxedExpr>(OriginalE))
  10614. E->EvaluateForOverflow(Context);
  10615. else if (auto Call = dyn_cast<CallExpr>(E))
  10616. Exprs.append(Call->arg_begin(), Call->arg_end());
  10617. else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
  10618. Exprs.append(Message->arg_begin(), Message->arg_end());
  10619. } while (!Exprs.empty());
  10620. }
  10621. namespace {
  10622. /// Visitor for expressions which looks for unsequenced operations on the
  10623. /// same object.
  10624. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  10625. using Base = EvaluatedExprVisitor<SequenceChecker>;
  10626. /// A tree of sequenced regions within an expression. Two regions are
  10627. /// unsequenced if one is an ancestor or a descendent of the other. When we
  10628. /// finish processing an expression with sequencing, such as a comma
  10629. /// expression, we fold its tree nodes into its parent, since they are
  10630. /// unsequenced with respect to nodes we will visit later.
  10631. class SequenceTree {
  10632. struct Value {
  10633. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  10634. unsigned Parent : 31;
  10635. unsigned Merged : 1;
  10636. };
  10637. SmallVector<Value, 8> Values;
  10638. public:
  10639. /// A region within an expression which may be sequenced with respect
  10640. /// to some other region.
  10641. class Seq {
  10642. friend class SequenceTree;
  10643. unsigned Index;
  10644. explicit Seq(unsigned N) : Index(N) {}
  10645. public:
  10646. Seq() : Index(0) {}
  10647. };
  10648. SequenceTree() { Values.push_back(Value(0)); }
  10649. Seq root() const { return Seq(0); }
  10650. /// Create a new sequence of operations, which is an unsequenced
  10651. /// subset of \p Parent. This sequence of operations is sequenced with
  10652. /// respect to other children of \p Parent.
  10653. Seq allocate(Seq Parent) {
  10654. Values.push_back(Value(Parent.Index));
  10655. return Seq(Values.size() - 1);
  10656. }
  10657. /// Merge a sequence of operations into its parent.
  10658. void merge(Seq S) {
  10659. Values[S.Index].Merged = true;
  10660. }
  10661. /// Determine whether two operations are unsequenced. This operation
  10662. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  10663. /// should have been merged into its parent as appropriate.
  10664. bool isUnsequenced(Seq Cur, Seq Old) {
  10665. unsigned C = representative(Cur.Index);
  10666. unsigned Target = representative(Old.Index);
  10667. while (C >= Target) {
  10668. if (C == Target)
  10669. return true;
  10670. C = Values[C].Parent;
  10671. }
  10672. return false;
  10673. }
  10674. private:
  10675. /// Pick a representative for a sequence.
  10676. unsigned representative(unsigned K) {
  10677. if (Values[K].Merged)
  10678. // Perform path compression as we go.
  10679. return Values[K].Parent = representative(Values[K].Parent);
  10680. return K;
  10681. }
  10682. };
  10683. /// An object for which we can track unsequenced uses.
  10684. using Object = NamedDecl *;
  10685. /// Different flavors of object usage which we track. We only track the
  10686. /// least-sequenced usage of each kind.
  10687. enum UsageKind {
  10688. /// A read of an object. Multiple unsequenced reads are OK.
  10689. UK_Use,
  10690. /// A modification of an object which is sequenced before the value
  10691. /// computation of the expression, such as ++n in C++.
  10692. UK_ModAsValue,
  10693. /// A modification of an object which is not sequenced before the value
  10694. /// computation of the expression, such as n++.
  10695. UK_ModAsSideEffect,
  10696. UK_Count = UK_ModAsSideEffect + 1
  10697. };
  10698. struct Usage {
  10699. Expr *Use;
  10700. SequenceTree::Seq Seq;
  10701. Usage() : Use(nullptr), Seq() {}
  10702. };
  10703. struct UsageInfo {
  10704. Usage Uses[UK_Count];
  10705. /// Have we issued a diagnostic for this variable already?
  10706. bool Diagnosed;
  10707. UsageInfo() : Uses(), Diagnosed(false) {}
  10708. };
  10709. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  10710. Sema &SemaRef;
  10711. /// Sequenced regions within the expression.
  10712. SequenceTree Tree;
  10713. /// Declaration modifications and references which we have seen.
  10714. UsageInfoMap UsageMap;
  10715. /// The region we are currently within.
  10716. SequenceTree::Seq Region;
  10717. /// Filled in with declarations which were modified as a side-effect
  10718. /// (that is, post-increment operations).
  10719. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  10720. /// Expressions to check later. We defer checking these to reduce
  10721. /// stack usage.
  10722. SmallVectorImpl<Expr *> &WorkList;
  10723. /// RAII object wrapping the visitation of a sequenced subexpression of an
  10724. /// expression. At the end of this process, the side-effects of the evaluation
  10725. /// become sequenced with respect to the value computation of the result, so
  10726. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  10727. /// UK_ModAsValue.
  10728. struct SequencedSubexpression {
  10729. SequencedSubexpression(SequenceChecker &Self)
  10730. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  10731. Self.ModAsSideEffect = &ModAsSideEffect;
  10732. }
  10733. ~SequencedSubexpression() {
  10734. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  10735. UsageInfo &U = Self.UsageMap[M.first];
  10736. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  10737. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  10738. SideEffectUsage = M.second;
  10739. }
  10740. Self.ModAsSideEffect = OldModAsSideEffect;
  10741. }
  10742. SequenceChecker &Self;
  10743. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  10744. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  10745. };
  10746. /// RAII object wrapping the visitation of a subexpression which we might
  10747. /// choose to evaluate as a constant. If any subexpression is evaluated and
  10748. /// found to be non-constant, this allows us to suppress the evaluation of
  10749. /// the outer expression.
  10750. class EvaluationTracker {
  10751. public:
  10752. EvaluationTracker(SequenceChecker &Self)
  10753. : Self(Self), Prev(Self.EvalTracker) {
  10754. Self.EvalTracker = this;
  10755. }
  10756. ~EvaluationTracker() {
  10757. Self.EvalTracker = Prev;
  10758. if (Prev)
  10759. Prev->EvalOK &= EvalOK;
  10760. }
  10761. bool evaluate(const Expr *E, bool &Result) {
  10762. if (!EvalOK || E->isValueDependent())
  10763. return false;
  10764. EvalOK = E->EvaluateAsBooleanCondition(
  10765. Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
  10766. return EvalOK;
  10767. }
  10768. private:
  10769. SequenceChecker &Self;
  10770. EvaluationTracker *Prev;
  10771. bool EvalOK = true;
  10772. } *EvalTracker = nullptr;
  10773. /// Find the object which is produced by the specified expression,
  10774. /// if any.
  10775. Object getObject(Expr *E, bool Mod) const {
  10776. E = E->IgnoreParenCasts();
  10777. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10778. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  10779. return getObject(UO->getSubExpr(), Mod);
  10780. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10781. if (BO->getOpcode() == BO_Comma)
  10782. return getObject(BO->getRHS(), Mod);
  10783. if (Mod && BO->isAssignmentOp())
  10784. return getObject(BO->getLHS(), Mod);
  10785. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  10786. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  10787. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  10788. return ME->getMemberDecl();
  10789. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10790. // FIXME: If this is a reference, map through to its value.
  10791. return DRE->getDecl();
  10792. return nullptr;
  10793. }
  10794. /// Note that an object was modified or used by an expression.
  10795. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  10796. Usage &U = UI.Uses[UK];
  10797. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  10798. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  10799. ModAsSideEffect->push_back(std::make_pair(O, U));
  10800. U.Use = Ref;
  10801. U.Seq = Region;
  10802. }
  10803. }
  10804. /// Check whether a modification or use conflicts with a prior usage.
  10805. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  10806. bool IsModMod) {
  10807. if (UI.Diagnosed)
  10808. return;
  10809. const Usage &U = UI.Uses[OtherKind];
  10810. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  10811. return;
  10812. Expr *Mod = U.Use;
  10813. Expr *ModOrUse = Ref;
  10814. if (OtherKind == UK_Use)
  10815. std::swap(Mod, ModOrUse);
  10816. SemaRef.DiagRuntimeBehavior(
  10817. Mod->getExprLoc(), {Mod, ModOrUse},
  10818. SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
  10819. : diag::warn_unsequenced_mod_use)
  10820. << O << SourceRange(ModOrUse->getExprLoc()));
  10821. UI.Diagnosed = true;
  10822. }
  10823. void notePreUse(Object O, Expr *Use) {
  10824. UsageInfo &U = UsageMap[O];
  10825. // Uses conflict with other modifications.
  10826. checkUsage(O, U, Use, UK_ModAsValue, false);
  10827. }
  10828. void notePostUse(Object O, Expr *Use) {
  10829. UsageInfo &U = UsageMap[O];
  10830. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  10831. addUsage(U, O, Use, UK_Use);
  10832. }
  10833. void notePreMod(Object O, Expr *Mod) {
  10834. UsageInfo &U = UsageMap[O];
  10835. // Modifications conflict with other modifications and with uses.
  10836. checkUsage(O, U, Mod, UK_ModAsValue, true);
  10837. checkUsage(O, U, Mod, UK_Use, false);
  10838. }
  10839. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  10840. UsageInfo &U = UsageMap[O];
  10841. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  10842. addUsage(U, O, Use, UK);
  10843. }
  10844. public:
  10845. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  10846. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  10847. Visit(E);
  10848. }
  10849. void VisitStmt(Stmt *S) {
  10850. // Skip all statements which aren't expressions for now.
  10851. }
  10852. void VisitExpr(Expr *E) {
  10853. // By default, just recurse to evaluated subexpressions.
  10854. Base::VisitStmt(E);
  10855. }
  10856. void VisitCastExpr(CastExpr *E) {
  10857. Object O = Object();
  10858. if (E->getCastKind() == CK_LValueToRValue)
  10859. O = getObject(E->getSubExpr(), false);
  10860. if (O)
  10861. notePreUse(O, E);
  10862. VisitExpr(E);
  10863. if (O)
  10864. notePostUse(O, E);
  10865. }
  10866. void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
  10867. SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
  10868. SequenceTree::Seq AfterRegion = Tree.allocate(Region);
  10869. SequenceTree::Seq OldRegion = Region;
  10870. {
  10871. SequencedSubexpression SeqBefore(*this);
  10872. Region = BeforeRegion;
  10873. Visit(SequencedBefore);
  10874. }
  10875. Region = AfterRegion;
  10876. Visit(SequencedAfter);
  10877. Region = OldRegion;
  10878. Tree.merge(BeforeRegion);
  10879. Tree.merge(AfterRegion);
  10880. }
  10881. void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
  10882. // C++17 [expr.sub]p1:
  10883. // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
  10884. // expression E1 is sequenced before the expression E2.
  10885. if (SemaRef.getLangOpts().CPlusPlus17)
  10886. VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
  10887. else
  10888. Base::VisitStmt(ASE);
  10889. }
  10890. void VisitBinComma(BinaryOperator *BO) {
  10891. // C++11 [expr.comma]p1:
  10892. // Every value computation and side effect associated with the left
  10893. // expression is sequenced before every value computation and side
  10894. // effect associated with the right expression.
  10895. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  10896. }
  10897. void VisitBinAssign(BinaryOperator *BO) {
  10898. // The modification is sequenced after the value computation of the LHS
  10899. // and RHS, so check it before inspecting the operands and update the
  10900. // map afterwards.
  10901. Object O = getObject(BO->getLHS(), true);
  10902. if (!O)
  10903. return VisitExpr(BO);
  10904. notePreMod(O, BO);
  10905. // C++11 [expr.ass]p7:
  10906. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  10907. // only once.
  10908. //
  10909. // Therefore, for a compound assignment operator, O is considered used
  10910. // everywhere except within the evaluation of E1 itself.
  10911. if (isa<CompoundAssignOperator>(BO))
  10912. notePreUse(O, BO);
  10913. Visit(BO->getLHS());
  10914. if (isa<CompoundAssignOperator>(BO))
  10915. notePostUse(O, BO);
  10916. Visit(BO->getRHS());
  10917. // C++11 [expr.ass]p1:
  10918. // the assignment is sequenced [...] before the value computation of the
  10919. // assignment expression.
  10920. // C11 6.5.16/3 has no such rule.
  10921. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  10922. : UK_ModAsSideEffect);
  10923. }
  10924. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  10925. VisitBinAssign(CAO);
  10926. }
  10927. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10928. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10929. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  10930. Object O = getObject(UO->getSubExpr(), true);
  10931. if (!O)
  10932. return VisitExpr(UO);
  10933. notePreMod(O, UO);
  10934. Visit(UO->getSubExpr());
  10935. // C++11 [expr.pre.incr]p1:
  10936. // the expression ++x is equivalent to x+=1
  10937. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  10938. : UK_ModAsSideEffect);
  10939. }
  10940. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  10941. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  10942. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  10943. Object O = getObject(UO->getSubExpr(), true);
  10944. if (!O)
  10945. return VisitExpr(UO);
  10946. notePreMod(O, UO);
  10947. Visit(UO->getSubExpr());
  10948. notePostMod(O, UO, UK_ModAsSideEffect);
  10949. }
  10950. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  10951. void VisitBinLOr(BinaryOperator *BO) {
  10952. // The side-effects of the LHS of an '&&' are sequenced before the
  10953. // value computation of the RHS, and hence before the value computation
  10954. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  10955. // as if they were unconditionally sequenced.
  10956. EvaluationTracker Eval(*this);
  10957. {
  10958. SequencedSubexpression Sequenced(*this);
  10959. Visit(BO->getLHS());
  10960. }
  10961. bool Result;
  10962. if (Eval.evaluate(BO->getLHS(), Result)) {
  10963. if (!Result)
  10964. Visit(BO->getRHS());
  10965. } else {
  10966. // Check for unsequenced operations in the RHS, treating it as an
  10967. // entirely separate evaluation.
  10968. //
  10969. // FIXME: If there are operations in the RHS which are unsequenced
  10970. // with respect to operations outside the RHS, and those operations
  10971. // are unconditionally evaluated, diagnose them.
  10972. WorkList.push_back(BO->getRHS());
  10973. }
  10974. }
  10975. void VisitBinLAnd(BinaryOperator *BO) {
  10976. EvaluationTracker Eval(*this);
  10977. {
  10978. SequencedSubexpression Sequenced(*this);
  10979. Visit(BO->getLHS());
  10980. }
  10981. bool Result;
  10982. if (Eval.evaluate(BO->getLHS(), Result)) {
  10983. if (Result)
  10984. Visit(BO->getRHS());
  10985. } else {
  10986. WorkList.push_back(BO->getRHS());
  10987. }
  10988. }
  10989. // Only visit the condition, unless we can be sure which subexpression will
  10990. // be chosen.
  10991. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  10992. EvaluationTracker Eval(*this);
  10993. {
  10994. SequencedSubexpression Sequenced(*this);
  10995. Visit(CO->getCond());
  10996. }
  10997. bool Result;
  10998. if (Eval.evaluate(CO->getCond(), Result))
  10999. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  11000. else {
  11001. WorkList.push_back(CO->getTrueExpr());
  11002. WorkList.push_back(CO->getFalseExpr());
  11003. }
  11004. }
  11005. void VisitCallExpr(CallExpr *CE) {
  11006. // C++11 [intro.execution]p15:
  11007. // When calling a function [...], every value computation and side effect
  11008. // associated with any argument expression, or with the postfix expression
  11009. // designating the called function, is sequenced before execution of every
  11010. // expression or statement in the body of the function [and thus before
  11011. // the value computation of its result].
  11012. SequencedSubexpression Sequenced(*this);
  11013. Base::VisitCallExpr(CE);
  11014. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  11015. }
  11016. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  11017. // This is a call, so all subexpressions are sequenced before the result.
  11018. SequencedSubexpression Sequenced(*this);
  11019. if (!CCE->isListInitialization())
  11020. return VisitExpr(CCE);
  11021. // In C++11, list initializations are sequenced.
  11022. SmallVector<SequenceTree::Seq, 32> Elts;
  11023. SequenceTree::Seq Parent = Region;
  11024. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  11025. E = CCE->arg_end();
  11026. I != E; ++I) {
  11027. Region = Tree.allocate(Parent);
  11028. Elts.push_back(Region);
  11029. Visit(*I);
  11030. }
  11031. // Forget that the initializers are sequenced.
  11032. Region = Parent;
  11033. for (unsigned I = 0; I < Elts.size(); ++I)
  11034. Tree.merge(Elts[I]);
  11035. }
  11036. void VisitInitListExpr(InitListExpr *ILE) {
  11037. if (!SemaRef.getLangOpts().CPlusPlus11)
  11038. return VisitExpr(ILE);
  11039. // In C++11, list initializations are sequenced.
  11040. SmallVector<SequenceTree::Seq, 32> Elts;
  11041. SequenceTree::Seq Parent = Region;
  11042. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  11043. Expr *E = ILE->getInit(I);
  11044. if (!E) continue;
  11045. Region = Tree.allocate(Parent);
  11046. Elts.push_back(Region);
  11047. Visit(E);
  11048. }
  11049. // Forget that the initializers are sequenced.
  11050. Region = Parent;
  11051. for (unsigned I = 0; I < Elts.size(); ++I)
  11052. Tree.merge(Elts[I]);
  11053. }
  11054. };
  11055. } // namespace
  11056. void Sema::CheckUnsequencedOperations(Expr *E) {
  11057. SmallVector<Expr *, 8> WorkList;
  11058. WorkList.push_back(E);
  11059. while (!WorkList.empty()) {
  11060. Expr *Item = WorkList.pop_back_val();
  11061. SequenceChecker(*this, Item, WorkList);
  11062. }
  11063. }
  11064. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  11065. bool IsConstexpr) {
  11066. llvm::SaveAndRestore<bool> ConstantContext(
  11067. isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
  11068. CheckImplicitConversions(E, CheckLoc);
  11069. if (!E->isInstantiationDependent())
  11070. CheckUnsequencedOperations(E);
  11071. if (!IsConstexpr && !E->isValueDependent())
  11072. CheckForIntOverflow(E);
  11073. DiagnoseMisalignedMembers();
  11074. }
  11075. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  11076. FieldDecl *BitField,
  11077. Expr *Init) {
  11078. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  11079. }
  11080. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  11081. SourceLocation Loc) {
  11082. if (!PType->isVariablyModifiedType())
  11083. return;
  11084. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  11085. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  11086. return;
  11087. }
  11088. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  11089. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  11090. return;
  11091. }
  11092. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  11093. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  11094. return;
  11095. }
  11096. const ArrayType *AT = S.Context.getAsArrayType(PType);
  11097. if (!AT)
  11098. return;
  11099. if (AT->getSizeModifier() != ArrayType::Star) {
  11100. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  11101. return;
  11102. }
  11103. S.Diag(Loc, diag::err_array_star_in_function_definition);
  11104. }
  11105. /// CheckParmsForFunctionDef - Check that the parameters of the given
  11106. /// function are appropriate for the definition of a function. This
  11107. /// takes care of any checks that cannot be performed on the
  11108. /// declaration itself, e.g., that the types of each of the function
  11109. /// parameters are complete.
  11110. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  11111. bool CheckParameterNames) {
  11112. bool HasInvalidParm = false;
  11113. for (ParmVarDecl *Param : Parameters) {
  11114. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  11115. // function declarator that is part of a function definition of
  11116. // that function shall not have incomplete type.
  11117. //
  11118. // This is also C++ [dcl.fct]p6.
  11119. if (!Param->isInvalidDecl() &&
  11120. RequireCompleteType(Param->getLocation(), Param->getType(),
  11121. diag::err_typecheck_decl_incomplete_type)) {
  11122. Param->setInvalidDecl();
  11123. HasInvalidParm = true;
  11124. }
  11125. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  11126. // declaration of each parameter shall include an identifier.
  11127. if (CheckParameterNames &&
  11128. Param->getIdentifier() == nullptr &&
  11129. !Param->isImplicit() &&
  11130. !getLangOpts().CPlusPlus)
  11131. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  11132. // C99 6.7.5.3p12:
  11133. // If the function declarator is not part of a definition of that
  11134. // function, parameters may have incomplete type and may use the [*]
  11135. // notation in their sequences of declarator specifiers to specify
  11136. // variable length array types.
  11137. QualType PType = Param->getOriginalType();
  11138. // FIXME: This diagnostic should point the '[*]' if source-location
  11139. // information is added for it.
  11140. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  11141. // If the parameter is a c++ class type and it has to be destructed in the
  11142. // callee function, declare the destructor so that it can be called by the
  11143. // callee function. Do not perform any direct access check on the dtor here.
  11144. if (!Param->isInvalidDecl()) {
  11145. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  11146. if (!ClassDecl->isInvalidDecl() &&
  11147. !ClassDecl->hasIrrelevantDestructor() &&
  11148. !ClassDecl->isDependentContext() &&
  11149. ClassDecl->isParamDestroyedInCallee()) {
  11150. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  11151. MarkFunctionReferenced(Param->getLocation(), Destructor);
  11152. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  11153. }
  11154. }
  11155. }
  11156. // Parameters with the pass_object_size attribute only need to be marked
  11157. // constant at function definitions. Because we lack information about
  11158. // whether we're on a declaration or definition when we're instantiating the
  11159. // attribute, we need to check for constness here.
  11160. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  11161. if (!Param->getType().isConstQualified())
  11162. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  11163. << Attr->getSpelling() << 1;
  11164. // Check for parameter names shadowing fields from the class.
  11165. if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
  11166. // The owning context for the parameter should be the function, but we
  11167. // want to see if this function's declaration context is a record.
  11168. DeclContext *DC = Param->getDeclContext();
  11169. if (DC && DC->isFunctionOrMethod()) {
  11170. if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
  11171. CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
  11172. RD, /*DeclIsField*/ false);
  11173. }
  11174. }
  11175. }
  11176. return HasInvalidParm;
  11177. }
  11178. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  11179. /// or MemberExpr.
  11180. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  11181. ASTContext &Context) {
  11182. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  11183. return Context.getDeclAlign(DRE->getDecl());
  11184. if (const auto *ME = dyn_cast<MemberExpr>(E))
  11185. return Context.getDeclAlign(ME->getMemberDecl());
  11186. return TypeAlign;
  11187. }
  11188. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  11189. /// pointer cast increases the alignment requirements.
  11190. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  11191. // This is actually a lot of work to potentially be doing on every
  11192. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  11193. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  11194. return;
  11195. // Ignore dependent types.
  11196. if (T->isDependentType() || Op->getType()->isDependentType())
  11197. return;
  11198. // Require that the destination be a pointer type.
  11199. const PointerType *DestPtr = T->getAs<PointerType>();
  11200. if (!DestPtr) return;
  11201. // If the destination has alignment 1, we're done.
  11202. QualType DestPointee = DestPtr->getPointeeType();
  11203. if (DestPointee->isIncompleteType()) return;
  11204. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  11205. if (DestAlign.isOne()) return;
  11206. // Require that the source be a pointer type.
  11207. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  11208. if (!SrcPtr) return;
  11209. QualType SrcPointee = SrcPtr->getPointeeType();
  11210. // Whitelist casts from cv void*. We already implicitly
  11211. // whitelisted casts to cv void*, since they have alignment 1.
  11212. // Also whitelist casts involving incomplete types, which implicitly
  11213. // includes 'void'.
  11214. if (SrcPointee->isIncompleteType()) return;
  11215. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  11216. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  11217. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  11218. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  11219. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  11220. if (UO->getOpcode() == UO_AddrOf)
  11221. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  11222. }
  11223. if (SrcAlign >= DestAlign) return;
  11224. Diag(TRange.getBegin(), diag::warn_cast_align)
  11225. << Op->getType() << T
  11226. << static_cast<unsigned>(SrcAlign.getQuantity())
  11227. << static_cast<unsigned>(DestAlign.getQuantity())
  11228. << TRange << Op->getSourceRange();
  11229. }
  11230. /// Check whether this array fits the idiom of a size-one tail padded
  11231. /// array member of a struct.
  11232. ///
  11233. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  11234. /// commonly used to emulate flexible arrays in C89 code.
  11235. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  11236. const NamedDecl *ND) {
  11237. if (Size != 1 || !ND) return false;
  11238. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  11239. if (!FD) return false;
  11240. // Don't consider sizes resulting from macro expansions or template argument
  11241. // substitution to form C89 tail-padded arrays.
  11242. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  11243. while (TInfo) {
  11244. TypeLoc TL = TInfo->getTypeLoc();
  11245. // Look through typedefs.
  11246. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  11247. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  11248. TInfo = TDL->getTypeSourceInfo();
  11249. continue;
  11250. }
  11251. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  11252. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  11253. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  11254. return false;
  11255. }
  11256. break;
  11257. }
  11258. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  11259. if (!RD) return false;
  11260. if (RD->isUnion()) return false;
  11261. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  11262. if (!CRD->isStandardLayout()) return false;
  11263. }
  11264. // See if this is the last field decl in the record.
  11265. const Decl *D = FD;
  11266. while ((D = D->getNextDeclInContext()))
  11267. if (isa<FieldDecl>(D))
  11268. return false;
  11269. return true;
  11270. }
  11271. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  11272. const ArraySubscriptExpr *ASE,
  11273. bool AllowOnePastEnd, bool IndexNegated) {
  11274. // Already diagnosed by the constant evaluator.
  11275. if (isConstantEvaluated())
  11276. return;
  11277. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  11278. if (IndexExpr->isValueDependent())
  11279. return;
  11280. const Type *EffectiveType =
  11281. BaseExpr->getType()->getPointeeOrArrayElementType();
  11282. BaseExpr = BaseExpr->IgnoreParenCasts();
  11283. const ConstantArrayType *ArrayTy =
  11284. Context.getAsConstantArrayType(BaseExpr->getType());
  11285. if (!ArrayTy)
  11286. return;
  11287. const Type *BaseType = ArrayTy->getElementType().getTypePtr();
  11288. if (EffectiveType->isDependentType() || BaseType->isDependentType())
  11289. return;
  11290. Expr::EvalResult Result;
  11291. if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
  11292. return;
  11293. llvm::APSInt index = Result.Val.getInt();
  11294. if (IndexNegated)
  11295. index = -index;
  11296. const NamedDecl *ND = nullptr;
  11297. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11298. ND = DRE->getDecl();
  11299. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11300. ND = ME->getMemberDecl();
  11301. if (index.isUnsigned() || !index.isNegative()) {
  11302. // It is possible that the type of the base expression after
  11303. // IgnoreParenCasts is incomplete, even though the type of the base
  11304. // expression before IgnoreParenCasts is complete (see PR39746 for an
  11305. // example). In this case we have no information about whether the array
  11306. // access exceeds the array bounds. However we can still diagnose an array
  11307. // access which precedes the array bounds.
  11308. if (BaseType->isIncompleteType())
  11309. return;
  11310. llvm::APInt size = ArrayTy->getSize();
  11311. if (!size.isStrictlyPositive())
  11312. return;
  11313. if (BaseType != EffectiveType) {
  11314. // Make sure we're comparing apples to apples when comparing index to size
  11315. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  11316. uint64_t array_typesize = Context.getTypeSize(BaseType);
  11317. // Handle ptrarith_typesize being zero, such as when casting to void*
  11318. if (!ptrarith_typesize) ptrarith_typesize = 1;
  11319. if (ptrarith_typesize != array_typesize) {
  11320. // There's a cast to a different size type involved
  11321. uint64_t ratio = array_typesize / ptrarith_typesize;
  11322. // TODO: Be smarter about handling cases where array_typesize is not a
  11323. // multiple of ptrarith_typesize
  11324. if (ptrarith_typesize * ratio == array_typesize)
  11325. size *= llvm::APInt(size.getBitWidth(), ratio);
  11326. }
  11327. }
  11328. if (size.getBitWidth() > index.getBitWidth())
  11329. index = index.zext(size.getBitWidth());
  11330. else if (size.getBitWidth() < index.getBitWidth())
  11331. size = size.zext(index.getBitWidth());
  11332. // For array subscripting the index must be less than size, but for pointer
  11333. // arithmetic also allow the index (offset) to be equal to size since
  11334. // computing the next address after the end of the array is legal and
  11335. // commonly done e.g. in C++ iterators and range-based for loops.
  11336. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  11337. return;
  11338. // Also don't warn for arrays of size 1 which are members of some
  11339. // structure. These are often used to approximate flexible arrays in C89
  11340. // code.
  11341. if (IsTailPaddedMemberArray(*this, size, ND))
  11342. return;
  11343. // Suppress the warning if the subscript expression (as identified by the
  11344. // ']' location) and the index expression are both from macro expansions
  11345. // within a system header.
  11346. if (ASE) {
  11347. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  11348. ASE->getRBracketLoc());
  11349. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  11350. SourceLocation IndexLoc =
  11351. SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
  11352. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  11353. return;
  11354. }
  11355. }
  11356. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  11357. if (ASE)
  11358. DiagID = diag::warn_array_index_exceeds_bounds;
  11359. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11360. PDiag(DiagID) << index.toString(10, true)
  11361. << size.toString(10, true)
  11362. << (unsigned)size.getLimitedValue(~0U)
  11363. << IndexExpr->getSourceRange());
  11364. } else {
  11365. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  11366. if (!ASE) {
  11367. DiagID = diag::warn_ptr_arith_precedes_bounds;
  11368. if (index.isNegative()) index = -index;
  11369. }
  11370. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11371. PDiag(DiagID) << index.toString(10, true)
  11372. << IndexExpr->getSourceRange());
  11373. }
  11374. if (!ND) {
  11375. // Try harder to find a NamedDecl to point at in the note.
  11376. while (const ArraySubscriptExpr *ASE =
  11377. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  11378. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  11379. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11380. ND = DRE->getDecl();
  11381. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11382. ND = ME->getMemberDecl();
  11383. }
  11384. if (ND)
  11385. DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
  11386. PDiag(diag::note_array_index_out_of_bounds)
  11387. << ND->getDeclName());
  11388. }
  11389. void Sema::CheckArrayAccess(const Expr *expr) {
  11390. int AllowOnePastEnd = 0;
  11391. while (expr) {
  11392. expr = expr->IgnoreParenImpCasts();
  11393. switch (expr->getStmtClass()) {
  11394. case Stmt::ArraySubscriptExprClass: {
  11395. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  11396. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  11397. AllowOnePastEnd > 0);
  11398. expr = ASE->getBase();
  11399. break;
  11400. }
  11401. case Stmt::MemberExprClass: {
  11402. expr = cast<MemberExpr>(expr)->getBase();
  11403. break;
  11404. }
  11405. case Stmt::OMPArraySectionExprClass: {
  11406. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  11407. if (ASE->getLowerBound())
  11408. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  11409. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  11410. return;
  11411. }
  11412. case Stmt::UnaryOperatorClass: {
  11413. // Only unwrap the * and & unary operators
  11414. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  11415. expr = UO->getSubExpr();
  11416. switch (UO->getOpcode()) {
  11417. case UO_AddrOf:
  11418. AllowOnePastEnd++;
  11419. break;
  11420. case UO_Deref:
  11421. AllowOnePastEnd--;
  11422. break;
  11423. default:
  11424. return;
  11425. }
  11426. break;
  11427. }
  11428. case Stmt::ConditionalOperatorClass: {
  11429. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  11430. if (const Expr *lhs = cond->getLHS())
  11431. CheckArrayAccess(lhs);
  11432. if (const Expr *rhs = cond->getRHS())
  11433. CheckArrayAccess(rhs);
  11434. return;
  11435. }
  11436. case Stmt::CXXOperatorCallExprClass: {
  11437. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  11438. for (const auto *Arg : OCE->arguments())
  11439. CheckArrayAccess(Arg);
  11440. return;
  11441. }
  11442. default:
  11443. return;
  11444. }
  11445. }
  11446. }
  11447. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  11448. namespace {
  11449. struct RetainCycleOwner {
  11450. VarDecl *Variable = nullptr;
  11451. SourceRange Range;
  11452. SourceLocation Loc;
  11453. bool Indirect = false;
  11454. RetainCycleOwner() = default;
  11455. void setLocsFrom(Expr *e) {
  11456. Loc = e->getExprLoc();
  11457. Range = e->getSourceRange();
  11458. }
  11459. };
  11460. } // namespace
  11461. /// Consider whether capturing the given variable can possibly lead to
  11462. /// a retain cycle.
  11463. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  11464. // In ARC, it's captured strongly iff the variable has __strong
  11465. // lifetime. In MRR, it's captured strongly if the variable is
  11466. // __block and has an appropriate type.
  11467. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11468. return false;
  11469. owner.Variable = var;
  11470. if (ref)
  11471. owner.setLocsFrom(ref);
  11472. return true;
  11473. }
  11474. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11475. while (true) {
  11476. e = e->IgnoreParens();
  11477. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  11478. switch (cast->getCastKind()) {
  11479. case CK_BitCast:
  11480. case CK_LValueBitCast:
  11481. case CK_LValueToRValue:
  11482. case CK_ARCReclaimReturnedObject:
  11483. e = cast->getSubExpr();
  11484. continue;
  11485. default:
  11486. return false;
  11487. }
  11488. }
  11489. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  11490. ObjCIvarDecl *ivar = ref->getDecl();
  11491. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11492. return false;
  11493. // Try to find a retain cycle in the base.
  11494. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  11495. return false;
  11496. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  11497. owner.Indirect = true;
  11498. return true;
  11499. }
  11500. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  11501. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  11502. if (!var) return false;
  11503. return considerVariable(var, ref, owner);
  11504. }
  11505. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  11506. if (member->isArrow()) return false;
  11507. // Don't count this as an indirect ownership.
  11508. e = member->getBase();
  11509. continue;
  11510. }
  11511. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  11512. // Only pay attention to pseudo-objects on property references.
  11513. ObjCPropertyRefExpr *pre
  11514. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  11515. ->IgnoreParens());
  11516. if (!pre) return false;
  11517. if (pre->isImplicitProperty()) return false;
  11518. ObjCPropertyDecl *property = pre->getExplicitProperty();
  11519. if (!property->isRetaining() &&
  11520. !(property->getPropertyIvarDecl() &&
  11521. property->getPropertyIvarDecl()->getType()
  11522. .getObjCLifetime() == Qualifiers::OCL_Strong))
  11523. return false;
  11524. owner.Indirect = true;
  11525. if (pre->isSuperReceiver()) {
  11526. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  11527. if (!owner.Variable)
  11528. return false;
  11529. owner.Loc = pre->getLocation();
  11530. owner.Range = pre->getSourceRange();
  11531. return true;
  11532. }
  11533. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  11534. ->getSourceExpr());
  11535. continue;
  11536. }
  11537. // Array ivars?
  11538. return false;
  11539. }
  11540. }
  11541. namespace {
  11542. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  11543. ASTContext &Context;
  11544. VarDecl *Variable;
  11545. Expr *Capturer = nullptr;
  11546. bool VarWillBeReased = false;
  11547. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  11548. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  11549. Context(Context), Variable(variable) {}
  11550. void VisitDeclRefExpr(DeclRefExpr *ref) {
  11551. if (ref->getDecl() == Variable && !Capturer)
  11552. Capturer = ref;
  11553. }
  11554. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  11555. if (Capturer) return;
  11556. Visit(ref->getBase());
  11557. if (Capturer && ref->isFreeIvar())
  11558. Capturer = ref;
  11559. }
  11560. void VisitBlockExpr(BlockExpr *block) {
  11561. // Look inside nested blocks
  11562. if (block->getBlockDecl()->capturesVariable(Variable))
  11563. Visit(block->getBlockDecl()->getBody());
  11564. }
  11565. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  11566. if (Capturer) return;
  11567. if (OVE->getSourceExpr())
  11568. Visit(OVE->getSourceExpr());
  11569. }
  11570. void VisitBinaryOperator(BinaryOperator *BinOp) {
  11571. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  11572. return;
  11573. Expr *LHS = BinOp->getLHS();
  11574. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  11575. if (DRE->getDecl() != Variable)
  11576. return;
  11577. if (Expr *RHS = BinOp->getRHS()) {
  11578. RHS = RHS->IgnoreParenCasts();
  11579. llvm::APSInt Value;
  11580. VarWillBeReased =
  11581. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  11582. }
  11583. }
  11584. }
  11585. };
  11586. } // namespace
  11587. /// Check whether the given argument is a block which captures a
  11588. /// variable.
  11589. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11590. assert(owner.Variable && owner.Loc.isValid());
  11591. e = e->IgnoreParenCasts();
  11592. // Look through [^{...} copy] and Block_copy(^{...}).
  11593. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  11594. Selector Cmd = ME->getSelector();
  11595. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  11596. e = ME->getInstanceReceiver();
  11597. if (!e)
  11598. return nullptr;
  11599. e = e->IgnoreParenCasts();
  11600. }
  11601. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  11602. if (CE->getNumArgs() == 1) {
  11603. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  11604. if (Fn) {
  11605. const IdentifierInfo *FnI = Fn->getIdentifier();
  11606. if (FnI && FnI->isStr("_Block_copy")) {
  11607. e = CE->getArg(0)->IgnoreParenCasts();
  11608. }
  11609. }
  11610. }
  11611. }
  11612. BlockExpr *block = dyn_cast<BlockExpr>(e);
  11613. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  11614. return nullptr;
  11615. FindCaptureVisitor visitor(S.Context, owner.Variable);
  11616. visitor.Visit(block->getBlockDecl()->getBody());
  11617. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  11618. }
  11619. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  11620. RetainCycleOwner &owner) {
  11621. assert(capturer);
  11622. assert(owner.Variable && owner.Loc.isValid());
  11623. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  11624. << owner.Variable << capturer->getSourceRange();
  11625. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  11626. << owner.Indirect << owner.Range;
  11627. }
  11628. /// Check for a keyword selector that starts with the word 'add' or
  11629. /// 'set'.
  11630. static bool isSetterLikeSelector(Selector sel) {
  11631. if (sel.isUnarySelector()) return false;
  11632. StringRef str = sel.getNameForSlot(0);
  11633. while (!str.empty() && str.front() == '_') str = str.substr(1);
  11634. if (str.startswith("set"))
  11635. str = str.substr(3);
  11636. else if (str.startswith("add")) {
  11637. // Specially whitelist 'addOperationWithBlock:'.
  11638. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  11639. return false;
  11640. str = str.substr(3);
  11641. }
  11642. else
  11643. return false;
  11644. if (str.empty()) return true;
  11645. return !isLowercase(str.front());
  11646. }
  11647. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  11648. ObjCMessageExpr *Message) {
  11649. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  11650. Message->getReceiverInterface(),
  11651. NSAPI::ClassId_NSMutableArray);
  11652. if (!IsMutableArray) {
  11653. return None;
  11654. }
  11655. Selector Sel = Message->getSelector();
  11656. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  11657. S.NSAPIObj->getNSArrayMethodKind(Sel);
  11658. if (!MKOpt) {
  11659. return None;
  11660. }
  11661. NSAPI::NSArrayMethodKind MK = *MKOpt;
  11662. switch (MK) {
  11663. case NSAPI::NSMutableArr_addObject:
  11664. case NSAPI::NSMutableArr_insertObjectAtIndex:
  11665. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  11666. return 0;
  11667. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  11668. return 1;
  11669. default:
  11670. return None;
  11671. }
  11672. return None;
  11673. }
  11674. static
  11675. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  11676. ObjCMessageExpr *Message) {
  11677. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  11678. Message->getReceiverInterface(),
  11679. NSAPI::ClassId_NSMutableDictionary);
  11680. if (!IsMutableDictionary) {
  11681. return None;
  11682. }
  11683. Selector Sel = Message->getSelector();
  11684. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  11685. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  11686. if (!MKOpt) {
  11687. return None;
  11688. }
  11689. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  11690. switch (MK) {
  11691. case NSAPI::NSMutableDict_setObjectForKey:
  11692. case NSAPI::NSMutableDict_setValueForKey:
  11693. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  11694. return 0;
  11695. default:
  11696. return None;
  11697. }
  11698. return None;
  11699. }
  11700. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  11701. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  11702. Message->getReceiverInterface(),
  11703. NSAPI::ClassId_NSMutableSet);
  11704. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  11705. Message->getReceiverInterface(),
  11706. NSAPI::ClassId_NSMutableOrderedSet);
  11707. if (!IsMutableSet && !IsMutableOrderedSet) {
  11708. return None;
  11709. }
  11710. Selector Sel = Message->getSelector();
  11711. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  11712. if (!MKOpt) {
  11713. return None;
  11714. }
  11715. NSAPI::NSSetMethodKind MK = *MKOpt;
  11716. switch (MK) {
  11717. case NSAPI::NSMutableSet_addObject:
  11718. case NSAPI::NSOrderedSet_setObjectAtIndex:
  11719. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  11720. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  11721. return 0;
  11722. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  11723. return 1;
  11724. }
  11725. return None;
  11726. }
  11727. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  11728. if (!Message->isInstanceMessage()) {
  11729. return;
  11730. }
  11731. Optional<int> ArgOpt;
  11732. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  11733. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  11734. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  11735. return;
  11736. }
  11737. int ArgIndex = *ArgOpt;
  11738. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  11739. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  11740. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  11741. }
  11742. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  11743. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11744. if (ArgRE->isObjCSelfExpr()) {
  11745. Diag(Message->getSourceRange().getBegin(),
  11746. diag::warn_objc_circular_container)
  11747. << ArgRE->getDecl() << StringRef("'super'");
  11748. }
  11749. }
  11750. } else {
  11751. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  11752. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  11753. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  11754. }
  11755. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  11756. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11757. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  11758. ValueDecl *Decl = ReceiverRE->getDecl();
  11759. Diag(Message->getSourceRange().getBegin(),
  11760. diag::warn_objc_circular_container)
  11761. << Decl << Decl;
  11762. if (!ArgRE->isObjCSelfExpr()) {
  11763. Diag(Decl->getLocation(),
  11764. diag::note_objc_circular_container_declared_here)
  11765. << Decl;
  11766. }
  11767. }
  11768. }
  11769. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  11770. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  11771. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  11772. ObjCIvarDecl *Decl = IvarRE->getDecl();
  11773. Diag(Message->getSourceRange().getBegin(),
  11774. diag::warn_objc_circular_container)
  11775. << Decl << Decl;
  11776. Diag(Decl->getLocation(),
  11777. diag::note_objc_circular_container_declared_here)
  11778. << Decl;
  11779. }
  11780. }
  11781. }
  11782. }
  11783. }
  11784. /// Check a message send to see if it's likely to cause a retain cycle.
  11785. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  11786. // Only check instance methods whose selector looks like a setter.
  11787. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  11788. return;
  11789. // Try to find a variable that the receiver is strongly owned by.
  11790. RetainCycleOwner owner;
  11791. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  11792. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  11793. return;
  11794. } else {
  11795. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  11796. owner.Variable = getCurMethodDecl()->getSelfDecl();
  11797. owner.Loc = msg->getSuperLoc();
  11798. owner.Range = msg->getSuperLoc();
  11799. }
  11800. // Check whether the receiver is captured by any of the arguments.
  11801. const ObjCMethodDecl *MD = msg->getMethodDecl();
  11802. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  11803. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  11804. // noescape blocks should not be retained by the method.
  11805. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  11806. continue;
  11807. return diagnoseRetainCycle(*this, capturer, owner);
  11808. }
  11809. }
  11810. }
  11811. /// Check a property assign to see if it's likely to cause a retain cycle.
  11812. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  11813. RetainCycleOwner owner;
  11814. if (!findRetainCycleOwner(*this, receiver, owner))
  11815. return;
  11816. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  11817. diagnoseRetainCycle(*this, capturer, owner);
  11818. }
  11819. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  11820. RetainCycleOwner Owner;
  11821. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  11822. return;
  11823. // Because we don't have an expression for the variable, we have to set the
  11824. // location explicitly here.
  11825. Owner.Loc = Var->getLocation();
  11826. Owner.Range = Var->getSourceRange();
  11827. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  11828. diagnoseRetainCycle(*this, Capturer, Owner);
  11829. }
  11830. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  11831. Expr *RHS, bool isProperty) {
  11832. // Check if RHS is an Objective-C object literal, which also can get
  11833. // immediately zapped in a weak reference. Note that we explicitly
  11834. // allow ObjCStringLiterals, since those are designed to never really die.
  11835. RHS = RHS->IgnoreParenImpCasts();
  11836. // This enum needs to match with the 'select' in
  11837. // warn_objc_arc_literal_assign (off-by-1).
  11838. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  11839. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  11840. return false;
  11841. S.Diag(Loc, diag::warn_arc_literal_assign)
  11842. << (unsigned) Kind
  11843. << (isProperty ? 0 : 1)
  11844. << RHS->getSourceRange();
  11845. return true;
  11846. }
  11847. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  11848. Qualifiers::ObjCLifetime LT,
  11849. Expr *RHS, bool isProperty) {
  11850. // Strip off any implicit cast added to get to the one ARC-specific.
  11851. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11852. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11853. S.Diag(Loc, diag::warn_arc_retained_assign)
  11854. << (LT == Qualifiers::OCL_ExplicitNone)
  11855. << (isProperty ? 0 : 1)
  11856. << RHS->getSourceRange();
  11857. return true;
  11858. }
  11859. RHS = cast->getSubExpr();
  11860. }
  11861. if (LT == Qualifiers::OCL_Weak &&
  11862. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  11863. return true;
  11864. return false;
  11865. }
  11866. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  11867. QualType LHS, Expr *RHS) {
  11868. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  11869. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  11870. return false;
  11871. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  11872. return true;
  11873. return false;
  11874. }
  11875. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  11876. Expr *LHS, Expr *RHS) {
  11877. QualType LHSType;
  11878. // PropertyRef on LHS type need be directly obtained from
  11879. // its declaration as it has a PseudoType.
  11880. ObjCPropertyRefExpr *PRE
  11881. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  11882. if (PRE && !PRE->isImplicitProperty()) {
  11883. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11884. if (PD)
  11885. LHSType = PD->getType();
  11886. }
  11887. if (LHSType.isNull())
  11888. LHSType = LHS->getType();
  11889. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  11890. if (LT == Qualifiers::OCL_Weak) {
  11891. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  11892. getCurFunction()->markSafeWeakUse(LHS);
  11893. }
  11894. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  11895. return;
  11896. // FIXME. Check for other life times.
  11897. if (LT != Qualifiers::OCL_None)
  11898. return;
  11899. if (PRE) {
  11900. if (PRE->isImplicitProperty())
  11901. return;
  11902. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11903. if (!PD)
  11904. return;
  11905. unsigned Attributes = PD->getPropertyAttributes();
  11906. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  11907. // when 'assign' attribute was not explicitly specified
  11908. // by user, ignore it and rely on property type itself
  11909. // for lifetime info.
  11910. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  11911. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  11912. LHSType->isObjCRetainableType())
  11913. return;
  11914. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11915. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11916. Diag(Loc, diag::warn_arc_retained_property_assign)
  11917. << RHS->getSourceRange();
  11918. return;
  11919. }
  11920. RHS = cast->getSubExpr();
  11921. }
  11922. }
  11923. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  11924. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  11925. return;
  11926. }
  11927. }
  11928. }
  11929. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  11930. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  11931. SourceLocation StmtLoc,
  11932. const NullStmt *Body) {
  11933. // Do not warn if the body is a macro that expands to nothing, e.g:
  11934. //
  11935. // #define CALL(x)
  11936. // if (condition)
  11937. // CALL(0);
  11938. if (Body->hasLeadingEmptyMacro())
  11939. return false;
  11940. // Get line numbers of statement and body.
  11941. bool StmtLineInvalid;
  11942. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  11943. &StmtLineInvalid);
  11944. if (StmtLineInvalid)
  11945. return false;
  11946. bool BodyLineInvalid;
  11947. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  11948. &BodyLineInvalid);
  11949. if (BodyLineInvalid)
  11950. return false;
  11951. // Warn if null statement and body are on the same line.
  11952. if (StmtLine != BodyLine)
  11953. return false;
  11954. return true;
  11955. }
  11956. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  11957. const Stmt *Body,
  11958. unsigned DiagID) {
  11959. // Since this is a syntactic check, don't emit diagnostic for template
  11960. // instantiations, this just adds noise.
  11961. if (CurrentInstantiationScope)
  11962. return;
  11963. // The body should be a null statement.
  11964. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  11965. if (!NBody)
  11966. return;
  11967. // Do the usual checks.
  11968. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  11969. return;
  11970. Diag(NBody->getSemiLoc(), DiagID);
  11971. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  11972. }
  11973. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  11974. const Stmt *PossibleBody) {
  11975. assert(!CurrentInstantiationScope); // Ensured by caller
  11976. SourceLocation StmtLoc;
  11977. const Stmt *Body;
  11978. unsigned DiagID;
  11979. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  11980. StmtLoc = FS->getRParenLoc();
  11981. Body = FS->getBody();
  11982. DiagID = diag::warn_empty_for_body;
  11983. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  11984. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  11985. Body = WS->getBody();
  11986. DiagID = diag::warn_empty_while_body;
  11987. } else
  11988. return; // Neither `for' nor `while'.
  11989. // The body should be a null statement.
  11990. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  11991. if (!NBody)
  11992. return;
  11993. // Skip expensive checks if diagnostic is disabled.
  11994. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  11995. return;
  11996. // Do the usual checks.
  11997. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  11998. return;
  11999. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  12000. // noise level low, emit diagnostics only if for/while is followed by a
  12001. // CompoundStmt, e.g.:
  12002. // for (int i = 0; i < n; i++);
  12003. // {
  12004. // a(i);
  12005. // }
  12006. // or if for/while is followed by a statement with more indentation
  12007. // than for/while itself:
  12008. // for (int i = 0; i < n; i++);
  12009. // a(i);
  12010. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  12011. if (!ProbableTypo) {
  12012. bool BodyColInvalid;
  12013. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  12014. PossibleBody->getBeginLoc(), &BodyColInvalid);
  12015. if (BodyColInvalid)
  12016. return;
  12017. bool StmtColInvalid;
  12018. unsigned StmtCol =
  12019. SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
  12020. if (StmtColInvalid)
  12021. return;
  12022. if (BodyCol > StmtCol)
  12023. ProbableTypo = true;
  12024. }
  12025. if (ProbableTypo) {
  12026. Diag(NBody->getSemiLoc(), DiagID);
  12027. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  12028. }
  12029. }
  12030. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  12031. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  12032. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  12033. SourceLocation OpLoc) {
  12034. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  12035. return;
  12036. if (inTemplateInstantiation())
  12037. return;
  12038. // Strip parens and casts away.
  12039. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  12040. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  12041. // Check for a call expression
  12042. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  12043. if (!CE || CE->getNumArgs() != 1)
  12044. return;
  12045. // Check for a call to std::move
  12046. if (!CE->isCallToStdMove())
  12047. return;
  12048. // Get argument from std::move
  12049. RHSExpr = CE->getArg(0);
  12050. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  12051. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  12052. // Two DeclRefExpr's, check that the decls are the same.
  12053. if (LHSDeclRef && RHSDeclRef) {
  12054. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12055. return;
  12056. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12057. RHSDeclRef->getDecl()->getCanonicalDecl())
  12058. return;
  12059. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12060. << LHSExpr->getSourceRange()
  12061. << RHSExpr->getSourceRange();
  12062. return;
  12063. }
  12064. // Member variables require a different approach to check for self moves.
  12065. // MemberExpr's are the same if every nested MemberExpr refers to the same
  12066. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  12067. // the base Expr's are CXXThisExpr's.
  12068. const Expr *LHSBase = LHSExpr;
  12069. const Expr *RHSBase = RHSExpr;
  12070. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  12071. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  12072. if (!LHSME || !RHSME)
  12073. return;
  12074. while (LHSME && RHSME) {
  12075. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  12076. RHSME->getMemberDecl()->getCanonicalDecl())
  12077. return;
  12078. LHSBase = LHSME->getBase();
  12079. RHSBase = RHSME->getBase();
  12080. LHSME = dyn_cast<MemberExpr>(LHSBase);
  12081. RHSME = dyn_cast<MemberExpr>(RHSBase);
  12082. }
  12083. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  12084. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  12085. if (LHSDeclRef && RHSDeclRef) {
  12086. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12087. return;
  12088. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12089. RHSDeclRef->getDecl()->getCanonicalDecl())
  12090. return;
  12091. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12092. << LHSExpr->getSourceRange()
  12093. << RHSExpr->getSourceRange();
  12094. return;
  12095. }
  12096. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  12097. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12098. << LHSExpr->getSourceRange()
  12099. << RHSExpr->getSourceRange();
  12100. }
  12101. //===--- Layout compatibility ----------------------------------------------//
  12102. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  12103. /// Check if two enumeration types are layout-compatible.
  12104. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  12105. // C++11 [dcl.enum] p8:
  12106. // Two enumeration types are layout-compatible if they have the same
  12107. // underlying type.
  12108. return ED1->isComplete() && ED2->isComplete() &&
  12109. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  12110. }
  12111. /// Check if two fields are layout-compatible.
  12112. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  12113. FieldDecl *Field2) {
  12114. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  12115. return false;
  12116. if (Field1->isBitField() != Field2->isBitField())
  12117. return false;
  12118. if (Field1->isBitField()) {
  12119. // Make sure that the bit-fields are the same length.
  12120. unsigned Bits1 = Field1->getBitWidthValue(C);
  12121. unsigned Bits2 = Field2->getBitWidthValue(C);
  12122. if (Bits1 != Bits2)
  12123. return false;
  12124. }
  12125. return true;
  12126. }
  12127. /// Check if two standard-layout structs are layout-compatible.
  12128. /// (C++11 [class.mem] p17)
  12129. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  12130. RecordDecl *RD2) {
  12131. // If both records are C++ classes, check that base classes match.
  12132. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  12133. // If one of records is a CXXRecordDecl we are in C++ mode,
  12134. // thus the other one is a CXXRecordDecl, too.
  12135. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  12136. // Check number of base classes.
  12137. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  12138. return false;
  12139. // Check the base classes.
  12140. for (CXXRecordDecl::base_class_const_iterator
  12141. Base1 = D1CXX->bases_begin(),
  12142. BaseEnd1 = D1CXX->bases_end(),
  12143. Base2 = D2CXX->bases_begin();
  12144. Base1 != BaseEnd1;
  12145. ++Base1, ++Base2) {
  12146. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  12147. return false;
  12148. }
  12149. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  12150. // If only RD2 is a C++ class, it should have zero base classes.
  12151. if (D2CXX->getNumBases() > 0)
  12152. return false;
  12153. }
  12154. // Check the fields.
  12155. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  12156. Field2End = RD2->field_end(),
  12157. Field1 = RD1->field_begin(),
  12158. Field1End = RD1->field_end();
  12159. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  12160. if (!isLayoutCompatible(C, *Field1, *Field2))
  12161. return false;
  12162. }
  12163. if (Field1 != Field1End || Field2 != Field2End)
  12164. return false;
  12165. return true;
  12166. }
  12167. /// Check if two standard-layout unions are layout-compatible.
  12168. /// (C++11 [class.mem] p18)
  12169. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  12170. RecordDecl *RD2) {
  12171. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  12172. for (auto *Field2 : RD2->fields())
  12173. UnmatchedFields.insert(Field2);
  12174. for (auto *Field1 : RD1->fields()) {
  12175. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  12176. I = UnmatchedFields.begin(),
  12177. E = UnmatchedFields.end();
  12178. for ( ; I != E; ++I) {
  12179. if (isLayoutCompatible(C, Field1, *I)) {
  12180. bool Result = UnmatchedFields.erase(*I);
  12181. (void) Result;
  12182. assert(Result);
  12183. break;
  12184. }
  12185. }
  12186. if (I == E)
  12187. return false;
  12188. }
  12189. return UnmatchedFields.empty();
  12190. }
  12191. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  12192. RecordDecl *RD2) {
  12193. if (RD1->isUnion() != RD2->isUnion())
  12194. return false;
  12195. if (RD1->isUnion())
  12196. return isLayoutCompatibleUnion(C, RD1, RD2);
  12197. else
  12198. return isLayoutCompatibleStruct(C, RD1, RD2);
  12199. }
  12200. /// Check if two types are layout-compatible in C++11 sense.
  12201. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  12202. if (T1.isNull() || T2.isNull())
  12203. return false;
  12204. // C++11 [basic.types] p11:
  12205. // If two types T1 and T2 are the same type, then T1 and T2 are
  12206. // layout-compatible types.
  12207. if (C.hasSameType(T1, T2))
  12208. return true;
  12209. T1 = T1.getCanonicalType().getUnqualifiedType();
  12210. T2 = T2.getCanonicalType().getUnqualifiedType();
  12211. const Type::TypeClass TC1 = T1->getTypeClass();
  12212. const Type::TypeClass TC2 = T2->getTypeClass();
  12213. if (TC1 != TC2)
  12214. return false;
  12215. if (TC1 == Type::Enum) {
  12216. return isLayoutCompatible(C,
  12217. cast<EnumType>(T1)->getDecl(),
  12218. cast<EnumType>(T2)->getDecl());
  12219. } else if (TC1 == Type::Record) {
  12220. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  12221. return false;
  12222. return isLayoutCompatible(C,
  12223. cast<RecordType>(T1)->getDecl(),
  12224. cast<RecordType>(T2)->getDecl());
  12225. }
  12226. return false;
  12227. }
  12228. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  12229. /// Given a type tag expression find the type tag itself.
  12230. ///
  12231. /// \param TypeExpr Type tag expression, as it appears in user's code.
  12232. ///
  12233. /// \param VD Declaration of an identifier that appears in a type tag.
  12234. ///
  12235. /// \param MagicValue Type tag magic value.
  12236. ///
  12237. /// \param isConstantEvaluated wether the evalaution should be performed in
  12238. /// constant context.
  12239. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  12240. const ValueDecl **VD, uint64_t *MagicValue,
  12241. bool isConstantEvaluated) {
  12242. while(true) {
  12243. if (!TypeExpr)
  12244. return false;
  12245. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  12246. switch (TypeExpr->getStmtClass()) {
  12247. case Stmt::UnaryOperatorClass: {
  12248. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  12249. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  12250. TypeExpr = UO->getSubExpr();
  12251. continue;
  12252. }
  12253. return false;
  12254. }
  12255. case Stmt::DeclRefExprClass: {
  12256. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  12257. *VD = DRE->getDecl();
  12258. return true;
  12259. }
  12260. case Stmt::IntegerLiteralClass: {
  12261. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  12262. llvm::APInt MagicValueAPInt = IL->getValue();
  12263. if (MagicValueAPInt.getActiveBits() <= 64) {
  12264. *MagicValue = MagicValueAPInt.getZExtValue();
  12265. return true;
  12266. } else
  12267. return false;
  12268. }
  12269. case Stmt::BinaryConditionalOperatorClass:
  12270. case Stmt::ConditionalOperatorClass: {
  12271. const AbstractConditionalOperator *ACO =
  12272. cast<AbstractConditionalOperator>(TypeExpr);
  12273. bool Result;
  12274. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
  12275. isConstantEvaluated)) {
  12276. if (Result)
  12277. TypeExpr = ACO->getTrueExpr();
  12278. else
  12279. TypeExpr = ACO->getFalseExpr();
  12280. continue;
  12281. }
  12282. return false;
  12283. }
  12284. case Stmt::BinaryOperatorClass: {
  12285. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  12286. if (BO->getOpcode() == BO_Comma) {
  12287. TypeExpr = BO->getRHS();
  12288. continue;
  12289. }
  12290. return false;
  12291. }
  12292. default:
  12293. return false;
  12294. }
  12295. }
  12296. }
  12297. /// Retrieve the C type corresponding to type tag TypeExpr.
  12298. ///
  12299. /// \param TypeExpr Expression that specifies a type tag.
  12300. ///
  12301. /// \param MagicValues Registered magic values.
  12302. ///
  12303. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  12304. /// kind.
  12305. ///
  12306. /// \param TypeInfo Information about the corresponding C type.
  12307. ///
  12308. /// \param isConstantEvaluated wether the evalaution should be performed in
  12309. /// constant context.
  12310. ///
  12311. /// \returns true if the corresponding C type was found.
  12312. static bool GetMatchingCType(
  12313. const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
  12314. const ASTContext &Ctx,
  12315. const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
  12316. *MagicValues,
  12317. bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
  12318. bool isConstantEvaluated) {
  12319. FoundWrongKind = false;
  12320. // Variable declaration that has type_tag_for_datatype attribute.
  12321. const ValueDecl *VD = nullptr;
  12322. uint64_t MagicValue;
  12323. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
  12324. return false;
  12325. if (VD) {
  12326. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  12327. if (I->getArgumentKind() != ArgumentKind) {
  12328. FoundWrongKind = true;
  12329. return false;
  12330. }
  12331. TypeInfo.Type = I->getMatchingCType();
  12332. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  12333. TypeInfo.MustBeNull = I->getMustBeNull();
  12334. return true;
  12335. }
  12336. return false;
  12337. }
  12338. if (!MagicValues)
  12339. return false;
  12340. llvm::DenseMap<Sema::TypeTagMagicValue,
  12341. Sema::TypeTagData>::const_iterator I =
  12342. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  12343. if (I == MagicValues->end())
  12344. return false;
  12345. TypeInfo = I->second;
  12346. return true;
  12347. }
  12348. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  12349. uint64_t MagicValue, QualType Type,
  12350. bool LayoutCompatible,
  12351. bool MustBeNull) {
  12352. if (!TypeTagForDatatypeMagicValues)
  12353. TypeTagForDatatypeMagicValues.reset(
  12354. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  12355. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  12356. (*TypeTagForDatatypeMagicValues)[Magic] =
  12357. TypeTagData(Type, LayoutCompatible, MustBeNull);
  12358. }
  12359. static bool IsSameCharType(QualType T1, QualType T2) {
  12360. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  12361. if (!BT1)
  12362. return false;
  12363. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  12364. if (!BT2)
  12365. return false;
  12366. BuiltinType::Kind T1Kind = BT1->getKind();
  12367. BuiltinType::Kind T2Kind = BT2->getKind();
  12368. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  12369. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  12370. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  12371. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  12372. }
  12373. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  12374. const ArrayRef<const Expr *> ExprArgs,
  12375. SourceLocation CallSiteLoc) {
  12376. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  12377. bool IsPointerAttr = Attr->getIsPointer();
  12378. // Retrieve the argument representing the 'type_tag'.
  12379. unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
  12380. if (TypeTagIdxAST >= ExprArgs.size()) {
  12381. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12382. << 0 << Attr->getTypeTagIdx().getSourceIndex();
  12383. return;
  12384. }
  12385. const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
  12386. bool FoundWrongKind;
  12387. TypeTagData TypeInfo;
  12388. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  12389. TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
  12390. TypeInfo, isConstantEvaluated())) {
  12391. if (FoundWrongKind)
  12392. Diag(TypeTagExpr->getExprLoc(),
  12393. diag::warn_type_tag_for_datatype_wrong_kind)
  12394. << TypeTagExpr->getSourceRange();
  12395. return;
  12396. }
  12397. // Retrieve the argument representing the 'arg_idx'.
  12398. unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
  12399. if (ArgumentIdxAST >= ExprArgs.size()) {
  12400. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12401. << 1 << Attr->getArgumentIdx().getSourceIndex();
  12402. return;
  12403. }
  12404. const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
  12405. if (IsPointerAttr) {
  12406. // Skip implicit cast of pointer to `void *' (as a function argument).
  12407. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  12408. if (ICE->getType()->isVoidPointerType() &&
  12409. ICE->getCastKind() == CK_BitCast)
  12410. ArgumentExpr = ICE->getSubExpr();
  12411. }
  12412. QualType ArgumentType = ArgumentExpr->getType();
  12413. // Passing a `void*' pointer shouldn't trigger a warning.
  12414. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  12415. return;
  12416. if (TypeInfo.MustBeNull) {
  12417. // Type tag with matching void type requires a null pointer.
  12418. if (!ArgumentExpr->isNullPointerConstant(Context,
  12419. Expr::NPC_ValueDependentIsNotNull)) {
  12420. Diag(ArgumentExpr->getExprLoc(),
  12421. diag::warn_type_safety_null_pointer_required)
  12422. << ArgumentKind->getName()
  12423. << ArgumentExpr->getSourceRange()
  12424. << TypeTagExpr->getSourceRange();
  12425. }
  12426. return;
  12427. }
  12428. QualType RequiredType = TypeInfo.Type;
  12429. if (IsPointerAttr)
  12430. RequiredType = Context.getPointerType(RequiredType);
  12431. bool mismatch = false;
  12432. if (!TypeInfo.LayoutCompatible) {
  12433. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  12434. // C++11 [basic.fundamental] p1:
  12435. // Plain char, signed char, and unsigned char are three distinct types.
  12436. //
  12437. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  12438. // char' depending on the current char signedness mode.
  12439. if (mismatch)
  12440. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  12441. RequiredType->getPointeeType())) ||
  12442. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  12443. mismatch = false;
  12444. } else
  12445. if (IsPointerAttr)
  12446. mismatch = !isLayoutCompatible(Context,
  12447. ArgumentType->getPointeeType(),
  12448. RequiredType->getPointeeType());
  12449. else
  12450. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  12451. if (mismatch)
  12452. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  12453. << ArgumentType << ArgumentKind
  12454. << TypeInfo.LayoutCompatible << RequiredType
  12455. << ArgumentExpr->getSourceRange()
  12456. << TypeTagExpr->getSourceRange();
  12457. }
  12458. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  12459. CharUnits Alignment) {
  12460. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  12461. }
  12462. void Sema::DiagnoseMisalignedMembers() {
  12463. for (MisalignedMember &m : MisalignedMembers) {
  12464. const NamedDecl *ND = m.RD;
  12465. if (ND->getName().empty()) {
  12466. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  12467. ND = TD;
  12468. }
  12469. Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
  12470. << m.MD << ND << m.E->getSourceRange();
  12471. }
  12472. MisalignedMembers.clear();
  12473. }
  12474. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  12475. E = E->IgnoreParens();
  12476. if (!T->isPointerType() && !T->isIntegerType())
  12477. return;
  12478. if (isa<UnaryOperator>(E) &&
  12479. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  12480. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  12481. if (isa<MemberExpr>(Op)) {
  12482. auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
  12483. if (MA != MisalignedMembers.end() &&
  12484. (T->isIntegerType() ||
  12485. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  12486. Context.getTypeAlignInChars(
  12487. T->getPointeeType()) <= MA->Alignment))))
  12488. MisalignedMembers.erase(MA);
  12489. }
  12490. }
  12491. }
  12492. void Sema::RefersToMemberWithReducedAlignment(
  12493. Expr *E,
  12494. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  12495. Action) {
  12496. const auto *ME = dyn_cast<MemberExpr>(E);
  12497. if (!ME)
  12498. return;
  12499. // No need to check expressions with an __unaligned-qualified type.
  12500. if (E->getType().getQualifiers().hasUnaligned())
  12501. return;
  12502. // For a chain of MemberExpr like "a.b.c.d" this list
  12503. // will keep FieldDecl's like [d, c, b].
  12504. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  12505. const MemberExpr *TopME = nullptr;
  12506. bool AnyIsPacked = false;
  12507. do {
  12508. QualType BaseType = ME->getBase()->getType();
  12509. if (ME->isArrow())
  12510. BaseType = BaseType->getPointeeType();
  12511. RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
  12512. if (RD->isInvalidDecl())
  12513. return;
  12514. ValueDecl *MD = ME->getMemberDecl();
  12515. auto *FD = dyn_cast<FieldDecl>(MD);
  12516. // We do not care about non-data members.
  12517. if (!FD || FD->isInvalidDecl())
  12518. return;
  12519. AnyIsPacked =
  12520. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  12521. ReverseMemberChain.push_back(FD);
  12522. TopME = ME;
  12523. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  12524. } while (ME);
  12525. assert(TopME && "We did not compute a topmost MemberExpr!");
  12526. // Not the scope of this diagnostic.
  12527. if (!AnyIsPacked)
  12528. return;
  12529. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  12530. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  12531. // TODO: The innermost base of the member expression may be too complicated.
  12532. // For now, just disregard these cases. This is left for future
  12533. // improvement.
  12534. if (!DRE && !isa<CXXThisExpr>(TopBase))
  12535. return;
  12536. // Alignment expected by the whole expression.
  12537. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  12538. // No need to do anything else with this case.
  12539. if (ExpectedAlignment.isOne())
  12540. return;
  12541. // Synthesize offset of the whole access.
  12542. CharUnits Offset;
  12543. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  12544. I++) {
  12545. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  12546. }
  12547. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  12548. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  12549. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  12550. // The base expression of the innermost MemberExpr may give
  12551. // stronger guarantees than the class containing the member.
  12552. if (DRE && !TopME->isArrow()) {
  12553. const ValueDecl *VD = DRE->getDecl();
  12554. if (!VD->getType()->isReferenceType())
  12555. CompleteObjectAlignment =
  12556. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  12557. }
  12558. // Check if the synthesized offset fulfills the alignment.
  12559. if (Offset % ExpectedAlignment != 0 ||
  12560. // It may fulfill the offset it but the effective alignment may still be
  12561. // lower than the expected expression alignment.
  12562. CompleteObjectAlignment < ExpectedAlignment) {
  12563. // If this happens, we want to determine a sensible culprit of this.
  12564. // Intuitively, watching the chain of member expressions from right to
  12565. // left, we start with the required alignment (as required by the field
  12566. // type) but some packed attribute in that chain has reduced the alignment.
  12567. // It may happen that another packed structure increases it again. But if
  12568. // we are here such increase has not been enough. So pointing the first
  12569. // FieldDecl that either is packed or else its RecordDecl is,
  12570. // seems reasonable.
  12571. FieldDecl *FD = nullptr;
  12572. CharUnits Alignment;
  12573. for (FieldDecl *FDI : ReverseMemberChain) {
  12574. if (FDI->hasAttr<PackedAttr>() ||
  12575. FDI->getParent()->hasAttr<PackedAttr>()) {
  12576. FD = FDI;
  12577. Alignment = std::min(
  12578. Context.getTypeAlignInChars(FD->getType()),
  12579. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  12580. break;
  12581. }
  12582. }
  12583. assert(FD && "We did not find a packed FieldDecl!");
  12584. Action(E, FD->getParent(), FD, Alignment);
  12585. }
  12586. }
  12587. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  12588. using namespace std::placeholders;
  12589. RefersToMemberWithReducedAlignment(
  12590. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  12591. _2, _3, _4));
  12592. }