SemaChecking.cpp 563 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414
  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. /// Check the number of arguments, and set the result type to
  177. /// the argument type.
  178. static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
  179. if (checkArgCount(S, TheCall, 1))
  180. return true;
  181. TheCall->setType(TheCall->getArg(0)->getType());
  182. return false;
  183. }
  184. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
  185. if (checkArgCount(S, TheCall, 3))
  186. return true;
  187. // First two arguments should be integers.
  188. for (unsigned I = 0; I < 2; ++I) {
  189. ExprResult Arg = TheCall->getArg(I);
  190. QualType Ty = Arg.get()->getType();
  191. if (!Ty->isIntegerType()) {
  192. S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
  193. << Ty << Arg.get()->getSourceRange();
  194. return true;
  195. }
  196. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  197. S.getASTContext(), Ty, /*consume*/ false);
  198. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  199. if (Arg.isInvalid())
  200. return true;
  201. TheCall->setArg(I, Arg.get());
  202. }
  203. // Third argument should be a pointer to a non-const integer.
  204. // IRGen correctly handles volatile, restrict, and address spaces, and
  205. // the other qualifiers aren't possible.
  206. {
  207. ExprResult Arg = TheCall->getArg(2);
  208. QualType Ty = Arg.get()->getType();
  209. const auto *PtrTy = Ty->getAs<PointerType>();
  210. if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
  211. !PtrTy->getPointeeType().isConstQualified())) {
  212. S.Diag(Arg.get()->getBeginLoc(),
  213. diag::err_overflow_builtin_must_be_ptr_int)
  214. << Ty << Arg.get()->getSourceRange();
  215. return true;
  216. }
  217. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  218. S.getASTContext(), Ty, /*consume*/ false);
  219. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  220. if (Arg.isInvalid())
  221. return true;
  222. TheCall->setArg(2, Arg.get());
  223. }
  224. return false;
  225. }
  226. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  227. if (checkArgCount(S, BuiltinCall, 2))
  228. return true;
  229. SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
  230. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  231. Expr *Call = BuiltinCall->getArg(0);
  232. Expr *Chain = BuiltinCall->getArg(1);
  233. if (Call->getStmtClass() != Stmt::CallExprClass) {
  234. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  235. << Call->getSourceRange();
  236. return true;
  237. }
  238. auto CE = cast<CallExpr>(Call);
  239. if (CE->getCallee()->getType()->isBlockPointerType()) {
  240. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  241. << Call->getSourceRange();
  242. return true;
  243. }
  244. const Decl *TargetDecl = CE->getCalleeDecl();
  245. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  246. if (FD->getBuiltinID()) {
  247. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  248. << Call->getSourceRange();
  249. return true;
  250. }
  251. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  252. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  253. << Call->getSourceRange();
  254. return true;
  255. }
  256. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  257. if (ChainResult.isInvalid())
  258. return true;
  259. if (!ChainResult.get()->getType()->isPointerType()) {
  260. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  261. << Chain->getSourceRange();
  262. return true;
  263. }
  264. QualType ReturnTy = CE->getCallReturnType(S.Context);
  265. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  266. QualType BuiltinTy = S.Context.getFunctionType(
  267. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  268. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  269. Builtin =
  270. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  271. BuiltinCall->setType(CE->getType());
  272. BuiltinCall->setValueKind(CE->getValueKind());
  273. BuiltinCall->setObjectKind(CE->getObjectKind());
  274. BuiltinCall->setCallee(Builtin);
  275. BuiltinCall->setArg(1, ChainResult.get());
  276. return false;
  277. }
  278. /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
  279. /// __builtin_*_chk function, then use the object size argument specified in the
  280. /// source. Otherwise, infer the object size using __builtin_object_size.
  281. void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
  282. CallExpr *TheCall) {
  283. // FIXME: There are some more useful checks we could be doing here:
  284. // - Analyze the format string of sprintf to see how much of buffer is used.
  285. // - Evaluate strlen of strcpy arguments, use as object size.
  286. if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
  287. isConstantEvaluated())
  288. return;
  289. unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
  290. if (!BuiltinID)
  291. return;
  292. unsigned DiagID = 0;
  293. bool IsChkVariant = false;
  294. unsigned SizeIndex, ObjectIndex;
  295. switch (BuiltinID) {
  296. default:
  297. return;
  298. case Builtin::BI__builtin___memcpy_chk:
  299. case Builtin::BI__builtin___memmove_chk:
  300. case Builtin::BI__builtin___memset_chk:
  301. case Builtin::BI__builtin___strlcat_chk:
  302. case Builtin::BI__builtin___strlcpy_chk:
  303. case Builtin::BI__builtin___strncat_chk:
  304. case Builtin::BI__builtin___strncpy_chk:
  305. case Builtin::BI__builtin___stpncpy_chk:
  306. case Builtin::BI__builtin___memccpy_chk: {
  307. DiagID = diag::warn_builtin_chk_overflow;
  308. IsChkVariant = true;
  309. SizeIndex = TheCall->getNumArgs() - 2;
  310. ObjectIndex = TheCall->getNumArgs() - 1;
  311. break;
  312. }
  313. case Builtin::BI__builtin___snprintf_chk:
  314. case Builtin::BI__builtin___vsnprintf_chk: {
  315. DiagID = diag::warn_builtin_chk_overflow;
  316. IsChkVariant = true;
  317. SizeIndex = 1;
  318. ObjectIndex = 3;
  319. break;
  320. }
  321. case Builtin::BIstrncat:
  322. case Builtin::BI__builtin_strncat:
  323. case Builtin::BIstrncpy:
  324. case Builtin::BI__builtin_strncpy:
  325. case Builtin::BIstpncpy:
  326. case Builtin::BI__builtin_stpncpy: {
  327. // Whether these functions overflow depends on the runtime strlen of the
  328. // string, not just the buffer size, so emitting the "always overflow"
  329. // diagnostic isn't quite right. We should still diagnose passing a buffer
  330. // size larger than the destination buffer though; this is a runtime abort
  331. // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
  332. DiagID = diag::warn_fortify_source_size_mismatch;
  333. SizeIndex = TheCall->getNumArgs() - 1;
  334. ObjectIndex = 0;
  335. break;
  336. }
  337. case Builtin::BImemcpy:
  338. case Builtin::BI__builtin_memcpy:
  339. case Builtin::BImemmove:
  340. case Builtin::BI__builtin_memmove:
  341. case Builtin::BImemset:
  342. case Builtin::BI__builtin_memset: {
  343. DiagID = diag::warn_fortify_source_overflow;
  344. SizeIndex = TheCall->getNumArgs() - 1;
  345. ObjectIndex = 0;
  346. break;
  347. }
  348. case Builtin::BIsnprintf:
  349. case Builtin::BI__builtin_snprintf:
  350. case Builtin::BIvsnprintf:
  351. case Builtin::BI__builtin_vsnprintf: {
  352. DiagID = diag::warn_fortify_source_size_mismatch;
  353. SizeIndex = 1;
  354. ObjectIndex = 0;
  355. break;
  356. }
  357. }
  358. llvm::APSInt ObjectSize;
  359. // For __builtin___*_chk, the object size is explicitly provided by the caller
  360. // (usually using __builtin_object_size). Use that value to check this call.
  361. if (IsChkVariant) {
  362. Expr::EvalResult Result;
  363. Expr *SizeArg = TheCall->getArg(ObjectIndex);
  364. if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
  365. return;
  366. ObjectSize = Result.Val.getInt();
  367. // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
  368. } else {
  369. // If the parameter has a pass_object_size attribute, then we should use its
  370. // (potentially) more strict checking mode. Otherwise, conservatively assume
  371. // type 0.
  372. int BOSType = 0;
  373. if (const auto *POS =
  374. FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
  375. BOSType = POS->getType();
  376. Expr *ObjArg = TheCall->getArg(ObjectIndex);
  377. uint64_t Result;
  378. if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
  379. return;
  380. // Get the object size in the target's size_t width.
  381. const TargetInfo &TI = getASTContext().getTargetInfo();
  382. unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
  383. ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
  384. }
  385. // Evaluate the number of bytes of the object that this call will use.
  386. Expr::EvalResult Result;
  387. Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
  388. if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
  389. return;
  390. llvm::APSInt UsedSize = Result.Val.getInt();
  391. if (UsedSize.ule(ObjectSize))
  392. return;
  393. StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
  394. // Skim off the details of whichever builtin was called to produce a better
  395. // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
  396. if (IsChkVariant) {
  397. FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
  398. FunctionName = FunctionName.drop_back(std::strlen("_chk"));
  399. } else if (FunctionName.startswith("__builtin_")) {
  400. FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
  401. }
  402. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  403. PDiag(DiagID)
  404. << FunctionName << ObjectSize.toString(/*Radix=*/10)
  405. << UsedSize.toString(/*Radix=*/10));
  406. }
  407. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  408. Scope::ScopeFlags NeededScopeFlags,
  409. unsigned DiagID) {
  410. // Scopes aren't available during instantiation. Fortunately, builtin
  411. // functions cannot be template args so they cannot be formed through template
  412. // instantiation. Therefore checking once during the parse is sufficient.
  413. if (SemaRef.inTemplateInstantiation())
  414. return false;
  415. Scope *S = SemaRef.getCurScope();
  416. while (S && !S->isSEHExceptScope())
  417. S = S->getParent();
  418. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  419. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  420. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  421. << DRE->getDecl()->getIdentifier();
  422. return true;
  423. }
  424. return false;
  425. }
  426. static inline bool isBlockPointer(Expr *Arg) {
  427. return Arg->getType()->isBlockPointerType();
  428. }
  429. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  430. /// void*, which is a requirement of device side enqueue.
  431. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  432. const BlockPointerType *BPT =
  433. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  434. ArrayRef<QualType> Params =
  435. BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
  436. unsigned ArgCounter = 0;
  437. bool IllegalParams = false;
  438. // Iterate through the block parameters until either one is found that is not
  439. // a local void*, or the block is valid.
  440. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  441. I != E; ++I, ++ArgCounter) {
  442. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  443. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  444. LangAS::opencl_local) {
  445. // Get the location of the error. If a block literal has been passed
  446. // (BlockExpr) then we can point straight to the offending argument,
  447. // else we just point to the variable reference.
  448. SourceLocation ErrorLoc;
  449. if (isa<BlockExpr>(BlockArg)) {
  450. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  451. ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
  452. } else if (isa<DeclRefExpr>(BlockArg)) {
  453. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
  454. }
  455. S.Diag(ErrorLoc,
  456. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  457. IllegalParams = true;
  458. }
  459. }
  460. return IllegalParams;
  461. }
  462. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  463. if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
  464. S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
  465. << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
  466. return true;
  467. }
  468. return false;
  469. }
  470. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  471. if (checkArgCount(S, TheCall, 2))
  472. return true;
  473. if (checkOpenCLSubgroupExt(S, TheCall))
  474. return true;
  475. // First argument is an ndrange_t type.
  476. Expr *NDRangeArg = TheCall->getArg(0);
  477. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  478. S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  479. << TheCall->getDirectCallee() << "'ndrange_t'";
  480. return true;
  481. }
  482. Expr *BlockArg = TheCall->getArg(1);
  483. if (!isBlockPointer(BlockArg)) {
  484. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  485. << TheCall->getDirectCallee() << "block";
  486. return true;
  487. }
  488. return checkOpenCLBlockArgs(S, BlockArg);
  489. }
  490. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  491. /// get_kernel_work_group_size
  492. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  493. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  494. if (checkArgCount(S, TheCall, 1))
  495. return true;
  496. Expr *BlockArg = TheCall->getArg(0);
  497. if (!isBlockPointer(BlockArg)) {
  498. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  499. << TheCall->getDirectCallee() << "block";
  500. return true;
  501. }
  502. return checkOpenCLBlockArgs(S, BlockArg);
  503. }
  504. /// Diagnose integer type and any valid implicit conversion to it.
  505. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  506. const QualType &IntType);
  507. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  508. unsigned Start, unsigned End) {
  509. bool IllegalParams = false;
  510. for (unsigned I = Start; I <= End; ++I)
  511. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  512. S.Context.getSizeType());
  513. return IllegalParams;
  514. }
  515. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  516. /// 'local void*' parameter of passed block.
  517. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  518. Expr *BlockArg,
  519. unsigned NumNonVarArgs) {
  520. const BlockPointerType *BPT =
  521. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  522. unsigned NumBlockParams =
  523. BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
  524. unsigned TotalNumArgs = TheCall->getNumArgs();
  525. // For each argument passed to the block, a corresponding uint needs to
  526. // be passed to describe the size of the local memory.
  527. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  528. S.Diag(TheCall->getBeginLoc(),
  529. diag::err_opencl_enqueue_kernel_local_size_args);
  530. return true;
  531. }
  532. // Check that the sizes of the local memory are specified by integers.
  533. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  534. TotalNumArgs - 1);
  535. }
  536. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  537. /// overload formats specified in Table 6.13.17.1.
  538. /// int enqueue_kernel(queue_t queue,
  539. /// kernel_enqueue_flags_t flags,
  540. /// const ndrange_t ndrange,
  541. /// void (^block)(void))
  542. /// int enqueue_kernel(queue_t queue,
  543. /// kernel_enqueue_flags_t flags,
  544. /// const ndrange_t ndrange,
  545. /// uint num_events_in_wait_list,
  546. /// clk_event_t *event_wait_list,
  547. /// clk_event_t *event_ret,
  548. /// void (^block)(void))
  549. /// int enqueue_kernel(queue_t queue,
  550. /// kernel_enqueue_flags_t flags,
  551. /// const ndrange_t ndrange,
  552. /// void (^block)(local void*, ...),
  553. /// uint size0, ...)
  554. /// int enqueue_kernel(queue_t queue,
  555. /// kernel_enqueue_flags_t flags,
  556. /// const ndrange_t ndrange,
  557. /// uint num_events_in_wait_list,
  558. /// clk_event_t *event_wait_list,
  559. /// clk_event_t *event_ret,
  560. /// void (^block)(local void*, ...),
  561. /// uint size0, ...)
  562. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  563. unsigned NumArgs = TheCall->getNumArgs();
  564. if (NumArgs < 4) {
  565. S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
  566. return true;
  567. }
  568. Expr *Arg0 = TheCall->getArg(0);
  569. Expr *Arg1 = TheCall->getArg(1);
  570. Expr *Arg2 = TheCall->getArg(2);
  571. Expr *Arg3 = TheCall->getArg(3);
  572. // First argument always needs to be a queue_t type.
  573. if (!Arg0->getType()->isQueueT()) {
  574. S.Diag(TheCall->getArg(0)->getBeginLoc(),
  575. diag::err_opencl_builtin_expected_type)
  576. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  577. return true;
  578. }
  579. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  580. if (!Arg1->getType()->isIntegerType()) {
  581. S.Diag(TheCall->getArg(1)->getBeginLoc(),
  582. diag::err_opencl_builtin_expected_type)
  583. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  584. return true;
  585. }
  586. // Third argument is always an ndrange_t type.
  587. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  588. S.Diag(TheCall->getArg(2)->getBeginLoc(),
  589. diag::err_opencl_builtin_expected_type)
  590. << TheCall->getDirectCallee() << "'ndrange_t'";
  591. return true;
  592. }
  593. // With four arguments, there is only one form that the function could be
  594. // called in: no events and no variable arguments.
  595. if (NumArgs == 4) {
  596. // check that the last argument is the right block type.
  597. if (!isBlockPointer(Arg3)) {
  598. S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  599. << TheCall->getDirectCallee() << "block";
  600. return true;
  601. }
  602. // we have a block type, check the prototype
  603. const BlockPointerType *BPT =
  604. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  605. if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
  606. S.Diag(Arg3->getBeginLoc(),
  607. diag::err_opencl_enqueue_kernel_blocks_no_args);
  608. return true;
  609. }
  610. return false;
  611. }
  612. // we can have block + varargs.
  613. if (isBlockPointer(Arg3))
  614. return (checkOpenCLBlockArgs(S, Arg3) ||
  615. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  616. // last two cases with either exactly 7 args or 7 args and varargs.
  617. if (NumArgs >= 7) {
  618. // check common block argument.
  619. Expr *Arg6 = TheCall->getArg(6);
  620. if (!isBlockPointer(Arg6)) {
  621. S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  622. << TheCall->getDirectCallee() << "block";
  623. return true;
  624. }
  625. if (checkOpenCLBlockArgs(S, Arg6))
  626. return true;
  627. // Forth argument has to be any integer type.
  628. if (!Arg3->getType()->isIntegerType()) {
  629. S.Diag(TheCall->getArg(3)->getBeginLoc(),
  630. diag::err_opencl_builtin_expected_type)
  631. << TheCall->getDirectCallee() << "integer";
  632. return true;
  633. }
  634. // check remaining common arguments.
  635. Expr *Arg4 = TheCall->getArg(4);
  636. Expr *Arg5 = TheCall->getArg(5);
  637. // Fifth argument is always passed as a pointer to clk_event_t.
  638. if (!Arg4->isNullPointerConstant(S.Context,
  639. Expr::NPC_ValueDependentIsNotNull) &&
  640. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  641. S.Diag(TheCall->getArg(4)->getBeginLoc(),
  642. diag::err_opencl_builtin_expected_type)
  643. << TheCall->getDirectCallee()
  644. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  645. return true;
  646. }
  647. // Sixth argument is always passed as a pointer to clk_event_t.
  648. if (!Arg5->isNullPointerConstant(S.Context,
  649. Expr::NPC_ValueDependentIsNotNull) &&
  650. !(Arg5->getType()->isPointerType() &&
  651. Arg5->getType()->getPointeeType()->isClkEventT())) {
  652. S.Diag(TheCall->getArg(5)->getBeginLoc(),
  653. diag::err_opencl_builtin_expected_type)
  654. << TheCall->getDirectCallee()
  655. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  656. return true;
  657. }
  658. if (NumArgs == 7)
  659. return false;
  660. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  661. }
  662. // None of the specific case has been detected, give generic error
  663. S.Diag(TheCall->getBeginLoc(),
  664. diag::err_opencl_enqueue_kernel_incorrect_args);
  665. return true;
  666. }
  667. /// Returns OpenCL access qual.
  668. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  669. return D->getAttr<OpenCLAccessAttr>();
  670. }
  671. /// Returns true if pipe element type is different from the pointer.
  672. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  673. const Expr *Arg0 = Call->getArg(0);
  674. // First argument type should always be pipe.
  675. if (!Arg0->getType()->isPipeType()) {
  676. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  677. << Call->getDirectCallee() << Arg0->getSourceRange();
  678. return true;
  679. }
  680. OpenCLAccessAttr *AccessQual =
  681. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  682. // Validates the access qualifier is compatible with the call.
  683. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  684. // read_only and write_only, and assumed to be read_only if no qualifier is
  685. // specified.
  686. switch (Call->getDirectCallee()->getBuiltinID()) {
  687. case Builtin::BIread_pipe:
  688. case Builtin::BIreserve_read_pipe:
  689. case Builtin::BIcommit_read_pipe:
  690. case Builtin::BIwork_group_reserve_read_pipe:
  691. case Builtin::BIsub_group_reserve_read_pipe:
  692. case Builtin::BIwork_group_commit_read_pipe:
  693. case Builtin::BIsub_group_commit_read_pipe:
  694. if (!(!AccessQual || AccessQual->isReadOnly())) {
  695. S.Diag(Arg0->getBeginLoc(),
  696. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  697. << "read_only" << Arg0->getSourceRange();
  698. return true;
  699. }
  700. break;
  701. case Builtin::BIwrite_pipe:
  702. case Builtin::BIreserve_write_pipe:
  703. case Builtin::BIcommit_write_pipe:
  704. case Builtin::BIwork_group_reserve_write_pipe:
  705. case Builtin::BIsub_group_reserve_write_pipe:
  706. case Builtin::BIwork_group_commit_write_pipe:
  707. case Builtin::BIsub_group_commit_write_pipe:
  708. if (!(AccessQual && AccessQual->isWriteOnly())) {
  709. S.Diag(Arg0->getBeginLoc(),
  710. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  711. << "write_only" << Arg0->getSourceRange();
  712. return true;
  713. }
  714. break;
  715. default:
  716. break;
  717. }
  718. return false;
  719. }
  720. /// Returns true if pipe element type is different from the pointer.
  721. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  722. const Expr *Arg0 = Call->getArg(0);
  723. const Expr *ArgIdx = Call->getArg(Idx);
  724. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  725. const QualType EltTy = PipeTy->getElementType();
  726. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  727. // The Idx argument should be a pointer and the type of the pointer and
  728. // the type of pipe element should also be the same.
  729. if (!ArgTy ||
  730. !S.Context.hasSameType(
  731. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  732. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  733. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  734. << ArgIdx->getType() << ArgIdx->getSourceRange();
  735. return true;
  736. }
  737. return false;
  738. }
  739. // Performs semantic analysis for the read/write_pipe call.
  740. // \param S Reference to the semantic analyzer.
  741. // \param Call A pointer to the builtin call.
  742. // \return True if a semantic error has been found, false otherwise.
  743. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  744. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  745. // functions have two forms.
  746. switch (Call->getNumArgs()) {
  747. case 2:
  748. if (checkOpenCLPipeArg(S, Call))
  749. return true;
  750. // The call with 2 arguments should be
  751. // read/write_pipe(pipe T, T*).
  752. // Check packet type T.
  753. if (checkOpenCLPipePacketType(S, Call, 1))
  754. return true;
  755. break;
  756. case 4: {
  757. if (checkOpenCLPipeArg(S, Call))
  758. return true;
  759. // The call with 4 arguments should be
  760. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  761. // Check reserve_id_t.
  762. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  763. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  764. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  765. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  766. return true;
  767. }
  768. // Check the index.
  769. const Expr *Arg2 = Call->getArg(2);
  770. if (!Arg2->getType()->isIntegerType() &&
  771. !Arg2->getType()->isUnsignedIntegerType()) {
  772. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  773. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  774. << Arg2->getType() << Arg2->getSourceRange();
  775. return true;
  776. }
  777. // Check packet type T.
  778. if (checkOpenCLPipePacketType(S, Call, 3))
  779. return true;
  780. } break;
  781. default:
  782. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
  783. << Call->getDirectCallee() << Call->getSourceRange();
  784. return true;
  785. }
  786. return false;
  787. }
  788. // Performs a semantic analysis on the {work_group_/sub_group_
  789. // /_}reserve_{read/write}_pipe
  790. // \param S Reference to the semantic analyzer.
  791. // \param Call The call to the builtin function to be analyzed.
  792. // \return True if a semantic error was found, false otherwise.
  793. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  794. if (checkArgCount(S, Call, 2))
  795. return true;
  796. if (checkOpenCLPipeArg(S, Call))
  797. return true;
  798. // Check the reserve size.
  799. if (!Call->getArg(1)->getType()->isIntegerType() &&
  800. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  801. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  802. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  803. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  804. return true;
  805. }
  806. // Since return type of reserve_read/write_pipe built-in function is
  807. // reserve_id_t, which is not defined in the builtin def file , we used int
  808. // as return type and need to override the return type of these functions.
  809. Call->setType(S.Context.OCLReserveIDTy);
  810. return false;
  811. }
  812. // Performs a semantic analysis on {work_group_/sub_group_
  813. // /_}commit_{read/write}_pipe
  814. // \param S Reference to the semantic analyzer.
  815. // \param Call The call to the builtin function to be analyzed.
  816. // \return True if a semantic error was found, false otherwise.
  817. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  818. if (checkArgCount(S, Call, 2))
  819. return true;
  820. if (checkOpenCLPipeArg(S, Call))
  821. return true;
  822. // Check reserve_id_t.
  823. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  824. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  825. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  826. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  827. return true;
  828. }
  829. return false;
  830. }
  831. // Performs a semantic analysis on the call to built-in Pipe
  832. // Query Functions.
  833. // \param S Reference to the semantic analyzer.
  834. // \param Call The call to the builtin function to be analyzed.
  835. // \return True if a semantic error was found, false otherwise.
  836. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  837. if (checkArgCount(S, Call, 1))
  838. return true;
  839. if (!Call->getArg(0)->getType()->isPipeType()) {
  840. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  841. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  842. return true;
  843. }
  844. return false;
  845. }
  846. // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  847. // Performs semantic analysis for the to_global/local/private call.
  848. // \param S Reference to the semantic analyzer.
  849. // \param BuiltinID ID of the builtin function.
  850. // \param Call A pointer to the builtin call.
  851. // \return True if a semantic error has been found, false otherwise.
  852. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  853. CallExpr *Call) {
  854. if (Call->getNumArgs() != 1) {
  855. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
  856. << Call->getDirectCallee() << Call->getSourceRange();
  857. return true;
  858. }
  859. auto RT = Call->getArg(0)->getType();
  860. if (!RT->isPointerType() || RT->getPointeeType()
  861. .getAddressSpace() == LangAS::opencl_constant) {
  862. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
  863. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  864. return true;
  865. }
  866. if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
  867. S.Diag(Call->getArg(0)->getBeginLoc(),
  868. diag::warn_opencl_generic_address_space_arg)
  869. << Call->getDirectCallee()->getNameInfo().getAsString()
  870. << Call->getArg(0)->getSourceRange();
  871. }
  872. RT = RT->getPointeeType();
  873. auto Qual = RT.getQualifiers();
  874. switch (BuiltinID) {
  875. case Builtin::BIto_global:
  876. Qual.setAddressSpace(LangAS::opencl_global);
  877. break;
  878. case Builtin::BIto_local:
  879. Qual.setAddressSpace(LangAS::opencl_local);
  880. break;
  881. case Builtin::BIto_private:
  882. Qual.setAddressSpace(LangAS::opencl_private);
  883. break;
  884. default:
  885. llvm_unreachable("Invalid builtin function");
  886. }
  887. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  888. RT.getUnqualifiedType(), Qual)));
  889. return false;
  890. }
  891. static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
  892. if (checkArgCount(S, TheCall, 1))
  893. return ExprError();
  894. // Compute __builtin_launder's parameter type from the argument.
  895. // The parameter type is:
  896. // * The type of the argument if it's not an array or function type,
  897. // Otherwise,
  898. // * The decayed argument type.
  899. QualType ParamTy = [&]() {
  900. QualType ArgTy = TheCall->getArg(0)->getType();
  901. if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
  902. return S.Context.getPointerType(Ty->getElementType());
  903. if (ArgTy->isFunctionType()) {
  904. return S.Context.getPointerType(ArgTy);
  905. }
  906. return ArgTy;
  907. }();
  908. TheCall->setType(ParamTy);
  909. auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
  910. if (!ParamTy->isPointerType())
  911. return 0;
  912. if (ParamTy->isFunctionPointerType())
  913. return 1;
  914. if (ParamTy->isVoidPointerType())
  915. return 2;
  916. return llvm::Optional<unsigned>{};
  917. }();
  918. if (DiagSelect.hasValue()) {
  919. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
  920. << DiagSelect.getValue() << TheCall->getSourceRange();
  921. return ExprError();
  922. }
  923. // We either have an incomplete class type, or we have a class template
  924. // whose instantiation has not been forced. Example:
  925. //
  926. // template <class T> struct Foo { T value; };
  927. // Foo<int> *p = nullptr;
  928. // auto *d = __builtin_launder(p);
  929. if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
  930. diag::err_incomplete_type))
  931. return ExprError();
  932. assert(ParamTy->getPointeeType()->isObjectType() &&
  933. "Unhandled non-object pointer case");
  934. InitializedEntity Entity =
  935. InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
  936. ExprResult Arg =
  937. S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
  938. if (Arg.isInvalid())
  939. return ExprError();
  940. TheCall->setArg(0, Arg.get());
  941. return TheCall;
  942. }
  943. // Emit an error and return true if the current architecture is not in the list
  944. // of supported architectures.
  945. static bool
  946. CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
  947. ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
  948. llvm::Triple::ArchType CurArch =
  949. S.getASTContext().getTargetInfo().getTriple().getArch();
  950. if (llvm::is_contained(SupportedArchs, CurArch))
  951. return false;
  952. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  953. << TheCall->getSourceRange();
  954. return true;
  955. }
  956. ExprResult
  957. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  958. CallExpr *TheCall) {
  959. ExprResult TheCallResult(TheCall);
  960. // Find out if any arguments are required to be integer constant expressions.
  961. unsigned ICEArguments = 0;
  962. ASTContext::GetBuiltinTypeError Error;
  963. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  964. if (Error != ASTContext::GE_None)
  965. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  966. // If any arguments are required to be ICE's, check and diagnose.
  967. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  968. // Skip arguments not required to be ICE's.
  969. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  970. llvm::APSInt Result;
  971. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  972. return true;
  973. ICEArguments &= ~(1 << ArgNo);
  974. }
  975. switch (BuiltinID) {
  976. case Builtin::BI__builtin___CFStringMakeConstantString:
  977. assert(TheCall->getNumArgs() == 1 &&
  978. "Wrong # arguments to builtin CFStringMakeConstantString");
  979. if (CheckObjCString(TheCall->getArg(0)))
  980. return ExprError();
  981. break;
  982. case Builtin::BI__builtin_ms_va_start:
  983. case Builtin::BI__builtin_stdarg_start:
  984. case Builtin::BI__builtin_va_start:
  985. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  986. return ExprError();
  987. break;
  988. case Builtin::BI__va_start: {
  989. switch (Context.getTargetInfo().getTriple().getArch()) {
  990. case llvm::Triple::aarch64:
  991. case llvm::Triple::arm:
  992. case llvm::Triple::thumb:
  993. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  994. return ExprError();
  995. break;
  996. default:
  997. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  998. return ExprError();
  999. break;
  1000. }
  1001. break;
  1002. }
  1003. // The acquire, release, and no fence variants are ARM and AArch64 only.
  1004. case Builtin::BI_interlockedbittestandset_acq:
  1005. case Builtin::BI_interlockedbittestandset_rel:
  1006. case Builtin::BI_interlockedbittestandset_nf:
  1007. case Builtin::BI_interlockedbittestandreset_acq:
  1008. case Builtin::BI_interlockedbittestandreset_rel:
  1009. case Builtin::BI_interlockedbittestandreset_nf:
  1010. if (CheckBuiltinTargetSupport(
  1011. *this, BuiltinID, TheCall,
  1012. {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
  1013. return ExprError();
  1014. break;
  1015. // The 64-bit bittest variants are x64, ARM, and AArch64 only.
  1016. case Builtin::BI_bittest64:
  1017. case Builtin::BI_bittestandcomplement64:
  1018. case Builtin::BI_bittestandreset64:
  1019. case Builtin::BI_bittestandset64:
  1020. case Builtin::BI_interlockedbittestandreset64:
  1021. case Builtin::BI_interlockedbittestandset64:
  1022. if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
  1023. {llvm::Triple::x86_64, llvm::Triple::arm,
  1024. llvm::Triple::thumb, llvm::Triple::aarch64}))
  1025. return ExprError();
  1026. break;
  1027. case Builtin::BI__builtin_isgreater:
  1028. case Builtin::BI__builtin_isgreaterequal:
  1029. case Builtin::BI__builtin_isless:
  1030. case Builtin::BI__builtin_islessequal:
  1031. case Builtin::BI__builtin_islessgreater:
  1032. case Builtin::BI__builtin_isunordered:
  1033. if (SemaBuiltinUnorderedCompare(TheCall))
  1034. return ExprError();
  1035. break;
  1036. case Builtin::BI__builtin_fpclassify:
  1037. if (SemaBuiltinFPClassification(TheCall, 6))
  1038. return ExprError();
  1039. break;
  1040. case Builtin::BI__builtin_isfinite:
  1041. case Builtin::BI__builtin_isinf:
  1042. case Builtin::BI__builtin_isinf_sign:
  1043. case Builtin::BI__builtin_isnan:
  1044. case Builtin::BI__builtin_isnormal:
  1045. case Builtin::BI__builtin_signbit:
  1046. case Builtin::BI__builtin_signbitf:
  1047. case Builtin::BI__builtin_signbitl:
  1048. if (SemaBuiltinFPClassification(TheCall, 1))
  1049. return ExprError();
  1050. break;
  1051. case Builtin::BI__builtin_shufflevector:
  1052. return SemaBuiltinShuffleVector(TheCall);
  1053. // TheCall will be freed by the smart pointer here, but that's fine, since
  1054. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  1055. case Builtin::BI__builtin_prefetch:
  1056. if (SemaBuiltinPrefetch(TheCall))
  1057. return ExprError();
  1058. break;
  1059. case Builtin::BI__builtin_alloca_with_align:
  1060. if (SemaBuiltinAllocaWithAlign(TheCall))
  1061. return ExprError();
  1062. LLVM_FALLTHROUGH;
  1063. case Builtin::BI__builtin_alloca:
  1064. Diag(TheCall->getBeginLoc(), diag::warn_alloca)
  1065. << TheCall->getDirectCallee();
  1066. break;
  1067. case Builtin::BI__assume:
  1068. case Builtin::BI__builtin_assume:
  1069. if (SemaBuiltinAssume(TheCall))
  1070. return ExprError();
  1071. break;
  1072. case Builtin::BI__builtin_assume_aligned:
  1073. if (SemaBuiltinAssumeAligned(TheCall))
  1074. return ExprError();
  1075. break;
  1076. case Builtin::BI__builtin_dynamic_object_size:
  1077. case Builtin::BI__builtin_object_size:
  1078. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  1079. return ExprError();
  1080. break;
  1081. case Builtin::BI__builtin_longjmp:
  1082. if (SemaBuiltinLongjmp(TheCall))
  1083. return ExprError();
  1084. break;
  1085. case Builtin::BI__builtin_setjmp:
  1086. if (SemaBuiltinSetjmp(TheCall))
  1087. return ExprError();
  1088. break;
  1089. case Builtin::BI_setjmp:
  1090. case Builtin::BI_setjmpex:
  1091. if (checkArgCount(*this, TheCall, 1))
  1092. return true;
  1093. break;
  1094. case Builtin::BI__builtin_classify_type:
  1095. if (checkArgCount(*this, TheCall, 1)) return true;
  1096. TheCall->setType(Context.IntTy);
  1097. break;
  1098. case Builtin::BI__builtin_constant_p: {
  1099. if (checkArgCount(*this, TheCall, 1)) return true;
  1100. ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
  1101. if (Arg.isInvalid()) return true;
  1102. TheCall->setArg(0, Arg.get());
  1103. TheCall->setType(Context.IntTy);
  1104. break;
  1105. }
  1106. case Builtin::BI__builtin_launder:
  1107. return SemaBuiltinLaunder(*this, TheCall);
  1108. case Builtin::BI__sync_fetch_and_add:
  1109. case Builtin::BI__sync_fetch_and_add_1:
  1110. case Builtin::BI__sync_fetch_and_add_2:
  1111. case Builtin::BI__sync_fetch_and_add_4:
  1112. case Builtin::BI__sync_fetch_and_add_8:
  1113. case Builtin::BI__sync_fetch_and_add_16:
  1114. case Builtin::BI__sync_fetch_and_sub:
  1115. case Builtin::BI__sync_fetch_and_sub_1:
  1116. case Builtin::BI__sync_fetch_and_sub_2:
  1117. case Builtin::BI__sync_fetch_and_sub_4:
  1118. case Builtin::BI__sync_fetch_and_sub_8:
  1119. case Builtin::BI__sync_fetch_and_sub_16:
  1120. case Builtin::BI__sync_fetch_and_or:
  1121. case Builtin::BI__sync_fetch_and_or_1:
  1122. case Builtin::BI__sync_fetch_and_or_2:
  1123. case Builtin::BI__sync_fetch_and_or_4:
  1124. case Builtin::BI__sync_fetch_and_or_8:
  1125. case Builtin::BI__sync_fetch_and_or_16:
  1126. case Builtin::BI__sync_fetch_and_and:
  1127. case Builtin::BI__sync_fetch_and_and_1:
  1128. case Builtin::BI__sync_fetch_and_and_2:
  1129. case Builtin::BI__sync_fetch_and_and_4:
  1130. case Builtin::BI__sync_fetch_and_and_8:
  1131. case Builtin::BI__sync_fetch_and_and_16:
  1132. case Builtin::BI__sync_fetch_and_xor:
  1133. case Builtin::BI__sync_fetch_and_xor_1:
  1134. case Builtin::BI__sync_fetch_and_xor_2:
  1135. case Builtin::BI__sync_fetch_and_xor_4:
  1136. case Builtin::BI__sync_fetch_and_xor_8:
  1137. case Builtin::BI__sync_fetch_and_xor_16:
  1138. case Builtin::BI__sync_fetch_and_nand:
  1139. case Builtin::BI__sync_fetch_and_nand_1:
  1140. case Builtin::BI__sync_fetch_and_nand_2:
  1141. case Builtin::BI__sync_fetch_and_nand_4:
  1142. case Builtin::BI__sync_fetch_and_nand_8:
  1143. case Builtin::BI__sync_fetch_and_nand_16:
  1144. case Builtin::BI__sync_add_and_fetch:
  1145. case Builtin::BI__sync_add_and_fetch_1:
  1146. case Builtin::BI__sync_add_and_fetch_2:
  1147. case Builtin::BI__sync_add_and_fetch_4:
  1148. case Builtin::BI__sync_add_and_fetch_8:
  1149. case Builtin::BI__sync_add_and_fetch_16:
  1150. case Builtin::BI__sync_sub_and_fetch:
  1151. case Builtin::BI__sync_sub_and_fetch_1:
  1152. case Builtin::BI__sync_sub_and_fetch_2:
  1153. case Builtin::BI__sync_sub_and_fetch_4:
  1154. case Builtin::BI__sync_sub_and_fetch_8:
  1155. case Builtin::BI__sync_sub_and_fetch_16:
  1156. case Builtin::BI__sync_and_and_fetch:
  1157. case Builtin::BI__sync_and_and_fetch_1:
  1158. case Builtin::BI__sync_and_and_fetch_2:
  1159. case Builtin::BI__sync_and_and_fetch_4:
  1160. case Builtin::BI__sync_and_and_fetch_8:
  1161. case Builtin::BI__sync_and_and_fetch_16:
  1162. case Builtin::BI__sync_or_and_fetch:
  1163. case Builtin::BI__sync_or_and_fetch_1:
  1164. case Builtin::BI__sync_or_and_fetch_2:
  1165. case Builtin::BI__sync_or_and_fetch_4:
  1166. case Builtin::BI__sync_or_and_fetch_8:
  1167. case Builtin::BI__sync_or_and_fetch_16:
  1168. case Builtin::BI__sync_xor_and_fetch:
  1169. case Builtin::BI__sync_xor_and_fetch_1:
  1170. case Builtin::BI__sync_xor_and_fetch_2:
  1171. case Builtin::BI__sync_xor_and_fetch_4:
  1172. case Builtin::BI__sync_xor_and_fetch_8:
  1173. case Builtin::BI__sync_xor_and_fetch_16:
  1174. case Builtin::BI__sync_nand_and_fetch:
  1175. case Builtin::BI__sync_nand_and_fetch_1:
  1176. case Builtin::BI__sync_nand_and_fetch_2:
  1177. case Builtin::BI__sync_nand_and_fetch_4:
  1178. case Builtin::BI__sync_nand_and_fetch_8:
  1179. case Builtin::BI__sync_nand_and_fetch_16:
  1180. case Builtin::BI__sync_val_compare_and_swap:
  1181. case Builtin::BI__sync_val_compare_and_swap_1:
  1182. case Builtin::BI__sync_val_compare_and_swap_2:
  1183. case Builtin::BI__sync_val_compare_and_swap_4:
  1184. case Builtin::BI__sync_val_compare_and_swap_8:
  1185. case Builtin::BI__sync_val_compare_and_swap_16:
  1186. case Builtin::BI__sync_bool_compare_and_swap:
  1187. case Builtin::BI__sync_bool_compare_and_swap_1:
  1188. case Builtin::BI__sync_bool_compare_and_swap_2:
  1189. case Builtin::BI__sync_bool_compare_and_swap_4:
  1190. case Builtin::BI__sync_bool_compare_and_swap_8:
  1191. case Builtin::BI__sync_bool_compare_and_swap_16:
  1192. case Builtin::BI__sync_lock_test_and_set:
  1193. case Builtin::BI__sync_lock_test_and_set_1:
  1194. case Builtin::BI__sync_lock_test_and_set_2:
  1195. case Builtin::BI__sync_lock_test_and_set_4:
  1196. case Builtin::BI__sync_lock_test_and_set_8:
  1197. case Builtin::BI__sync_lock_test_and_set_16:
  1198. case Builtin::BI__sync_lock_release:
  1199. case Builtin::BI__sync_lock_release_1:
  1200. case Builtin::BI__sync_lock_release_2:
  1201. case Builtin::BI__sync_lock_release_4:
  1202. case Builtin::BI__sync_lock_release_8:
  1203. case Builtin::BI__sync_lock_release_16:
  1204. case Builtin::BI__sync_swap:
  1205. case Builtin::BI__sync_swap_1:
  1206. case Builtin::BI__sync_swap_2:
  1207. case Builtin::BI__sync_swap_4:
  1208. case Builtin::BI__sync_swap_8:
  1209. case Builtin::BI__sync_swap_16:
  1210. return SemaBuiltinAtomicOverloaded(TheCallResult);
  1211. case Builtin::BI__sync_synchronize:
  1212. Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
  1213. << TheCall->getCallee()->getSourceRange();
  1214. break;
  1215. case Builtin::BI__builtin_nontemporal_load:
  1216. case Builtin::BI__builtin_nontemporal_store:
  1217. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  1218. #define BUILTIN(ID, TYPE, ATTRS)
  1219. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  1220. case Builtin::BI##ID: \
  1221. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  1222. #include "clang/Basic/Builtins.def"
  1223. case Builtin::BI__annotation:
  1224. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  1225. return ExprError();
  1226. break;
  1227. case Builtin::BI__builtin_annotation:
  1228. if (SemaBuiltinAnnotation(*this, TheCall))
  1229. return ExprError();
  1230. break;
  1231. case Builtin::BI__builtin_addressof:
  1232. if (SemaBuiltinAddressof(*this, TheCall))
  1233. return ExprError();
  1234. break;
  1235. case Builtin::BI__builtin_add_overflow:
  1236. case Builtin::BI__builtin_sub_overflow:
  1237. case Builtin::BI__builtin_mul_overflow:
  1238. if (SemaBuiltinOverflow(*this, TheCall))
  1239. return ExprError();
  1240. break;
  1241. case Builtin::BI__builtin_operator_new:
  1242. case Builtin::BI__builtin_operator_delete: {
  1243. bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
  1244. ExprResult Res =
  1245. SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
  1246. if (Res.isInvalid())
  1247. CorrectDelayedTyposInExpr(TheCallResult.get());
  1248. return Res;
  1249. }
  1250. case Builtin::BI__builtin_dump_struct: {
  1251. // We first want to ensure we are called with 2 arguments
  1252. if (checkArgCount(*this, TheCall, 2))
  1253. return ExprError();
  1254. // Ensure that the first argument is of type 'struct XX *'
  1255. const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
  1256. const QualType PtrArgType = PtrArg->getType();
  1257. if (!PtrArgType->isPointerType() ||
  1258. !PtrArgType->getPointeeType()->isRecordType()) {
  1259. Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1260. << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
  1261. << "structure pointer";
  1262. return ExprError();
  1263. }
  1264. // Ensure that the second argument is of type 'FunctionType'
  1265. const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
  1266. const QualType FnPtrArgType = FnPtrArg->getType();
  1267. if (!FnPtrArgType->isPointerType()) {
  1268. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1269. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1270. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1271. return ExprError();
  1272. }
  1273. const auto *FuncType =
  1274. FnPtrArgType->getPointeeType()->getAs<FunctionType>();
  1275. if (!FuncType) {
  1276. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1277. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1278. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1279. return ExprError();
  1280. }
  1281. if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
  1282. if (!FT->getNumParams()) {
  1283. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1284. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1285. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1286. return ExprError();
  1287. }
  1288. QualType PT = FT->getParamType(0);
  1289. if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
  1290. !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
  1291. !PT->getPointeeType().isConstQualified()) {
  1292. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1293. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1294. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1295. return ExprError();
  1296. }
  1297. }
  1298. TheCall->setType(Context.IntTy);
  1299. break;
  1300. }
  1301. case Builtin::BI__builtin_preserve_access_index:
  1302. if (SemaBuiltinPreserveAI(*this, TheCall))
  1303. return ExprError();
  1304. break;
  1305. case Builtin::BI__builtin_call_with_static_chain:
  1306. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  1307. return ExprError();
  1308. break;
  1309. case Builtin::BI__exception_code:
  1310. case Builtin::BI_exception_code:
  1311. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  1312. diag::err_seh___except_block))
  1313. return ExprError();
  1314. break;
  1315. case Builtin::BI__exception_info:
  1316. case Builtin::BI_exception_info:
  1317. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  1318. diag::err_seh___except_filter))
  1319. return ExprError();
  1320. break;
  1321. case Builtin::BI__GetExceptionInfo:
  1322. if (checkArgCount(*this, TheCall, 1))
  1323. return ExprError();
  1324. if (CheckCXXThrowOperand(
  1325. TheCall->getBeginLoc(),
  1326. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1327. TheCall))
  1328. return ExprError();
  1329. TheCall->setType(Context.VoidPtrTy);
  1330. break;
  1331. // OpenCL v2.0, s6.13.16 - Pipe functions
  1332. case Builtin::BIread_pipe:
  1333. case Builtin::BIwrite_pipe:
  1334. // Since those two functions are declared with var args, we need a semantic
  1335. // check for the argument.
  1336. if (SemaBuiltinRWPipe(*this, TheCall))
  1337. return ExprError();
  1338. break;
  1339. case Builtin::BIreserve_read_pipe:
  1340. case Builtin::BIreserve_write_pipe:
  1341. case Builtin::BIwork_group_reserve_read_pipe:
  1342. case Builtin::BIwork_group_reserve_write_pipe:
  1343. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1344. return ExprError();
  1345. break;
  1346. case Builtin::BIsub_group_reserve_read_pipe:
  1347. case Builtin::BIsub_group_reserve_write_pipe:
  1348. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1349. SemaBuiltinReserveRWPipe(*this, TheCall))
  1350. return ExprError();
  1351. break;
  1352. case Builtin::BIcommit_read_pipe:
  1353. case Builtin::BIcommit_write_pipe:
  1354. case Builtin::BIwork_group_commit_read_pipe:
  1355. case Builtin::BIwork_group_commit_write_pipe:
  1356. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1357. return ExprError();
  1358. break;
  1359. case Builtin::BIsub_group_commit_read_pipe:
  1360. case Builtin::BIsub_group_commit_write_pipe:
  1361. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1362. SemaBuiltinCommitRWPipe(*this, TheCall))
  1363. return ExprError();
  1364. break;
  1365. case Builtin::BIget_pipe_num_packets:
  1366. case Builtin::BIget_pipe_max_packets:
  1367. if (SemaBuiltinPipePackets(*this, TheCall))
  1368. return ExprError();
  1369. break;
  1370. case Builtin::BIto_global:
  1371. case Builtin::BIto_local:
  1372. case Builtin::BIto_private:
  1373. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1374. return ExprError();
  1375. break;
  1376. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1377. case Builtin::BIenqueue_kernel:
  1378. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1379. return ExprError();
  1380. break;
  1381. case Builtin::BIget_kernel_work_group_size:
  1382. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1383. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1384. return ExprError();
  1385. break;
  1386. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1387. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1388. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1389. return ExprError();
  1390. break;
  1391. case Builtin::BI__builtin_os_log_format:
  1392. case Builtin::BI__builtin_os_log_format_buffer_size:
  1393. if (SemaBuiltinOSLogFormat(TheCall))
  1394. return ExprError();
  1395. break;
  1396. }
  1397. // Since the target specific builtins for each arch overlap, only check those
  1398. // of the arch we are compiling for.
  1399. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  1400. switch (Context.getTargetInfo().getTriple().getArch()) {
  1401. case llvm::Triple::arm:
  1402. case llvm::Triple::armeb:
  1403. case llvm::Triple::thumb:
  1404. case llvm::Triple::thumbeb:
  1405. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  1406. return ExprError();
  1407. break;
  1408. case llvm::Triple::aarch64:
  1409. case llvm::Triple::aarch64_be:
  1410. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  1411. return ExprError();
  1412. break;
  1413. case llvm::Triple::hexagon:
  1414. if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
  1415. return ExprError();
  1416. break;
  1417. case llvm::Triple::mips:
  1418. case llvm::Triple::mipsel:
  1419. case llvm::Triple::mips64:
  1420. case llvm::Triple::mips64el:
  1421. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  1422. return ExprError();
  1423. break;
  1424. case llvm::Triple::systemz:
  1425. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  1426. return ExprError();
  1427. break;
  1428. case llvm::Triple::x86:
  1429. case llvm::Triple::x86_64:
  1430. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  1431. return ExprError();
  1432. break;
  1433. case llvm::Triple::ppc:
  1434. case llvm::Triple::ppc64:
  1435. case llvm::Triple::ppc64le:
  1436. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  1437. return ExprError();
  1438. break;
  1439. default:
  1440. break;
  1441. }
  1442. }
  1443. return TheCallResult;
  1444. }
  1445. // Get the valid immediate range for the specified NEON type code.
  1446. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  1447. NeonTypeFlags Type(t);
  1448. int IsQuad = ForceQuad ? true : Type.isQuad();
  1449. switch (Type.getEltType()) {
  1450. case NeonTypeFlags::Int8:
  1451. case NeonTypeFlags::Poly8:
  1452. return shift ? 7 : (8 << IsQuad) - 1;
  1453. case NeonTypeFlags::Int16:
  1454. case NeonTypeFlags::Poly16:
  1455. return shift ? 15 : (4 << IsQuad) - 1;
  1456. case NeonTypeFlags::Int32:
  1457. return shift ? 31 : (2 << IsQuad) - 1;
  1458. case NeonTypeFlags::Int64:
  1459. case NeonTypeFlags::Poly64:
  1460. return shift ? 63 : (1 << IsQuad) - 1;
  1461. case NeonTypeFlags::Poly128:
  1462. return shift ? 127 : (1 << IsQuad) - 1;
  1463. case NeonTypeFlags::Float16:
  1464. assert(!shift && "cannot shift float types!");
  1465. return (4 << IsQuad) - 1;
  1466. case NeonTypeFlags::Float32:
  1467. assert(!shift && "cannot shift float types!");
  1468. return (2 << IsQuad) - 1;
  1469. case NeonTypeFlags::Float64:
  1470. assert(!shift && "cannot shift float types!");
  1471. return (1 << IsQuad) - 1;
  1472. }
  1473. llvm_unreachable("Invalid NeonTypeFlag!");
  1474. }
  1475. /// getNeonEltType - Return the QualType corresponding to the elements of
  1476. /// the vector type specified by the NeonTypeFlags. This is used to check
  1477. /// the pointer arguments for Neon load/store intrinsics.
  1478. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  1479. bool IsPolyUnsigned, bool IsInt64Long) {
  1480. switch (Flags.getEltType()) {
  1481. case NeonTypeFlags::Int8:
  1482. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  1483. case NeonTypeFlags::Int16:
  1484. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  1485. case NeonTypeFlags::Int32:
  1486. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  1487. case NeonTypeFlags::Int64:
  1488. if (IsInt64Long)
  1489. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  1490. else
  1491. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  1492. : Context.LongLongTy;
  1493. case NeonTypeFlags::Poly8:
  1494. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  1495. case NeonTypeFlags::Poly16:
  1496. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  1497. case NeonTypeFlags::Poly64:
  1498. if (IsInt64Long)
  1499. return Context.UnsignedLongTy;
  1500. else
  1501. return Context.UnsignedLongLongTy;
  1502. case NeonTypeFlags::Poly128:
  1503. break;
  1504. case NeonTypeFlags::Float16:
  1505. return Context.HalfTy;
  1506. case NeonTypeFlags::Float32:
  1507. return Context.FloatTy;
  1508. case NeonTypeFlags::Float64:
  1509. return Context.DoubleTy;
  1510. }
  1511. llvm_unreachable("Invalid NeonTypeFlag!");
  1512. }
  1513. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1514. llvm::APSInt Result;
  1515. uint64_t mask = 0;
  1516. unsigned TV = 0;
  1517. int PtrArgNum = -1;
  1518. bool HasConstPtr = false;
  1519. switch (BuiltinID) {
  1520. #define GET_NEON_OVERLOAD_CHECK
  1521. #include "clang/Basic/arm_neon.inc"
  1522. #include "clang/Basic/arm_fp16.inc"
  1523. #undef GET_NEON_OVERLOAD_CHECK
  1524. }
  1525. // For NEON intrinsics which are overloaded on vector element type, validate
  1526. // the immediate which specifies which variant to emit.
  1527. unsigned ImmArg = TheCall->getNumArgs()-1;
  1528. if (mask) {
  1529. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  1530. return true;
  1531. TV = Result.getLimitedValue(64);
  1532. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  1533. return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
  1534. << TheCall->getArg(ImmArg)->getSourceRange();
  1535. }
  1536. if (PtrArgNum >= 0) {
  1537. // Check that pointer arguments have the specified type.
  1538. Expr *Arg = TheCall->getArg(PtrArgNum);
  1539. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  1540. Arg = ICE->getSubExpr();
  1541. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  1542. QualType RHSTy = RHS.get()->getType();
  1543. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  1544. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  1545. Arch == llvm::Triple::aarch64_be;
  1546. bool IsInt64Long =
  1547. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  1548. QualType EltTy =
  1549. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  1550. if (HasConstPtr)
  1551. EltTy = EltTy.withConst();
  1552. QualType LHSTy = Context.getPointerType(EltTy);
  1553. AssignConvertType ConvTy;
  1554. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  1555. if (RHS.isInvalid())
  1556. return true;
  1557. if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
  1558. RHS.get(), AA_Assigning))
  1559. return true;
  1560. }
  1561. // For NEON intrinsics which take an immediate value as part of the
  1562. // instruction, range check them here.
  1563. unsigned i = 0, l = 0, u = 0;
  1564. switch (BuiltinID) {
  1565. default:
  1566. return false;
  1567. #define GET_NEON_IMMEDIATE_CHECK
  1568. #include "clang/Basic/arm_neon.inc"
  1569. #include "clang/Basic/arm_fp16.inc"
  1570. #undef GET_NEON_IMMEDIATE_CHECK
  1571. }
  1572. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1573. }
  1574. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  1575. unsigned MaxWidth) {
  1576. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1577. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1578. BuiltinID == ARM::BI__builtin_arm_strex ||
  1579. BuiltinID == ARM::BI__builtin_arm_stlex ||
  1580. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1581. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1582. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1583. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  1584. "unexpected ARM builtin");
  1585. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1586. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1587. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1588. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  1589. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1590. // Ensure that we have the proper number of arguments.
  1591. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  1592. return true;
  1593. // Inspect the pointer argument of the atomic builtin. This should always be
  1594. // a pointer type, whose element is an integral scalar or pointer type.
  1595. // Because it is a pointer type, we don't have to worry about any implicit
  1596. // casts here.
  1597. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  1598. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  1599. if (PointerArgRes.isInvalid())
  1600. return true;
  1601. PointerArg = PointerArgRes.get();
  1602. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  1603. if (!pointerType) {
  1604. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  1605. << PointerArg->getType() << PointerArg->getSourceRange();
  1606. return true;
  1607. }
  1608. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  1609. // task is to insert the appropriate casts into the AST. First work out just
  1610. // what the appropriate type is.
  1611. QualType ValType = pointerType->getPointeeType();
  1612. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  1613. if (IsLdrex)
  1614. AddrType.addConst();
  1615. // Issue a warning if the cast is dodgy.
  1616. CastKind CastNeeded = CK_NoOp;
  1617. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  1618. CastNeeded = CK_BitCast;
  1619. Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
  1620. << PointerArg->getType() << Context.getPointerType(AddrType)
  1621. << AA_Passing << PointerArg->getSourceRange();
  1622. }
  1623. // Finally, do the cast and replace the argument with the corrected version.
  1624. AddrType = Context.getPointerType(AddrType);
  1625. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  1626. if (PointerArgRes.isInvalid())
  1627. return true;
  1628. PointerArg = PointerArgRes.get();
  1629. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  1630. // In general, we allow ints, floats and pointers to be loaded and stored.
  1631. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1632. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  1633. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  1634. << PointerArg->getType() << PointerArg->getSourceRange();
  1635. return true;
  1636. }
  1637. // But ARM doesn't have instructions to deal with 128-bit versions.
  1638. if (Context.getTypeSize(ValType) > MaxWidth) {
  1639. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  1640. Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
  1641. << PointerArg->getType() << PointerArg->getSourceRange();
  1642. return true;
  1643. }
  1644. switch (ValType.getObjCLifetime()) {
  1645. case Qualifiers::OCL_None:
  1646. case Qualifiers::OCL_ExplicitNone:
  1647. // okay
  1648. break;
  1649. case Qualifiers::OCL_Weak:
  1650. case Qualifiers::OCL_Strong:
  1651. case Qualifiers::OCL_Autoreleasing:
  1652. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  1653. << ValType << PointerArg->getSourceRange();
  1654. return true;
  1655. }
  1656. if (IsLdrex) {
  1657. TheCall->setType(ValType);
  1658. return false;
  1659. }
  1660. // Initialize the argument to be stored.
  1661. ExprResult ValArg = TheCall->getArg(0);
  1662. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  1663. Context, ValType, /*consume*/ false);
  1664. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  1665. if (ValArg.isInvalid())
  1666. return true;
  1667. TheCall->setArg(0, ValArg.get());
  1668. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  1669. // but the custom checker bypasses all default analysis.
  1670. TheCall->setType(Context.IntTy);
  1671. return false;
  1672. }
  1673. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1674. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1675. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1676. BuiltinID == ARM::BI__builtin_arm_strex ||
  1677. BuiltinID == ARM::BI__builtin_arm_stlex) {
  1678. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  1679. }
  1680. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  1681. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1682. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  1683. }
  1684. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  1685. BuiltinID == ARM::BI__builtin_arm_wsr64)
  1686. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  1687. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  1688. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  1689. BuiltinID == ARM::BI__builtin_arm_wsr ||
  1690. BuiltinID == ARM::BI__builtin_arm_wsrp)
  1691. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1692. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1693. return true;
  1694. // For intrinsics which take an immediate value as part of the instruction,
  1695. // range check them here.
  1696. // FIXME: VFP Intrinsics should error if VFP not present.
  1697. switch (BuiltinID) {
  1698. default: return false;
  1699. case ARM::BI__builtin_arm_ssat:
  1700. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  1701. case ARM::BI__builtin_arm_usat:
  1702. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  1703. case ARM::BI__builtin_arm_ssat16:
  1704. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  1705. case ARM::BI__builtin_arm_usat16:
  1706. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  1707. case ARM::BI__builtin_arm_vcvtr_f:
  1708. case ARM::BI__builtin_arm_vcvtr_d:
  1709. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  1710. case ARM::BI__builtin_arm_dmb:
  1711. case ARM::BI__builtin_arm_dsb:
  1712. case ARM::BI__builtin_arm_isb:
  1713. case ARM::BI__builtin_arm_dbg:
  1714. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  1715. }
  1716. }
  1717. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  1718. CallExpr *TheCall) {
  1719. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1720. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1721. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1722. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  1723. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  1724. }
  1725. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  1726. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1727. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  1728. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  1729. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  1730. }
  1731. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  1732. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  1733. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1734. // Memory Tagging Extensions (MTE) Intrinsics
  1735. if (BuiltinID == AArch64::BI__builtin_arm_irg ||
  1736. BuiltinID == AArch64::BI__builtin_arm_addg ||
  1737. BuiltinID == AArch64::BI__builtin_arm_gmi ||
  1738. BuiltinID == AArch64::BI__builtin_arm_ldg ||
  1739. BuiltinID == AArch64::BI__builtin_arm_stg ||
  1740. BuiltinID == AArch64::BI__builtin_arm_subp) {
  1741. return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
  1742. }
  1743. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  1744. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  1745. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  1746. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  1747. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1748. // Only check the valid encoding range. Any constant in this range would be
  1749. // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
  1750. // an exception for incorrect registers. This matches MSVC behavior.
  1751. if (BuiltinID == AArch64::BI_ReadStatusReg ||
  1752. BuiltinID == AArch64::BI_WriteStatusReg)
  1753. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
  1754. if (BuiltinID == AArch64::BI__getReg)
  1755. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
  1756. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1757. return true;
  1758. // For intrinsics which take an immediate value as part of the instruction,
  1759. // range check them here.
  1760. unsigned i = 0, l = 0, u = 0;
  1761. switch (BuiltinID) {
  1762. default: return false;
  1763. case AArch64::BI__builtin_arm_dmb:
  1764. case AArch64::BI__builtin_arm_dsb:
  1765. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  1766. case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
  1767. }
  1768. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1769. }
  1770. bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
  1771. struct BuiltinAndString {
  1772. unsigned BuiltinID;
  1773. const char *Str;
  1774. };
  1775. static BuiltinAndString ValidCPU[] = {
  1776. { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
  1777. { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
  1778. { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
  1779. { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
  1780. { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
  1781. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
  1782. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
  1783. { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
  1784. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
  1785. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
  1786. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
  1787. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
  1788. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
  1789. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
  1790. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
  1791. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
  1792. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
  1793. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
  1794. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
  1795. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
  1796. { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
  1797. { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
  1798. { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
  1799. };
  1800. static BuiltinAndString ValidHVX[] = {
  1801. { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
  1802. { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
  1803. { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
  1804. { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
  1805. { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
  1806. { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
  1807. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
  1808. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
  1809. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
  1810. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
  1811. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
  1812. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
  1813. { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
  1814. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
  1815. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
  1816. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
  1817. { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
  1818. { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
  1819. { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
  1820. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
  1821. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
  1822. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
  1823. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
  1824. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
  1825. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
  1826. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
  1827. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
  1828. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
  1829. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
  1830. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
  1831. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
  1832. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
  1833. { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
  1834. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
  1835. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
  1836. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
  1837. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
  1838. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
  1839. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
  1840. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
  1841. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
  1842. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
  1843. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
  1844. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
  1845. { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
  1846. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
  1847. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
  1848. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
  1849. { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
  1850. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
  1851. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
  1852. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
  1853. { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
  1854. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
  1855. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
  1856. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
  1857. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
  1858. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
  1859. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
  1860. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
  1861. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
  1862. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
  1863. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
  1864. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
  1865. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
  1866. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
  1867. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
  1868. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
  1869. { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
  1870. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
  1871. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
  1872. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
  1873. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
  1874. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
  1875. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
  1876. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
  1877. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
  1878. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
  1879. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
  1880. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
  1881. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
  1882. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
  1883. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
  1884. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
  1885. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
  1886. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
  1887. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
  1888. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
  1889. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
  1890. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
  1891. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
  1892. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
  1893. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
  1894. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
  1895. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
  1896. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
  1897. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
  1898. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
  1899. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
  1900. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
  1901. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
  1902. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
  1903. { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
  1904. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
  1905. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
  1906. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
  1907. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
  1908. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
  1909. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
  1910. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
  1911. { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
  1912. { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
  1913. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
  1914. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
  1915. { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
  1916. { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
  1917. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
  1918. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
  1919. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
  1920. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
  1921. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
  1922. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
  1923. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
  1924. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
  1925. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
  1926. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
  1927. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
  1928. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
  1929. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
  1930. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
  1931. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
  1932. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
  1933. { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
  1934. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
  1935. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
  1936. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
  1937. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
  1938. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
  1939. { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
  1940. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
  1941. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
  1942. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
  1943. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
  1944. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
  1945. { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
  1946. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
  1947. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
  1948. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
  1949. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
  1950. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
  1951. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
  1952. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
  1953. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
  1954. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
  1955. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
  1956. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
  1957. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
  1958. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
  1959. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
  1960. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
  1961. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
  1962. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
  1963. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
  1964. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
  1965. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
  1966. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
  1967. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
  1968. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
  1969. { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
  1970. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
  1971. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
  1972. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
  1973. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
  1974. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
  1975. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
  1976. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
  1977. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
  1978. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
  1979. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
  1980. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
  1981. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
  1982. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
  1983. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
  1984. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
  1985. { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
  1986. { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
  1987. { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
  1988. { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
  1989. { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
  1990. { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
  1991. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
  1992. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
  1993. { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
  1994. { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
  1995. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
  1996. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
  1997. { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
  1998. { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
  1999. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
  2000. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
  2001. { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
  2002. { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
  2003. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
  2004. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
  2005. { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
  2006. { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
  2007. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
  2008. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
  2009. { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
  2010. { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
  2011. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
  2012. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
  2013. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
  2014. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
  2015. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
  2016. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
  2017. { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
  2018. { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
  2019. { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
  2020. { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
  2021. { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
  2022. { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
  2023. { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
  2024. { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
  2025. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
  2026. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
  2027. { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
  2028. { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
  2029. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
  2030. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
  2031. { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
  2032. { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
  2033. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
  2034. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
  2035. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
  2036. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
  2037. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
  2038. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
  2039. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
  2040. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
  2041. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
  2042. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
  2043. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
  2044. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
  2045. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
  2046. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
  2047. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
  2048. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
  2049. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
  2050. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
  2051. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
  2052. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
  2053. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
  2054. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
  2055. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
  2056. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
  2057. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
  2058. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
  2059. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
  2060. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
  2061. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
  2062. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
  2063. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
  2064. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
  2065. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
  2066. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
  2067. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
  2068. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
  2069. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
  2070. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
  2071. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
  2072. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
  2073. { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
  2074. { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
  2075. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
  2076. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
  2077. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
  2078. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
  2079. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
  2080. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
  2081. { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
  2082. { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
  2083. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
  2084. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
  2085. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
  2086. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
  2087. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
  2088. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
  2089. { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
  2090. { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
  2091. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
  2092. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
  2093. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
  2094. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
  2095. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
  2096. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
  2097. { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
  2098. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
  2099. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
  2100. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
  2101. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
  2102. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
  2103. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
  2104. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
  2105. { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
  2106. { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
  2107. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
  2108. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
  2109. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
  2110. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
  2111. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
  2112. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
  2113. { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
  2114. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
  2115. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
  2116. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
  2117. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
  2118. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
  2119. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
  2120. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
  2121. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
  2122. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
  2123. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
  2124. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
  2125. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
  2126. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
  2127. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
  2128. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
  2129. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
  2130. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
  2131. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
  2132. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
  2133. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
  2134. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
  2135. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
  2136. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
  2137. { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
  2138. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
  2139. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
  2140. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
  2141. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
  2142. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
  2143. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
  2144. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
  2145. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
  2146. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
  2147. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
  2148. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
  2149. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
  2150. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
  2151. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
  2152. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
  2153. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
  2154. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
  2155. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
  2156. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
  2157. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
  2158. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
  2159. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
  2160. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
  2161. { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
  2162. { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
  2163. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
  2164. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
  2165. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
  2166. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
  2167. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
  2168. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
  2169. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
  2170. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
  2171. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
  2172. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
  2173. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
  2174. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
  2175. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
  2176. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
  2177. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
  2178. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
  2179. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
  2180. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
  2181. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
  2182. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
  2183. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
  2184. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
  2185. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
  2186. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
  2187. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
  2188. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
  2189. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
  2190. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
  2191. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
  2192. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
  2193. { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
  2194. { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
  2195. { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
  2196. { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
  2197. { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
  2198. { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
  2199. { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
  2200. { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
  2201. { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
  2202. { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
  2203. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
  2204. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
  2205. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
  2206. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
  2207. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
  2208. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
  2209. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
  2210. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
  2211. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
  2212. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
  2213. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
  2214. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
  2215. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
  2216. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
  2217. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
  2218. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
  2219. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
  2220. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
  2221. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
  2222. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
  2223. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
  2224. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
  2225. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
  2226. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
  2227. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
  2228. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
  2229. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
  2230. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
  2231. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
  2232. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
  2233. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
  2234. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
  2235. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
  2236. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
  2237. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
  2238. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
  2239. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
  2240. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
  2241. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
  2242. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
  2243. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
  2244. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
  2245. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
  2246. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
  2247. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
  2248. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
  2249. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
  2250. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
  2251. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
  2252. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
  2253. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
  2254. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
  2255. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
  2256. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
  2257. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
  2258. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
  2259. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
  2260. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
  2261. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
  2262. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
  2263. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
  2264. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
  2265. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
  2266. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
  2267. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
  2268. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
  2269. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
  2270. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
  2271. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
  2272. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
  2273. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
  2274. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
  2275. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
  2276. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
  2277. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
  2278. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
  2279. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
  2280. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
  2281. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
  2282. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
  2283. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
  2284. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
  2285. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
  2286. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
  2287. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
  2288. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
  2289. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
  2290. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
  2291. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
  2292. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
  2293. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
  2294. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
  2295. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
  2296. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
  2297. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
  2298. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
  2299. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
  2300. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
  2301. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
  2302. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
  2303. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
  2304. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
  2305. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
  2306. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
  2307. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
  2308. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
  2309. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
  2310. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
  2311. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
  2312. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
  2313. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
  2314. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
  2315. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
  2316. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
  2317. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
  2318. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
  2319. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
  2320. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
  2321. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
  2322. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
  2323. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
  2324. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
  2325. { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
  2326. { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
  2327. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
  2328. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
  2329. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
  2330. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
  2331. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
  2332. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
  2333. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
  2334. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
  2335. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
  2336. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
  2337. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
  2338. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
  2339. { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
  2340. { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
  2341. { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
  2342. { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
  2343. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
  2344. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
  2345. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
  2346. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
  2347. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
  2348. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
  2349. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
  2350. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
  2351. { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
  2352. { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
  2353. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
  2354. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
  2355. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
  2356. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
  2357. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
  2358. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
  2359. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
  2360. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
  2361. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
  2362. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
  2363. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
  2364. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
  2365. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
  2366. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
  2367. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
  2368. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
  2369. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
  2370. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
  2371. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
  2372. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
  2373. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
  2374. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
  2375. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
  2376. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
  2377. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
  2378. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
  2379. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
  2380. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
  2381. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
  2382. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
  2383. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
  2384. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
  2385. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
  2386. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
  2387. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
  2388. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
  2389. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
  2390. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
  2391. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
  2392. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
  2393. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
  2394. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
  2395. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
  2396. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
  2397. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
  2398. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
  2399. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
  2400. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
  2401. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
  2402. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
  2403. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
  2404. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
  2405. { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
  2406. { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
  2407. { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
  2408. { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
  2409. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
  2410. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
  2411. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
  2412. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
  2413. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
  2414. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
  2415. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
  2416. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
  2417. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
  2418. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
  2419. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
  2420. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
  2421. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
  2422. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
  2423. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
  2424. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
  2425. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
  2426. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
  2427. { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
  2428. { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
  2429. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
  2430. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
  2431. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
  2432. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
  2433. { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
  2434. { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
  2435. { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
  2436. { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
  2437. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
  2438. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
  2439. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
  2440. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
  2441. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
  2442. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
  2443. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
  2444. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
  2445. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
  2446. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
  2447. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
  2448. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
  2449. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
  2450. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
  2451. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
  2452. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
  2453. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
  2454. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
  2455. { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
  2456. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
  2457. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
  2458. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
  2459. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
  2460. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
  2461. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
  2462. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
  2463. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
  2464. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
  2465. { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
  2466. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
  2467. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
  2468. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
  2469. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
  2470. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
  2471. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
  2472. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
  2473. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
  2474. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
  2475. { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
  2476. { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
  2477. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
  2478. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
  2479. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
  2480. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
  2481. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
  2482. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
  2483. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
  2484. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
  2485. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
  2486. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
  2487. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
  2488. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
  2489. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
  2490. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
  2491. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
  2492. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
  2493. { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
  2494. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
  2495. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
  2496. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
  2497. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
  2498. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
  2499. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
  2500. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
  2501. { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
  2502. { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
  2503. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
  2504. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
  2505. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
  2506. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
  2507. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
  2508. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
  2509. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
  2510. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
  2511. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
  2512. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
  2513. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
  2514. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
  2515. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
  2516. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
  2517. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
  2518. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
  2519. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
  2520. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
  2521. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
  2522. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
  2523. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
  2524. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
  2525. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
  2526. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
  2527. { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
  2528. { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
  2529. { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
  2530. { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
  2531. { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
  2532. { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
  2533. };
  2534. // Sort the tables on first execution so we can binary search them.
  2535. auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
  2536. return LHS.BuiltinID < RHS.BuiltinID;
  2537. };
  2538. static const bool SortOnce =
  2539. (llvm::sort(ValidCPU, SortCmp),
  2540. llvm::sort(ValidHVX, SortCmp), true);
  2541. (void)SortOnce;
  2542. auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
  2543. return BI.BuiltinID < BuiltinID;
  2544. };
  2545. const TargetInfo &TI = Context.getTargetInfo();
  2546. const BuiltinAndString *FC =
  2547. llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
  2548. if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
  2549. const TargetOptions &Opts = TI.getTargetOpts();
  2550. StringRef CPU = Opts.CPU;
  2551. if (!CPU.empty()) {
  2552. assert(CPU.startswith("hexagon") && "Unexpected CPU name");
  2553. CPU.consume_front("hexagon");
  2554. SmallVector<StringRef, 3> CPUs;
  2555. StringRef(FC->Str).split(CPUs, ',');
  2556. if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
  2557. return Diag(TheCall->getBeginLoc(),
  2558. diag::err_hexagon_builtin_unsupported_cpu);
  2559. }
  2560. }
  2561. const BuiltinAndString *FH =
  2562. llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
  2563. if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
  2564. if (!TI.hasFeature("hvx"))
  2565. return Diag(TheCall->getBeginLoc(),
  2566. diag::err_hexagon_builtin_requires_hvx);
  2567. SmallVector<StringRef, 3> HVXs;
  2568. StringRef(FH->Str).split(HVXs, ',');
  2569. bool IsValid = llvm::any_of(HVXs,
  2570. [&TI] (StringRef V) {
  2571. std::string F = "hvx" + V.str();
  2572. return TI.hasFeature(F);
  2573. });
  2574. if (!IsValid)
  2575. return Diag(TheCall->getBeginLoc(),
  2576. diag::err_hexagon_builtin_unsupported_hvx);
  2577. }
  2578. return false;
  2579. }
  2580. bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
  2581. struct ArgInfo {
  2582. uint8_t OpNum;
  2583. bool IsSigned;
  2584. uint8_t BitWidth;
  2585. uint8_t Align;
  2586. };
  2587. struct BuiltinInfo {
  2588. unsigned BuiltinID;
  2589. ArgInfo Infos[2];
  2590. };
  2591. static BuiltinInfo Infos[] = {
  2592. { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
  2593. { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
  2594. { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
  2595. { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
  2596. { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
  2597. { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
  2598. { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
  2599. { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
  2600. { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
  2601. { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
  2602. { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
  2603. { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
  2604. { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
  2605. { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
  2606. { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
  2607. { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
  2608. { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
  2609. { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
  2610. { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
  2611. { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
  2612. { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
  2613. { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
  2614. { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
  2615. { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
  2616. { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
  2617. { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
  2618. { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
  2619. { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
  2620. { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
  2621. { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
  2622. { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
  2623. { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
  2624. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
  2625. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
  2626. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
  2627. { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
  2628. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
  2629. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
  2630. { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
  2631. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
  2632. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
  2633. { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
  2634. { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
  2635. { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
  2636. { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
  2637. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
  2638. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
  2639. { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
  2640. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
  2641. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
  2642. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
  2643. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
  2644. { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
  2645. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
  2646. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
  2647. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
  2648. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
  2649. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
  2650. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
  2651. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
  2652. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
  2653. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
  2654. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
  2655. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
  2656. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
  2657. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
  2658. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
  2659. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
  2660. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
  2661. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
  2662. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
  2663. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
  2664. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
  2665. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
  2666. {{ 1, false, 6, 0 }} },
  2667. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
  2668. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
  2669. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
  2670. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
  2671. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
  2672. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
  2673. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
  2674. {{ 1, false, 5, 0 }} },
  2675. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
  2676. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
  2677. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
  2678. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
  2679. { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
  2680. { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
  2681. { 2, false, 5, 0 }} },
  2682. { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
  2683. { 2, false, 6, 0 }} },
  2684. { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
  2685. { 3, false, 5, 0 }} },
  2686. { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
  2687. { 3, false, 6, 0 }} },
  2688. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
  2689. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
  2690. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
  2691. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
  2692. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
  2693. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
  2694. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
  2695. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
  2696. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
  2697. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
  2698. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
  2699. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
  2700. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
  2701. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
  2702. { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
  2703. { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
  2704. {{ 2, false, 4, 0 },
  2705. { 3, false, 5, 0 }} },
  2706. { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
  2707. {{ 2, false, 4, 0 },
  2708. { 3, false, 5, 0 }} },
  2709. { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
  2710. {{ 2, false, 4, 0 },
  2711. { 3, false, 5, 0 }} },
  2712. { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
  2713. {{ 2, false, 4, 0 },
  2714. { 3, false, 5, 0 }} },
  2715. { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
  2716. { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
  2717. { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
  2718. { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
  2719. { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
  2720. { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
  2721. { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
  2722. { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
  2723. { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
  2724. { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
  2725. { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
  2726. { 2, false, 5, 0 }} },
  2727. { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
  2728. { 2, false, 6, 0 }} },
  2729. { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
  2730. { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
  2731. { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
  2732. { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
  2733. { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
  2734. { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
  2735. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
  2736. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
  2737. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
  2738. {{ 1, false, 4, 0 }} },
  2739. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
  2740. { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
  2741. {{ 1, false, 4, 0 }} },
  2742. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
  2743. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
  2744. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
  2745. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
  2746. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
  2747. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
  2748. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
  2749. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
  2750. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
  2751. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
  2752. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
  2753. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
  2754. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
  2755. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
  2756. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
  2757. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
  2758. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
  2759. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
  2760. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
  2761. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
  2762. {{ 3, false, 1, 0 }} },
  2763. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
  2764. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
  2765. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
  2766. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
  2767. {{ 3, false, 1, 0 }} },
  2768. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
  2769. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
  2770. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
  2771. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
  2772. {{ 3, false, 1, 0 }} },
  2773. };
  2774. // Use a dynamically initialized static to sort the table exactly once on
  2775. // first run.
  2776. static const bool SortOnce =
  2777. (llvm::sort(Infos,
  2778. [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
  2779. return LHS.BuiltinID < RHS.BuiltinID;
  2780. }),
  2781. true);
  2782. (void)SortOnce;
  2783. const BuiltinInfo *F = llvm::partition_point(
  2784. Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
  2785. if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
  2786. return false;
  2787. bool Error = false;
  2788. for (const ArgInfo &A : F->Infos) {
  2789. // Ignore empty ArgInfo elements.
  2790. if (A.BitWidth == 0)
  2791. continue;
  2792. int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
  2793. int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
  2794. if (!A.Align) {
  2795. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
  2796. } else {
  2797. unsigned M = 1 << A.Align;
  2798. Min *= M;
  2799. Max *= M;
  2800. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
  2801. SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
  2802. }
  2803. }
  2804. return Error;
  2805. }
  2806. bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
  2807. CallExpr *TheCall) {
  2808. return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
  2809. CheckHexagonBuiltinArgument(BuiltinID, TheCall);
  2810. }
  2811. // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
  2812. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  2813. // ordering for DSP is unspecified. MSA is ordered by the data format used
  2814. // by the underlying instruction i.e., df/m, df/n and then by size.
  2815. //
  2816. // FIXME: The size tests here should instead be tablegen'd along with the
  2817. // definitions from include/clang/Basic/BuiltinsMips.def.
  2818. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  2819. // be too.
  2820. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2821. unsigned i = 0, l = 0, u = 0, m = 0;
  2822. switch (BuiltinID) {
  2823. default: return false;
  2824. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  2825. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  2826. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  2827. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  2828. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  2829. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  2830. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  2831. // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
  2832. // df/m field.
  2833. // These intrinsics take an unsigned 3 bit immediate.
  2834. case Mips::BI__builtin_msa_bclri_b:
  2835. case Mips::BI__builtin_msa_bnegi_b:
  2836. case Mips::BI__builtin_msa_bseti_b:
  2837. case Mips::BI__builtin_msa_sat_s_b:
  2838. case Mips::BI__builtin_msa_sat_u_b:
  2839. case Mips::BI__builtin_msa_slli_b:
  2840. case Mips::BI__builtin_msa_srai_b:
  2841. case Mips::BI__builtin_msa_srari_b:
  2842. case Mips::BI__builtin_msa_srli_b:
  2843. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  2844. case Mips::BI__builtin_msa_binsli_b:
  2845. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  2846. // These intrinsics take an unsigned 4 bit immediate.
  2847. case Mips::BI__builtin_msa_bclri_h:
  2848. case Mips::BI__builtin_msa_bnegi_h:
  2849. case Mips::BI__builtin_msa_bseti_h:
  2850. case Mips::BI__builtin_msa_sat_s_h:
  2851. case Mips::BI__builtin_msa_sat_u_h:
  2852. case Mips::BI__builtin_msa_slli_h:
  2853. case Mips::BI__builtin_msa_srai_h:
  2854. case Mips::BI__builtin_msa_srari_h:
  2855. case Mips::BI__builtin_msa_srli_h:
  2856. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  2857. case Mips::BI__builtin_msa_binsli_h:
  2858. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  2859. // These intrinsics take an unsigned 5 bit immediate.
  2860. // The first block of intrinsics actually have an unsigned 5 bit field,
  2861. // not a df/n field.
  2862. case Mips::BI__builtin_msa_cfcmsa:
  2863. case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
  2864. case Mips::BI__builtin_msa_clei_u_b:
  2865. case Mips::BI__builtin_msa_clei_u_h:
  2866. case Mips::BI__builtin_msa_clei_u_w:
  2867. case Mips::BI__builtin_msa_clei_u_d:
  2868. case Mips::BI__builtin_msa_clti_u_b:
  2869. case Mips::BI__builtin_msa_clti_u_h:
  2870. case Mips::BI__builtin_msa_clti_u_w:
  2871. case Mips::BI__builtin_msa_clti_u_d:
  2872. case Mips::BI__builtin_msa_maxi_u_b:
  2873. case Mips::BI__builtin_msa_maxi_u_h:
  2874. case Mips::BI__builtin_msa_maxi_u_w:
  2875. case Mips::BI__builtin_msa_maxi_u_d:
  2876. case Mips::BI__builtin_msa_mini_u_b:
  2877. case Mips::BI__builtin_msa_mini_u_h:
  2878. case Mips::BI__builtin_msa_mini_u_w:
  2879. case Mips::BI__builtin_msa_mini_u_d:
  2880. case Mips::BI__builtin_msa_addvi_b:
  2881. case Mips::BI__builtin_msa_addvi_h:
  2882. case Mips::BI__builtin_msa_addvi_w:
  2883. case Mips::BI__builtin_msa_addvi_d:
  2884. case Mips::BI__builtin_msa_bclri_w:
  2885. case Mips::BI__builtin_msa_bnegi_w:
  2886. case Mips::BI__builtin_msa_bseti_w:
  2887. case Mips::BI__builtin_msa_sat_s_w:
  2888. case Mips::BI__builtin_msa_sat_u_w:
  2889. case Mips::BI__builtin_msa_slli_w:
  2890. case Mips::BI__builtin_msa_srai_w:
  2891. case Mips::BI__builtin_msa_srari_w:
  2892. case Mips::BI__builtin_msa_srli_w:
  2893. case Mips::BI__builtin_msa_srlri_w:
  2894. case Mips::BI__builtin_msa_subvi_b:
  2895. case Mips::BI__builtin_msa_subvi_h:
  2896. case Mips::BI__builtin_msa_subvi_w:
  2897. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  2898. case Mips::BI__builtin_msa_binsli_w:
  2899. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  2900. // These intrinsics take an unsigned 6 bit immediate.
  2901. case Mips::BI__builtin_msa_bclri_d:
  2902. case Mips::BI__builtin_msa_bnegi_d:
  2903. case Mips::BI__builtin_msa_bseti_d:
  2904. case Mips::BI__builtin_msa_sat_s_d:
  2905. case Mips::BI__builtin_msa_sat_u_d:
  2906. case Mips::BI__builtin_msa_slli_d:
  2907. case Mips::BI__builtin_msa_srai_d:
  2908. case Mips::BI__builtin_msa_srari_d:
  2909. case Mips::BI__builtin_msa_srli_d:
  2910. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  2911. case Mips::BI__builtin_msa_binsli_d:
  2912. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  2913. // These intrinsics take a signed 5 bit immediate.
  2914. case Mips::BI__builtin_msa_ceqi_b:
  2915. case Mips::BI__builtin_msa_ceqi_h:
  2916. case Mips::BI__builtin_msa_ceqi_w:
  2917. case Mips::BI__builtin_msa_ceqi_d:
  2918. case Mips::BI__builtin_msa_clti_s_b:
  2919. case Mips::BI__builtin_msa_clti_s_h:
  2920. case Mips::BI__builtin_msa_clti_s_w:
  2921. case Mips::BI__builtin_msa_clti_s_d:
  2922. case Mips::BI__builtin_msa_clei_s_b:
  2923. case Mips::BI__builtin_msa_clei_s_h:
  2924. case Mips::BI__builtin_msa_clei_s_w:
  2925. case Mips::BI__builtin_msa_clei_s_d:
  2926. case Mips::BI__builtin_msa_maxi_s_b:
  2927. case Mips::BI__builtin_msa_maxi_s_h:
  2928. case Mips::BI__builtin_msa_maxi_s_w:
  2929. case Mips::BI__builtin_msa_maxi_s_d:
  2930. case Mips::BI__builtin_msa_mini_s_b:
  2931. case Mips::BI__builtin_msa_mini_s_h:
  2932. case Mips::BI__builtin_msa_mini_s_w:
  2933. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  2934. // These intrinsics take an unsigned 8 bit immediate.
  2935. case Mips::BI__builtin_msa_andi_b:
  2936. case Mips::BI__builtin_msa_nori_b:
  2937. case Mips::BI__builtin_msa_ori_b:
  2938. case Mips::BI__builtin_msa_shf_b:
  2939. case Mips::BI__builtin_msa_shf_h:
  2940. case Mips::BI__builtin_msa_shf_w:
  2941. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  2942. case Mips::BI__builtin_msa_bseli_b:
  2943. case Mips::BI__builtin_msa_bmnzi_b:
  2944. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  2945. // df/n format
  2946. // These intrinsics take an unsigned 4 bit immediate.
  2947. case Mips::BI__builtin_msa_copy_s_b:
  2948. case Mips::BI__builtin_msa_copy_u_b:
  2949. case Mips::BI__builtin_msa_insve_b:
  2950. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  2951. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  2952. // These intrinsics take an unsigned 3 bit immediate.
  2953. case Mips::BI__builtin_msa_copy_s_h:
  2954. case Mips::BI__builtin_msa_copy_u_h:
  2955. case Mips::BI__builtin_msa_insve_h:
  2956. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  2957. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  2958. // These intrinsics take an unsigned 2 bit immediate.
  2959. case Mips::BI__builtin_msa_copy_s_w:
  2960. case Mips::BI__builtin_msa_copy_u_w:
  2961. case Mips::BI__builtin_msa_insve_w:
  2962. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  2963. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  2964. // These intrinsics take an unsigned 1 bit immediate.
  2965. case Mips::BI__builtin_msa_copy_s_d:
  2966. case Mips::BI__builtin_msa_copy_u_d:
  2967. case Mips::BI__builtin_msa_insve_d:
  2968. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  2969. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  2970. // Memory offsets and immediate loads.
  2971. // These intrinsics take a signed 10 bit immediate.
  2972. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  2973. case Mips::BI__builtin_msa_ldi_h:
  2974. case Mips::BI__builtin_msa_ldi_w:
  2975. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  2976. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
  2977. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
  2978. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
  2979. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
  2980. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
  2981. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
  2982. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
  2983. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
  2984. }
  2985. if (!m)
  2986. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2987. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  2988. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  2989. }
  2990. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2991. unsigned i = 0, l = 0, u = 0;
  2992. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  2993. BuiltinID == PPC::BI__builtin_divdeu ||
  2994. BuiltinID == PPC::BI__builtin_bpermd;
  2995. bool IsTarget64Bit = Context.getTargetInfo()
  2996. .getTypeWidth(Context
  2997. .getTargetInfo()
  2998. .getIntPtrType()) == 64;
  2999. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  3000. BuiltinID == PPC::BI__builtin_divweu ||
  3001. BuiltinID == PPC::BI__builtin_divde ||
  3002. BuiltinID == PPC::BI__builtin_divdeu;
  3003. if (Is64BitBltin && !IsTarget64Bit)
  3004. return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
  3005. << TheCall->getSourceRange();
  3006. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  3007. (BuiltinID == PPC::BI__builtin_bpermd &&
  3008. !Context.getTargetInfo().hasFeature("bpermd")))
  3009. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  3010. << TheCall->getSourceRange();
  3011. auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
  3012. if (!Context.getTargetInfo().hasFeature("vsx"))
  3013. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  3014. << TheCall->getSourceRange();
  3015. return false;
  3016. };
  3017. switch (BuiltinID) {
  3018. default: return false;
  3019. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  3020. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  3021. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  3022. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3023. case PPC::BI__builtin_tbegin:
  3024. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  3025. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  3026. case PPC::BI__builtin_tabortwc:
  3027. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  3028. case PPC::BI__builtin_tabortwci:
  3029. case PPC::BI__builtin_tabortdci:
  3030. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  3031. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  3032. case PPC::BI__builtin_vsx_xxpermdi:
  3033. case PPC::BI__builtin_vsx_xxsldwi:
  3034. return SemaBuiltinVSX(TheCall);
  3035. case PPC::BI__builtin_unpack_vector_int128:
  3036. return SemaVSXCheck(TheCall) ||
  3037. SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  3038. case PPC::BI__builtin_pack_vector_int128:
  3039. return SemaVSXCheck(TheCall);
  3040. }
  3041. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3042. }
  3043. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  3044. CallExpr *TheCall) {
  3045. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  3046. Expr *Arg = TheCall->getArg(0);
  3047. llvm::APSInt AbortCode(32);
  3048. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  3049. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  3050. return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
  3051. << Arg->getSourceRange();
  3052. }
  3053. // For intrinsics which take an immediate value as part of the instruction,
  3054. // range check them here.
  3055. unsigned i = 0, l = 0, u = 0;
  3056. switch (BuiltinID) {
  3057. default: return false;
  3058. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  3059. case SystemZ::BI__builtin_s390_verimb:
  3060. case SystemZ::BI__builtin_s390_verimh:
  3061. case SystemZ::BI__builtin_s390_verimf:
  3062. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  3063. case SystemZ::BI__builtin_s390_vfaeb:
  3064. case SystemZ::BI__builtin_s390_vfaeh:
  3065. case SystemZ::BI__builtin_s390_vfaef:
  3066. case SystemZ::BI__builtin_s390_vfaebs:
  3067. case SystemZ::BI__builtin_s390_vfaehs:
  3068. case SystemZ::BI__builtin_s390_vfaefs:
  3069. case SystemZ::BI__builtin_s390_vfaezb:
  3070. case SystemZ::BI__builtin_s390_vfaezh:
  3071. case SystemZ::BI__builtin_s390_vfaezf:
  3072. case SystemZ::BI__builtin_s390_vfaezbs:
  3073. case SystemZ::BI__builtin_s390_vfaezhs:
  3074. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  3075. case SystemZ::BI__builtin_s390_vfisb:
  3076. case SystemZ::BI__builtin_s390_vfidb:
  3077. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  3078. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3079. case SystemZ::BI__builtin_s390_vftcisb:
  3080. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  3081. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  3082. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  3083. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  3084. case SystemZ::BI__builtin_s390_vstrcb:
  3085. case SystemZ::BI__builtin_s390_vstrch:
  3086. case SystemZ::BI__builtin_s390_vstrcf:
  3087. case SystemZ::BI__builtin_s390_vstrczb:
  3088. case SystemZ::BI__builtin_s390_vstrczh:
  3089. case SystemZ::BI__builtin_s390_vstrczf:
  3090. case SystemZ::BI__builtin_s390_vstrcbs:
  3091. case SystemZ::BI__builtin_s390_vstrchs:
  3092. case SystemZ::BI__builtin_s390_vstrcfs:
  3093. case SystemZ::BI__builtin_s390_vstrczbs:
  3094. case SystemZ::BI__builtin_s390_vstrczhs:
  3095. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  3096. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  3097. case SystemZ::BI__builtin_s390_vfminsb:
  3098. case SystemZ::BI__builtin_s390_vfmaxsb:
  3099. case SystemZ::BI__builtin_s390_vfmindb:
  3100. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  3101. case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
  3102. case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
  3103. }
  3104. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3105. }
  3106. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  3107. /// This checks that the target supports __builtin_cpu_supports and
  3108. /// that the string argument is constant and valid.
  3109. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  3110. Expr *Arg = TheCall->getArg(0);
  3111. // Check if the argument is a string literal.
  3112. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3113. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3114. << Arg->getSourceRange();
  3115. // Check the contents of the string.
  3116. StringRef Feature =
  3117. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3118. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  3119. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
  3120. << Arg->getSourceRange();
  3121. return false;
  3122. }
  3123. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  3124. /// This checks that the target supports __builtin_cpu_is and
  3125. /// that the string argument is constant and valid.
  3126. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  3127. Expr *Arg = TheCall->getArg(0);
  3128. // Check if the argument is a string literal.
  3129. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3130. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3131. << Arg->getSourceRange();
  3132. // Check the contents of the string.
  3133. StringRef Feature =
  3134. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3135. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  3136. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
  3137. << Arg->getSourceRange();
  3138. return false;
  3139. }
  3140. // Check if the rounding mode is legal.
  3141. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  3142. // Indicates if this instruction has rounding control or just SAE.
  3143. bool HasRC = false;
  3144. unsigned ArgNum = 0;
  3145. switch (BuiltinID) {
  3146. default:
  3147. return false;
  3148. case X86::BI__builtin_ia32_vcvttsd2si32:
  3149. case X86::BI__builtin_ia32_vcvttsd2si64:
  3150. case X86::BI__builtin_ia32_vcvttsd2usi32:
  3151. case X86::BI__builtin_ia32_vcvttsd2usi64:
  3152. case X86::BI__builtin_ia32_vcvttss2si32:
  3153. case X86::BI__builtin_ia32_vcvttss2si64:
  3154. case X86::BI__builtin_ia32_vcvttss2usi32:
  3155. case X86::BI__builtin_ia32_vcvttss2usi64:
  3156. ArgNum = 1;
  3157. break;
  3158. case X86::BI__builtin_ia32_maxpd512:
  3159. case X86::BI__builtin_ia32_maxps512:
  3160. case X86::BI__builtin_ia32_minpd512:
  3161. case X86::BI__builtin_ia32_minps512:
  3162. ArgNum = 2;
  3163. break;
  3164. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  3165. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  3166. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  3167. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  3168. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  3169. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  3170. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  3171. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  3172. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  3173. case X86::BI__builtin_ia32_exp2pd_mask:
  3174. case X86::BI__builtin_ia32_exp2ps_mask:
  3175. case X86::BI__builtin_ia32_getexppd512_mask:
  3176. case X86::BI__builtin_ia32_getexpps512_mask:
  3177. case X86::BI__builtin_ia32_rcp28pd_mask:
  3178. case X86::BI__builtin_ia32_rcp28ps_mask:
  3179. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  3180. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  3181. case X86::BI__builtin_ia32_vcomisd:
  3182. case X86::BI__builtin_ia32_vcomiss:
  3183. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  3184. ArgNum = 3;
  3185. break;
  3186. case X86::BI__builtin_ia32_cmppd512_mask:
  3187. case X86::BI__builtin_ia32_cmpps512_mask:
  3188. case X86::BI__builtin_ia32_cmpsd_mask:
  3189. case X86::BI__builtin_ia32_cmpss_mask:
  3190. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  3191. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  3192. case X86::BI__builtin_ia32_getexpss128_round_mask:
  3193. case X86::BI__builtin_ia32_getmantpd512_mask:
  3194. case X86::BI__builtin_ia32_getmantps512_mask:
  3195. case X86::BI__builtin_ia32_maxsd_round_mask:
  3196. case X86::BI__builtin_ia32_maxss_round_mask:
  3197. case X86::BI__builtin_ia32_minsd_round_mask:
  3198. case X86::BI__builtin_ia32_minss_round_mask:
  3199. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  3200. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  3201. case X86::BI__builtin_ia32_reducepd512_mask:
  3202. case X86::BI__builtin_ia32_reduceps512_mask:
  3203. case X86::BI__builtin_ia32_rndscalepd_mask:
  3204. case X86::BI__builtin_ia32_rndscaleps_mask:
  3205. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  3206. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  3207. ArgNum = 4;
  3208. break;
  3209. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3210. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3211. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3212. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3213. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3214. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3215. case X86::BI__builtin_ia32_fixupimmss_mask:
  3216. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3217. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3218. case X86::BI__builtin_ia32_getmantss_round_mask:
  3219. case X86::BI__builtin_ia32_rangepd512_mask:
  3220. case X86::BI__builtin_ia32_rangeps512_mask:
  3221. case X86::BI__builtin_ia32_rangesd128_round_mask:
  3222. case X86::BI__builtin_ia32_rangess128_round_mask:
  3223. case X86::BI__builtin_ia32_reducesd_mask:
  3224. case X86::BI__builtin_ia32_reducess_mask:
  3225. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3226. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3227. ArgNum = 5;
  3228. break;
  3229. case X86::BI__builtin_ia32_vcvtsd2si64:
  3230. case X86::BI__builtin_ia32_vcvtsd2si32:
  3231. case X86::BI__builtin_ia32_vcvtsd2usi32:
  3232. case X86::BI__builtin_ia32_vcvtsd2usi64:
  3233. case X86::BI__builtin_ia32_vcvtss2si32:
  3234. case X86::BI__builtin_ia32_vcvtss2si64:
  3235. case X86::BI__builtin_ia32_vcvtss2usi32:
  3236. case X86::BI__builtin_ia32_vcvtss2usi64:
  3237. case X86::BI__builtin_ia32_sqrtpd512:
  3238. case X86::BI__builtin_ia32_sqrtps512:
  3239. ArgNum = 1;
  3240. HasRC = true;
  3241. break;
  3242. case X86::BI__builtin_ia32_addpd512:
  3243. case X86::BI__builtin_ia32_addps512:
  3244. case X86::BI__builtin_ia32_divpd512:
  3245. case X86::BI__builtin_ia32_divps512:
  3246. case X86::BI__builtin_ia32_mulpd512:
  3247. case X86::BI__builtin_ia32_mulps512:
  3248. case X86::BI__builtin_ia32_subpd512:
  3249. case X86::BI__builtin_ia32_subps512:
  3250. case X86::BI__builtin_ia32_cvtsi2sd64:
  3251. case X86::BI__builtin_ia32_cvtsi2ss32:
  3252. case X86::BI__builtin_ia32_cvtsi2ss64:
  3253. case X86::BI__builtin_ia32_cvtusi2sd64:
  3254. case X86::BI__builtin_ia32_cvtusi2ss32:
  3255. case X86::BI__builtin_ia32_cvtusi2ss64:
  3256. ArgNum = 2;
  3257. HasRC = true;
  3258. break;
  3259. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  3260. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  3261. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  3262. case X86::BI__builtin_ia32_cvtpd2dq512_mask:
  3263. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  3264. case X86::BI__builtin_ia32_cvtpd2udq512_mask:
  3265. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  3266. case X86::BI__builtin_ia32_cvtps2dq512_mask:
  3267. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  3268. case X86::BI__builtin_ia32_cvtps2udq512_mask:
  3269. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  3270. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  3271. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  3272. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  3273. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  3274. ArgNum = 3;
  3275. HasRC = true;
  3276. break;
  3277. case X86::BI__builtin_ia32_addss_round_mask:
  3278. case X86::BI__builtin_ia32_addsd_round_mask:
  3279. case X86::BI__builtin_ia32_divss_round_mask:
  3280. case X86::BI__builtin_ia32_divsd_round_mask:
  3281. case X86::BI__builtin_ia32_mulss_round_mask:
  3282. case X86::BI__builtin_ia32_mulsd_round_mask:
  3283. case X86::BI__builtin_ia32_subss_round_mask:
  3284. case X86::BI__builtin_ia32_subsd_round_mask:
  3285. case X86::BI__builtin_ia32_scalefpd512_mask:
  3286. case X86::BI__builtin_ia32_scalefps512_mask:
  3287. case X86::BI__builtin_ia32_scalefsd_round_mask:
  3288. case X86::BI__builtin_ia32_scalefss_round_mask:
  3289. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  3290. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  3291. case X86::BI__builtin_ia32_sqrtss_round_mask:
  3292. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  3293. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  3294. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  3295. case X86::BI__builtin_ia32_vfmaddss3_mask:
  3296. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  3297. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  3298. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  3299. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  3300. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  3301. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  3302. case X86::BI__builtin_ia32_vfmaddps512_mask:
  3303. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  3304. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  3305. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  3306. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  3307. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  3308. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  3309. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  3310. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  3311. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  3312. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  3313. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  3314. ArgNum = 4;
  3315. HasRC = true;
  3316. break;
  3317. }
  3318. llvm::APSInt Result;
  3319. // We can't check the value of a dependent argument.
  3320. Expr *Arg = TheCall->getArg(ArgNum);
  3321. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3322. return false;
  3323. // Check constant-ness first.
  3324. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3325. return true;
  3326. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  3327. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  3328. // combined with ROUND_NO_EXC.
  3329. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  3330. Result == 8/*ROUND_NO_EXC*/ ||
  3331. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  3332. return false;
  3333. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
  3334. << Arg->getSourceRange();
  3335. }
  3336. // Check if the gather/scatter scale is legal.
  3337. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  3338. CallExpr *TheCall) {
  3339. unsigned ArgNum = 0;
  3340. switch (BuiltinID) {
  3341. default:
  3342. return false;
  3343. case X86::BI__builtin_ia32_gatherpfdpd:
  3344. case X86::BI__builtin_ia32_gatherpfdps:
  3345. case X86::BI__builtin_ia32_gatherpfqpd:
  3346. case X86::BI__builtin_ia32_gatherpfqps:
  3347. case X86::BI__builtin_ia32_scatterpfdpd:
  3348. case X86::BI__builtin_ia32_scatterpfdps:
  3349. case X86::BI__builtin_ia32_scatterpfqpd:
  3350. case X86::BI__builtin_ia32_scatterpfqps:
  3351. ArgNum = 3;
  3352. break;
  3353. case X86::BI__builtin_ia32_gatherd_pd:
  3354. case X86::BI__builtin_ia32_gatherd_pd256:
  3355. case X86::BI__builtin_ia32_gatherq_pd:
  3356. case X86::BI__builtin_ia32_gatherq_pd256:
  3357. case X86::BI__builtin_ia32_gatherd_ps:
  3358. case X86::BI__builtin_ia32_gatherd_ps256:
  3359. case X86::BI__builtin_ia32_gatherq_ps:
  3360. case X86::BI__builtin_ia32_gatherq_ps256:
  3361. case X86::BI__builtin_ia32_gatherd_q:
  3362. case X86::BI__builtin_ia32_gatherd_q256:
  3363. case X86::BI__builtin_ia32_gatherq_q:
  3364. case X86::BI__builtin_ia32_gatherq_q256:
  3365. case X86::BI__builtin_ia32_gatherd_d:
  3366. case X86::BI__builtin_ia32_gatherd_d256:
  3367. case X86::BI__builtin_ia32_gatherq_d:
  3368. case X86::BI__builtin_ia32_gatherq_d256:
  3369. case X86::BI__builtin_ia32_gather3div2df:
  3370. case X86::BI__builtin_ia32_gather3div2di:
  3371. case X86::BI__builtin_ia32_gather3div4df:
  3372. case X86::BI__builtin_ia32_gather3div4di:
  3373. case X86::BI__builtin_ia32_gather3div4sf:
  3374. case X86::BI__builtin_ia32_gather3div4si:
  3375. case X86::BI__builtin_ia32_gather3div8sf:
  3376. case X86::BI__builtin_ia32_gather3div8si:
  3377. case X86::BI__builtin_ia32_gather3siv2df:
  3378. case X86::BI__builtin_ia32_gather3siv2di:
  3379. case X86::BI__builtin_ia32_gather3siv4df:
  3380. case X86::BI__builtin_ia32_gather3siv4di:
  3381. case X86::BI__builtin_ia32_gather3siv4sf:
  3382. case X86::BI__builtin_ia32_gather3siv4si:
  3383. case X86::BI__builtin_ia32_gather3siv8sf:
  3384. case X86::BI__builtin_ia32_gather3siv8si:
  3385. case X86::BI__builtin_ia32_gathersiv8df:
  3386. case X86::BI__builtin_ia32_gathersiv16sf:
  3387. case X86::BI__builtin_ia32_gatherdiv8df:
  3388. case X86::BI__builtin_ia32_gatherdiv16sf:
  3389. case X86::BI__builtin_ia32_gathersiv8di:
  3390. case X86::BI__builtin_ia32_gathersiv16si:
  3391. case X86::BI__builtin_ia32_gatherdiv8di:
  3392. case X86::BI__builtin_ia32_gatherdiv16si:
  3393. case X86::BI__builtin_ia32_scatterdiv2df:
  3394. case X86::BI__builtin_ia32_scatterdiv2di:
  3395. case X86::BI__builtin_ia32_scatterdiv4df:
  3396. case X86::BI__builtin_ia32_scatterdiv4di:
  3397. case X86::BI__builtin_ia32_scatterdiv4sf:
  3398. case X86::BI__builtin_ia32_scatterdiv4si:
  3399. case X86::BI__builtin_ia32_scatterdiv8sf:
  3400. case X86::BI__builtin_ia32_scatterdiv8si:
  3401. case X86::BI__builtin_ia32_scattersiv2df:
  3402. case X86::BI__builtin_ia32_scattersiv2di:
  3403. case X86::BI__builtin_ia32_scattersiv4df:
  3404. case X86::BI__builtin_ia32_scattersiv4di:
  3405. case X86::BI__builtin_ia32_scattersiv4sf:
  3406. case X86::BI__builtin_ia32_scattersiv4si:
  3407. case X86::BI__builtin_ia32_scattersiv8sf:
  3408. case X86::BI__builtin_ia32_scattersiv8si:
  3409. case X86::BI__builtin_ia32_scattersiv8df:
  3410. case X86::BI__builtin_ia32_scattersiv16sf:
  3411. case X86::BI__builtin_ia32_scatterdiv8df:
  3412. case X86::BI__builtin_ia32_scatterdiv16sf:
  3413. case X86::BI__builtin_ia32_scattersiv8di:
  3414. case X86::BI__builtin_ia32_scattersiv16si:
  3415. case X86::BI__builtin_ia32_scatterdiv8di:
  3416. case X86::BI__builtin_ia32_scatterdiv16si:
  3417. ArgNum = 4;
  3418. break;
  3419. }
  3420. llvm::APSInt Result;
  3421. // We can't check the value of a dependent argument.
  3422. Expr *Arg = TheCall->getArg(ArgNum);
  3423. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3424. return false;
  3425. // Check constant-ness first.
  3426. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3427. return true;
  3428. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  3429. return false;
  3430. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
  3431. << Arg->getSourceRange();
  3432. }
  3433. static bool isX86_32Builtin(unsigned BuiltinID) {
  3434. // These builtins only work on x86-32 targets.
  3435. switch (BuiltinID) {
  3436. case X86::BI__builtin_ia32_readeflags_u32:
  3437. case X86::BI__builtin_ia32_writeeflags_u32:
  3438. return true;
  3439. }
  3440. return false;
  3441. }
  3442. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  3443. if (BuiltinID == X86::BI__builtin_cpu_supports)
  3444. return SemaBuiltinCpuSupports(*this, TheCall);
  3445. if (BuiltinID == X86::BI__builtin_cpu_is)
  3446. return SemaBuiltinCpuIs(*this, TheCall);
  3447. // Check for 32-bit only builtins on a 64-bit target.
  3448. const llvm::Triple &TT = Context.getTargetInfo().getTriple();
  3449. if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
  3450. return Diag(TheCall->getCallee()->getBeginLoc(),
  3451. diag::err_32_bit_builtin_64_bit_tgt);
  3452. // If the intrinsic has rounding or SAE make sure its valid.
  3453. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  3454. return true;
  3455. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  3456. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  3457. return true;
  3458. // For intrinsics which take an immediate value as part of the instruction,
  3459. // range check them here.
  3460. int i = 0, l = 0, u = 0;
  3461. switch (BuiltinID) {
  3462. default:
  3463. return false;
  3464. case X86::BI__builtin_ia32_vec_ext_v2si:
  3465. case X86::BI__builtin_ia32_vec_ext_v2di:
  3466. case X86::BI__builtin_ia32_vextractf128_pd256:
  3467. case X86::BI__builtin_ia32_vextractf128_ps256:
  3468. case X86::BI__builtin_ia32_vextractf128_si256:
  3469. case X86::BI__builtin_ia32_extract128i256:
  3470. case X86::BI__builtin_ia32_extractf64x4_mask:
  3471. case X86::BI__builtin_ia32_extracti64x4_mask:
  3472. case X86::BI__builtin_ia32_extractf32x8_mask:
  3473. case X86::BI__builtin_ia32_extracti32x8_mask:
  3474. case X86::BI__builtin_ia32_extractf64x2_256_mask:
  3475. case X86::BI__builtin_ia32_extracti64x2_256_mask:
  3476. case X86::BI__builtin_ia32_extractf32x4_256_mask:
  3477. case X86::BI__builtin_ia32_extracti32x4_256_mask:
  3478. i = 1; l = 0; u = 1;
  3479. break;
  3480. case X86::BI__builtin_ia32_vec_set_v2di:
  3481. case X86::BI__builtin_ia32_vinsertf128_pd256:
  3482. case X86::BI__builtin_ia32_vinsertf128_ps256:
  3483. case X86::BI__builtin_ia32_vinsertf128_si256:
  3484. case X86::BI__builtin_ia32_insert128i256:
  3485. case X86::BI__builtin_ia32_insertf32x8:
  3486. case X86::BI__builtin_ia32_inserti32x8:
  3487. case X86::BI__builtin_ia32_insertf64x4:
  3488. case X86::BI__builtin_ia32_inserti64x4:
  3489. case X86::BI__builtin_ia32_insertf64x2_256:
  3490. case X86::BI__builtin_ia32_inserti64x2_256:
  3491. case X86::BI__builtin_ia32_insertf32x4_256:
  3492. case X86::BI__builtin_ia32_inserti32x4_256:
  3493. i = 2; l = 0; u = 1;
  3494. break;
  3495. case X86::BI__builtin_ia32_vpermilpd:
  3496. case X86::BI__builtin_ia32_vec_ext_v4hi:
  3497. case X86::BI__builtin_ia32_vec_ext_v4si:
  3498. case X86::BI__builtin_ia32_vec_ext_v4sf:
  3499. case X86::BI__builtin_ia32_vec_ext_v4di:
  3500. case X86::BI__builtin_ia32_extractf32x4_mask:
  3501. case X86::BI__builtin_ia32_extracti32x4_mask:
  3502. case X86::BI__builtin_ia32_extractf64x2_512_mask:
  3503. case X86::BI__builtin_ia32_extracti64x2_512_mask:
  3504. i = 1; l = 0; u = 3;
  3505. break;
  3506. case X86::BI_mm_prefetch:
  3507. case X86::BI__builtin_ia32_vec_ext_v8hi:
  3508. case X86::BI__builtin_ia32_vec_ext_v8si:
  3509. i = 1; l = 0; u = 7;
  3510. break;
  3511. case X86::BI__builtin_ia32_sha1rnds4:
  3512. case X86::BI__builtin_ia32_blendpd:
  3513. case X86::BI__builtin_ia32_shufpd:
  3514. case X86::BI__builtin_ia32_vec_set_v4hi:
  3515. case X86::BI__builtin_ia32_vec_set_v4si:
  3516. case X86::BI__builtin_ia32_vec_set_v4di:
  3517. case X86::BI__builtin_ia32_shuf_f32x4_256:
  3518. case X86::BI__builtin_ia32_shuf_f64x2_256:
  3519. case X86::BI__builtin_ia32_shuf_i32x4_256:
  3520. case X86::BI__builtin_ia32_shuf_i64x2_256:
  3521. case X86::BI__builtin_ia32_insertf64x2_512:
  3522. case X86::BI__builtin_ia32_inserti64x2_512:
  3523. case X86::BI__builtin_ia32_insertf32x4:
  3524. case X86::BI__builtin_ia32_inserti32x4:
  3525. i = 2; l = 0; u = 3;
  3526. break;
  3527. case X86::BI__builtin_ia32_vpermil2pd:
  3528. case X86::BI__builtin_ia32_vpermil2pd256:
  3529. case X86::BI__builtin_ia32_vpermil2ps:
  3530. case X86::BI__builtin_ia32_vpermil2ps256:
  3531. i = 3; l = 0; u = 3;
  3532. break;
  3533. case X86::BI__builtin_ia32_cmpb128_mask:
  3534. case X86::BI__builtin_ia32_cmpw128_mask:
  3535. case X86::BI__builtin_ia32_cmpd128_mask:
  3536. case X86::BI__builtin_ia32_cmpq128_mask:
  3537. case X86::BI__builtin_ia32_cmpb256_mask:
  3538. case X86::BI__builtin_ia32_cmpw256_mask:
  3539. case X86::BI__builtin_ia32_cmpd256_mask:
  3540. case X86::BI__builtin_ia32_cmpq256_mask:
  3541. case X86::BI__builtin_ia32_cmpb512_mask:
  3542. case X86::BI__builtin_ia32_cmpw512_mask:
  3543. case X86::BI__builtin_ia32_cmpd512_mask:
  3544. case X86::BI__builtin_ia32_cmpq512_mask:
  3545. case X86::BI__builtin_ia32_ucmpb128_mask:
  3546. case X86::BI__builtin_ia32_ucmpw128_mask:
  3547. case X86::BI__builtin_ia32_ucmpd128_mask:
  3548. case X86::BI__builtin_ia32_ucmpq128_mask:
  3549. case X86::BI__builtin_ia32_ucmpb256_mask:
  3550. case X86::BI__builtin_ia32_ucmpw256_mask:
  3551. case X86::BI__builtin_ia32_ucmpd256_mask:
  3552. case X86::BI__builtin_ia32_ucmpq256_mask:
  3553. case X86::BI__builtin_ia32_ucmpb512_mask:
  3554. case X86::BI__builtin_ia32_ucmpw512_mask:
  3555. case X86::BI__builtin_ia32_ucmpd512_mask:
  3556. case X86::BI__builtin_ia32_ucmpq512_mask:
  3557. case X86::BI__builtin_ia32_vpcomub:
  3558. case X86::BI__builtin_ia32_vpcomuw:
  3559. case X86::BI__builtin_ia32_vpcomud:
  3560. case X86::BI__builtin_ia32_vpcomuq:
  3561. case X86::BI__builtin_ia32_vpcomb:
  3562. case X86::BI__builtin_ia32_vpcomw:
  3563. case X86::BI__builtin_ia32_vpcomd:
  3564. case X86::BI__builtin_ia32_vpcomq:
  3565. case X86::BI__builtin_ia32_vec_set_v8hi:
  3566. case X86::BI__builtin_ia32_vec_set_v8si:
  3567. i = 2; l = 0; u = 7;
  3568. break;
  3569. case X86::BI__builtin_ia32_vpermilpd256:
  3570. case X86::BI__builtin_ia32_roundps:
  3571. case X86::BI__builtin_ia32_roundpd:
  3572. case X86::BI__builtin_ia32_roundps256:
  3573. case X86::BI__builtin_ia32_roundpd256:
  3574. case X86::BI__builtin_ia32_getmantpd128_mask:
  3575. case X86::BI__builtin_ia32_getmantpd256_mask:
  3576. case X86::BI__builtin_ia32_getmantps128_mask:
  3577. case X86::BI__builtin_ia32_getmantps256_mask:
  3578. case X86::BI__builtin_ia32_getmantpd512_mask:
  3579. case X86::BI__builtin_ia32_getmantps512_mask:
  3580. case X86::BI__builtin_ia32_vec_ext_v16qi:
  3581. case X86::BI__builtin_ia32_vec_ext_v16hi:
  3582. i = 1; l = 0; u = 15;
  3583. break;
  3584. case X86::BI__builtin_ia32_pblendd128:
  3585. case X86::BI__builtin_ia32_blendps:
  3586. case X86::BI__builtin_ia32_blendpd256:
  3587. case X86::BI__builtin_ia32_shufpd256:
  3588. case X86::BI__builtin_ia32_roundss:
  3589. case X86::BI__builtin_ia32_roundsd:
  3590. case X86::BI__builtin_ia32_rangepd128_mask:
  3591. case X86::BI__builtin_ia32_rangepd256_mask:
  3592. case X86::BI__builtin_ia32_rangepd512_mask:
  3593. case X86::BI__builtin_ia32_rangeps128_mask:
  3594. case X86::BI__builtin_ia32_rangeps256_mask:
  3595. case X86::BI__builtin_ia32_rangeps512_mask:
  3596. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3597. case X86::BI__builtin_ia32_getmantss_round_mask:
  3598. case X86::BI__builtin_ia32_vec_set_v16qi:
  3599. case X86::BI__builtin_ia32_vec_set_v16hi:
  3600. i = 2; l = 0; u = 15;
  3601. break;
  3602. case X86::BI__builtin_ia32_vec_ext_v32qi:
  3603. i = 1; l = 0; u = 31;
  3604. break;
  3605. case X86::BI__builtin_ia32_cmpps:
  3606. case X86::BI__builtin_ia32_cmpss:
  3607. case X86::BI__builtin_ia32_cmppd:
  3608. case X86::BI__builtin_ia32_cmpsd:
  3609. case X86::BI__builtin_ia32_cmpps256:
  3610. case X86::BI__builtin_ia32_cmppd256:
  3611. case X86::BI__builtin_ia32_cmpps128_mask:
  3612. case X86::BI__builtin_ia32_cmppd128_mask:
  3613. case X86::BI__builtin_ia32_cmpps256_mask:
  3614. case X86::BI__builtin_ia32_cmppd256_mask:
  3615. case X86::BI__builtin_ia32_cmpps512_mask:
  3616. case X86::BI__builtin_ia32_cmppd512_mask:
  3617. case X86::BI__builtin_ia32_cmpsd_mask:
  3618. case X86::BI__builtin_ia32_cmpss_mask:
  3619. case X86::BI__builtin_ia32_vec_set_v32qi:
  3620. i = 2; l = 0; u = 31;
  3621. break;
  3622. case X86::BI__builtin_ia32_permdf256:
  3623. case X86::BI__builtin_ia32_permdi256:
  3624. case X86::BI__builtin_ia32_permdf512:
  3625. case X86::BI__builtin_ia32_permdi512:
  3626. case X86::BI__builtin_ia32_vpermilps:
  3627. case X86::BI__builtin_ia32_vpermilps256:
  3628. case X86::BI__builtin_ia32_vpermilpd512:
  3629. case X86::BI__builtin_ia32_vpermilps512:
  3630. case X86::BI__builtin_ia32_pshufd:
  3631. case X86::BI__builtin_ia32_pshufd256:
  3632. case X86::BI__builtin_ia32_pshufd512:
  3633. case X86::BI__builtin_ia32_pshufhw:
  3634. case X86::BI__builtin_ia32_pshufhw256:
  3635. case X86::BI__builtin_ia32_pshufhw512:
  3636. case X86::BI__builtin_ia32_pshuflw:
  3637. case X86::BI__builtin_ia32_pshuflw256:
  3638. case X86::BI__builtin_ia32_pshuflw512:
  3639. case X86::BI__builtin_ia32_vcvtps2ph:
  3640. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  3641. case X86::BI__builtin_ia32_vcvtps2ph256:
  3642. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  3643. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  3644. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  3645. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  3646. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  3647. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  3648. case X86::BI__builtin_ia32_rndscaleps_mask:
  3649. case X86::BI__builtin_ia32_rndscalepd_mask:
  3650. case X86::BI__builtin_ia32_reducepd128_mask:
  3651. case X86::BI__builtin_ia32_reducepd256_mask:
  3652. case X86::BI__builtin_ia32_reducepd512_mask:
  3653. case X86::BI__builtin_ia32_reduceps128_mask:
  3654. case X86::BI__builtin_ia32_reduceps256_mask:
  3655. case X86::BI__builtin_ia32_reduceps512_mask:
  3656. case X86::BI__builtin_ia32_prold512:
  3657. case X86::BI__builtin_ia32_prolq512:
  3658. case X86::BI__builtin_ia32_prold128:
  3659. case X86::BI__builtin_ia32_prold256:
  3660. case X86::BI__builtin_ia32_prolq128:
  3661. case X86::BI__builtin_ia32_prolq256:
  3662. case X86::BI__builtin_ia32_prord512:
  3663. case X86::BI__builtin_ia32_prorq512:
  3664. case X86::BI__builtin_ia32_prord128:
  3665. case X86::BI__builtin_ia32_prord256:
  3666. case X86::BI__builtin_ia32_prorq128:
  3667. case X86::BI__builtin_ia32_prorq256:
  3668. case X86::BI__builtin_ia32_fpclasspd128_mask:
  3669. case X86::BI__builtin_ia32_fpclasspd256_mask:
  3670. case X86::BI__builtin_ia32_fpclassps128_mask:
  3671. case X86::BI__builtin_ia32_fpclassps256_mask:
  3672. case X86::BI__builtin_ia32_fpclassps512_mask:
  3673. case X86::BI__builtin_ia32_fpclasspd512_mask:
  3674. case X86::BI__builtin_ia32_fpclasssd_mask:
  3675. case X86::BI__builtin_ia32_fpclassss_mask:
  3676. case X86::BI__builtin_ia32_pslldqi128_byteshift:
  3677. case X86::BI__builtin_ia32_pslldqi256_byteshift:
  3678. case X86::BI__builtin_ia32_pslldqi512_byteshift:
  3679. case X86::BI__builtin_ia32_psrldqi128_byteshift:
  3680. case X86::BI__builtin_ia32_psrldqi256_byteshift:
  3681. case X86::BI__builtin_ia32_psrldqi512_byteshift:
  3682. case X86::BI__builtin_ia32_kshiftliqi:
  3683. case X86::BI__builtin_ia32_kshiftlihi:
  3684. case X86::BI__builtin_ia32_kshiftlisi:
  3685. case X86::BI__builtin_ia32_kshiftlidi:
  3686. case X86::BI__builtin_ia32_kshiftriqi:
  3687. case X86::BI__builtin_ia32_kshiftrihi:
  3688. case X86::BI__builtin_ia32_kshiftrisi:
  3689. case X86::BI__builtin_ia32_kshiftridi:
  3690. i = 1; l = 0; u = 255;
  3691. break;
  3692. case X86::BI__builtin_ia32_vperm2f128_pd256:
  3693. case X86::BI__builtin_ia32_vperm2f128_ps256:
  3694. case X86::BI__builtin_ia32_vperm2f128_si256:
  3695. case X86::BI__builtin_ia32_permti256:
  3696. case X86::BI__builtin_ia32_pblendw128:
  3697. case X86::BI__builtin_ia32_pblendw256:
  3698. case X86::BI__builtin_ia32_blendps256:
  3699. case X86::BI__builtin_ia32_pblendd256:
  3700. case X86::BI__builtin_ia32_palignr128:
  3701. case X86::BI__builtin_ia32_palignr256:
  3702. case X86::BI__builtin_ia32_palignr512:
  3703. case X86::BI__builtin_ia32_alignq512:
  3704. case X86::BI__builtin_ia32_alignd512:
  3705. case X86::BI__builtin_ia32_alignd128:
  3706. case X86::BI__builtin_ia32_alignd256:
  3707. case X86::BI__builtin_ia32_alignq128:
  3708. case X86::BI__builtin_ia32_alignq256:
  3709. case X86::BI__builtin_ia32_vcomisd:
  3710. case X86::BI__builtin_ia32_vcomiss:
  3711. case X86::BI__builtin_ia32_shuf_f32x4:
  3712. case X86::BI__builtin_ia32_shuf_f64x2:
  3713. case X86::BI__builtin_ia32_shuf_i32x4:
  3714. case X86::BI__builtin_ia32_shuf_i64x2:
  3715. case X86::BI__builtin_ia32_shufpd512:
  3716. case X86::BI__builtin_ia32_shufps:
  3717. case X86::BI__builtin_ia32_shufps256:
  3718. case X86::BI__builtin_ia32_shufps512:
  3719. case X86::BI__builtin_ia32_dbpsadbw128:
  3720. case X86::BI__builtin_ia32_dbpsadbw256:
  3721. case X86::BI__builtin_ia32_dbpsadbw512:
  3722. case X86::BI__builtin_ia32_vpshldd128:
  3723. case X86::BI__builtin_ia32_vpshldd256:
  3724. case X86::BI__builtin_ia32_vpshldd512:
  3725. case X86::BI__builtin_ia32_vpshldq128:
  3726. case X86::BI__builtin_ia32_vpshldq256:
  3727. case X86::BI__builtin_ia32_vpshldq512:
  3728. case X86::BI__builtin_ia32_vpshldw128:
  3729. case X86::BI__builtin_ia32_vpshldw256:
  3730. case X86::BI__builtin_ia32_vpshldw512:
  3731. case X86::BI__builtin_ia32_vpshrdd128:
  3732. case X86::BI__builtin_ia32_vpshrdd256:
  3733. case X86::BI__builtin_ia32_vpshrdd512:
  3734. case X86::BI__builtin_ia32_vpshrdq128:
  3735. case X86::BI__builtin_ia32_vpshrdq256:
  3736. case X86::BI__builtin_ia32_vpshrdq512:
  3737. case X86::BI__builtin_ia32_vpshrdw128:
  3738. case X86::BI__builtin_ia32_vpshrdw256:
  3739. case X86::BI__builtin_ia32_vpshrdw512:
  3740. i = 2; l = 0; u = 255;
  3741. break;
  3742. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3743. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3744. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3745. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3746. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3747. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3748. case X86::BI__builtin_ia32_fixupimmss_mask:
  3749. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3750. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  3751. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  3752. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  3753. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  3754. case X86::BI__builtin_ia32_fixupimmps128_mask:
  3755. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  3756. case X86::BI__builtin_ia32_fixupimmps256_mask:
  3757. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  3758. case X86::BI__builtin_ia32_pternlogd512_mask:
  3759. case X86::BI__builtin_ia32_pternlogd512_maskz:
  3760. case X86::BI__builtin_ia32_pternlogq512_mask:
  3761. case X86::BI__builtin_ia32_pternlogq512_maskz:
  3762. case X86::BI__builtin_ia32_pternlogd128_mask:
  3763. case X86::BI__builtin_ia32_pternlogd128_maskz:
  3764. case X86::BI__builtin_ia32_pternlogd256_mask:
  3765. case X86::BI__builtin_ia32_pternlogd256_maskz:
  3766. case X86::BI__builtin_ia32_pternlogq128_mask:
  3767. case X86::BI__builtin_ia32_pternlogq128_maskz:
  3768. case X86::BI__builtin_ia32_pternlogq256_mask:
  3769. case X86::BI__builtin_ia32_pternlogq256_maskz:
  3770. i = 3; l = 0; u = 255;
  3771. break;
  3772. case X86::BI__builtin_ia32_gatherpfdpd:
  3773. case X86::BI__builtin_ia32_gatherpfdps:
  3774. case X86::BI__builtin_ia32_gatherpfqpd:
  3775. case X86::BI__builtin_ia32_gatherpfqps:
  3776. case X86::BI__builtin_ia32_scatterpfdpd:
  3777. case X86::BI__builtin_ia32_scatterpfdps:
  3778. case X86::BI__builtin_ia32_scatterpfqpd:
  3779. case X86::BI__builtin_ia32_scatterpfqps:
  3780. i = 4; l = 2; u = 3;
  3781. break;
  3782. case X86::BI__builtin_ia32_reducesd_mask:
  3783. case X86::BI__builtin_ia32_reducess_mask:
  3784. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3785. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3786. i = 4; l = 0; u = 255;
  3787. break;
  3788. }
  3789. // Note that we don't force a hard error on the range check here, allowing
  3790. // template-generated or macro-generated dead code to potentially have out-of-
  3791. // range values. These need to code generate, but don't need to necessarily
  3792. // make any sense. We use a warning that defaults to an error.
  3793. return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
  3794. }
  3795. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  3796. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  3797. /// Returns true when the format fits the function and the FormatStringInfo has
  3798. /// been populated.
  3799. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  3800. FormatStringInfo *FSI) {
  3801. FSI->HasVAListArg = Format->getFirstArg() == 0;
  3802. FSI->FormatIdx = Format->getFormatIdx() - 1;
  3803. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  3804. // The way the format attribute works in GCC, the implicit this argument
  3805. // of member functions is counted. However, it doesn't appear in our own
  3806. // lists, so decrement format_idx in that case.
  3807. if (IsCXXMember) {
  3808. if(FSI->FormatIdx == 0)
  3809. return false;
  3810. --FSI->FormatIdx;
  3811. if (FSI->FirstDataArg != 0)
  3812. --FSI->FirstDataArg;
  3813. }
  3814. return true;
  3815. }
  3816. /// Checks if a the given expression evaluates to null.
  3817. ///
  3818. /// Returns true if the value evaluates to null.
  3819. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  3820. // If the expression has non-null type, it doesn't evaluate to null.
  3821. if (auto nullability
  3822. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  3823. if (*nullability == NullabilityKind::NonNull)
  3824. return false;
  3825. }
  3826. // As a special case, transparent unions initialized with zero are
  3827. // considered null for the purposes of the nonnull attribute.
  3828. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  3829. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  3830. if (const CompoundLiteralExpr *CLE =
  3831. dyn_cast<CompoundLiteralExpr>(Expr))
  3832. if (const InitListExpr *ILE =
  3833. dyn_cast<InitListExpr>(CLE->getInitializer()))
  3834. Expr = ILE->getInit(0);
  3835. }
  3836. bool Result;
  3837. return (!Expr->isValueDependent() &&
  3838. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  3839. !Result);
  3840. }
  3841. static void CheckNonNullArgument(Sema &S,
  3842. const Expr *ArgExpr,
  3843. SourceLocation CallSiteLoc) {
  3844. if (CheckNonNullExpr(S, ArgExpr))
  3845. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  3846. S.PDiag(diag::warn_null_arg)
  3847. << ArgExpr->getSourceRange());
  3848. }
  3849. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  3850. FormatStringInfo FSI;
  3851. if ((GetFormatStringType(Format) == FST_NSString) &&
  3852. getFormatStringInfo(Format, false, &FSI)) {
  3853. Idx = FSI.FormatIdx;
  3854. return true;
  3855. }
  3856. return false;
  3857. }
  3858. /// Diagnose use of %s directive in an NSString which is being passed
  3859. /// as formatting string to formatting method.
  3860. static void
  3861. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  3862. const NamedDecl *FDecl,
  3863. Expr **Args,
  3864. unsigned NumArgs) {
  3865. unsigned Idx = 0;
  3866. bool Format = false;
  3867. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  3868. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  3869. Idx = 2;
  3870. Format = true;
  3871. }
  3872. else
  3873. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3874. if (S.GetFormatNSStringIdx(I, Idx)) {
  3875. Format = true;
  3876. break;
  3877. }
  3878. }
  3879. if (!Format || NumArgs <= Idx)
  3880. return;
  3881. const Expr *FormatExpr = Args[Idx];
  3882. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  3883. FormatExpr = CSCE->getSubExpr();
  3884. const StringLiteral *FormatString;
  3885. if (const ObjCStringLiteral *OSL =
  3886. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  3887. FormatString = OSL->getString();
  3888. else
  3889. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  3890. if (!FormatString)
  3891. return;
  3892. if (S.FormatStringHasSArg(FormatString)) {
  3893. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  3894. << "%s" << 1 << 1;
  3895. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  3896. << FDecl->getDeclName();
  3897. }
  3898. }
  3899. /// Determine whether the given type has a non-null nullability annotation.
  3900. static bool isNonNullType(ASTContext &ctx, QualType type) {
  3901. if (auto nullability = type->getNullability(ctx))
  3902. return *nullability == NullabilityKind::NonNull;
  3903. return false;
  3904. }
  3905. static void CheckNonNullArguments(Sema &S,
  3906. const NamedDecl *FDecl,
  3907. const FunctionProtoType *Proto,
  3908. ArrayRef<const Expr *> Args,
  3909. SourceLocation CallSiteLoc) {
  3910. assert((FDecl || Proto) && "Need a function declaration or prototype");
  3911. // Already checked by by constant evaluator.
  3912. if (S.isConstantEvaluated())
  3913. return;
  3914. // Check the attributes attached to the method/function itself.
  3915. llvm::SmallBitVector NonNullArgs;
  3916. if (FDecl) {
  3917. // Handle the nonnull attribute on the function/method declaration itself.
  3918. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  3919. if (!NonNull->args_size()) {
  3920. // Easy case: all pointer arguments are nonnull.
  3921. for (const auto *Arg : Args)
  3922. if (S.isValidPointerAttrType(Arg->getType()))
  3923. CheckNonNullArgument(S, Arg, CallSiteLoc);
  3924. return;
  3925. }
  3926. for (const ParamIdx &Idx : NonNull->args()) {
  3927. unsigned IdxAST = Idx.getASTIndex();
  3928. if (IdxAST >= Args.size())
  3929. continue;
  3930. if (NonNullArgs.empty())
  3931. NonNullArgs.resize(Args.size());
  3932. NonNullArgs.set(IdxAST);
  3933. }
  3934. }
  3935. }
  3936. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  3937. // Handle the nonnull attribute on the parameters of the
  3938. // function/method.
  3939. ArrayRef<ParmVarDecl*> parms;
  3940. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  3941. parms = FD->parameters();
  3942. else
  3943. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  3944. unsigned ParamIndex = 0;
  3945. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  3946. I != E; ++I, ++ParamIndex) {
  3947. const ParmVarDecl *PVD = *I;
  3948. if (PVD->hasAttr<NonNullAttr>() ||
  3949. isNonNullType(S.Context, PVD->getType())) {
  3950. if (NonNullArgs.empty())
  3951. NonNullArgs.resize(Args.size());
  3952. NonNullArgs.set(ParamIndex);
  3953. }
  3954. }
  3955. } else {
  3956. // If we have a non-function, non-method declaration but no
  3957. // function prototype, try to dig out the function prototype.
  3958. if (!Proto) {
  3959. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  3960. QualType type = VD->getType().getNonReferenceType();
  3961. if (auto pointerType = type->getAs<PointerType>())
  3962. type = pointerType->getPointeeType();
  3963. else if (auto blockType = type->getAs<BlockPointerType>())
  3964. type = blockType->getPointeeType();
  3965. // FIXME: data member pointers?
  3966. // Dig out the function prototype, if there is one.
  3967. Proto = type->getAs<FunctionProtoType>();
  3968. }
  3969. }
  3970. // Fill in non-null argument information from the nullability
  3971. // information on the parameter types (if we have them).
  3972. if (Proto) {
  3973. unsigned Index = 0;
  3974. for (auto paramType : Proto->getParamTypes()) {
  3975. if (isNonNullType(S.Context, paramType)) {
  3976. if (NonNullArgs.empty())
  3977. NonNullArgs.resize(Args.size());
  3978. NonNullArgs.set(Index);
  3979. }
  3980. ++Index;
  3981. }
  3982. }
  3983. }
  3984. // Check for non-null arguments.
  3985. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  3986. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  3987. if (NonNullArgs[ArgIndex])
  3988. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  3989. }
  3990. }
  3991. /// Handles the checks for format strings, non-POD arguments to vararg
  3992. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  3993. /// attributes.
  3994. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  3995. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  3996. bool IsMemberFunction, SourceLocation Loc,
  3997. SourceRange Range, VariadicCallType CallType) {
  3998. // FIXME: We should check as much as we can in the template definition.
  3999. if (CurContext->isDependentContext())
  4000. return;
  4001. // Printf and scanf checking.
  4002. llvm::SmallBitVector CheckedVarArgs;
  4003. if (FDecl) {
  4004. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  4005. // Only create vector if there are format attributes.
  4006. CheckedVarArgs.resize(Args.size());
  4007. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  4008. CheckedVarArgs);
  4009. }
  4010. }
  4011. // Refuse POD arguments that weren't caught by the format string
  4012. // checks above.
  4013. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  4014. if (CallType != VariadicDoesNotApply &&
  4015. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  4016. unsigned NumParams = Proto ? Proto->getNumParams()
  4017. : FDecl && isa<FunctionDecl>(FDecl)
  4018. ? cast<FunctionDecl>(FDecl)->getNumParams()
  4019. : FDecl && isa<ObjCMethodDecl>(FDecl)
  4020. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  4021. : 0;
  4022. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  4023. // Args[ArgIdx] can be null in malformed code.
  4024. if (const Expr *Arg = Args[ArgIdx]) {
  4025. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  4026. checkVariadicArgument(Arg, CallType);
  4027. }
  4028. }
  4029. }
  4030. if (FDecl || Proto) {
  4031. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  4032. // Type safety checking.
  4033. if (FDecl) {
  4034. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  4035. CheckArgumentWithTypeTag(I, Args, Loc);
  4036. }
  4037. }
  4038. if (FD)
  4039. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  4040. }
  4041. /// CheckConstructorCall - Check a constructor call for correctness and safety
  4042. /// properties not enforced by the C type system.
  4043. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  4044. ArrayRef<const Expr *> Args,
  4045. const FunctionProtoType *Proto,
  4046. SourceLocation Loc) {
  4047. VariadicCallType CallType =
  4048. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  4049. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  4050. Loc, SourceRange(), CallType);
  4051. }
  4052. /// CheckFunctionCall - Check a direct function call for various correctness
  4053. /// and safety properties not strictly enforced by the C type system.
  4054. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  4055. const FunctionProtoType *Proto) {
  4056. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  4057. isa<CXXMethodDecl>(FDecl);
  4058. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  4059. IsMemberOperatorCall;
  4060. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  4061. TheCall->getCallee());
  4062. Expr** Args = TheCall->getArgs();
  4063. unsigned NumArgs = TheCall->getNumArgs();
  4064. Expr *ImplicitThis = nullptr;
  4065. if (IsMemberOperatorCall) {
  4066. // If this is a call to a member operator, hide the first argument
  4067. // from checkCall.
  4068. // FIXME: Our choice of AST representation here is less than ideal.
  4069. ImplicitThis = Args[0];
  4070. ++Args;
  4071. --NumArgs;
  4072. } else if (IsMemberFunction)
  4073. ImplicitThis =
  4074. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  4075. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  4076. IsMemberFunction, TheCall->getRParenLoc(),
  4077. TheCall->getCallee()->getSourceRange(), CallType);
  4078. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  4079. // None of the checks below are needed for functions that don't have
  4080. // simple names (e.g., C++ conversion functions).
  4081. if (!FnInfo)
  4082. return false;
  4083. CheckAbsoluteValueFunction(TheCall, FDecl);
  4084. CheckMaxUnsignedZero(TheCall, FDecl);
  4085. if (getLangOpts().ObjC)
  4086. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  4087. unsigned CMId = FDecl->getMemoryFunctionKind();
  4088. if (CMId == 0)
  4089. return false;
  4090. // Handle memory setting and copying functions.
  4091. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  4092. CheckStrlcpycatArguments(TheCall, FnInfo);
  4093. else if (CMId == Builtin::BIstrncat)
  4094. CheckStrncatArguments(TheCall, FnInfo);
  4095. else
  4096. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  4097. return false;
  4098. }
  4099. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  4100. ArrayRef<const Expr *> Args) {
  4101. VariadicCallType CallType =
  4102. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  4103. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  4104. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  4105. CallType);
  4106. return false;
  4107. }
  4108. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  4109. const FunctionProtoType *Proto) {
  4110. QualType Ty;
  4111. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  4112. Ty = V->getType().getNonReferenceType();
  4113. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  4114. Ty = F->getType().getNonReferenceType();
  4115. else
  4116. return false;
  4117. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  4118. !Ty->isFunctionProtoType())
  4119. return false;
  4120. VariadicCallType CallType;
  4121. if (!Proto || !Proto->isVariadic()) {
  4122. CallType = VariadicDoesNotApply;
  4123. } else if (Ty->isBlockPointerType()) {
  4124. CallType = VariadicBlock;
  4125. } else { // Ty->isFunctionPointerType()
  4126. CallType = VariadicFunction;
  4127. }
  4128. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  4129. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4130. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4131. TheCall->getCallee()->getSourceRange(), CallType);
  4132. return false;
  4133. }
  4134. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  4135. /// such as function pointers returned from functions.
  4136. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  4137. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  4138. TheCall->getCallee());
  4139. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  4140. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4141. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4142. TheCall->getCallee()->getSourceRange(), CallType);
  4143. return false;
  4144. }
  4145. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  4146. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  4147. return false;
  4148. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  4149. switch (Op) {
  4150. case AtomicExpr::AO__c11_atomic_init:
  4151. case AtomicExpr::AO__opencl_atomic_init:
  4152. llvm_unreachable("There is no ordering argument for an init");
  4153. case AtomicExpr::AO__c11_atomic_load:
  4154. case AtomicExpr::AO__opencl_atomic_load:
  4155. case AtomicExpr::AO__atomic_load_n:
  4156. case AtomicExpr::AO__atomic_load:
  4157. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  4158. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4159. case AtomicExpr::AO__c11_atomic_store:
  4160. case AtomicExpr::AO__opencl_atomic_store:
  4161. case AtomicExpr::AO__atomic_store:
  4162. case AtomicExpr::AO__atomic_store_n:
  4163. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  4164. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  4165. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4166. default:
  4167. return true;
  4168. }
  4169. }
  4170. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  4171. AtomicExpr::AtomicOp Op) {
  4172. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  4173. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4174. // All the non-OpenCL operations take one of the following forms.
  4175. // The OpenCL operations take the __c11 forms with one extra argument for
  4176. // synchronization scope.
  4177. enum {
  4178. // C __c11_atomic_init(A *, C)
  4179. Init,
  4180. // C __c11_atomic_load(A *, int)
  4181. Load,
  4182. // void __atomic_load(A *, CP, int)
  4183. LoadCopy,
  4184. // void __atomic_store(A *, CP, int)
  4185. Copy,
  4186. // C __c11_atomic_add(A *, M, int)
  4187. Arithmetic,
  4188. // C __atomic_exchange_n(A *, CP, int)
  4189. Xchg,
  4190. // void __atomic_exchange(A *, C *, CP, int)
  4191. GNUXchg,
  4192. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  4193. C11CmpXchg,
  4194. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  4195. GNUCmpXchg
  4196. } Form = Init;
  4197. const unsigned NumForm = GNUCmpXchg + 1;
  4198. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  4199. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  4200. // where:
  4201. // C is an appropriate type,
  4202. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  4203. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  4204. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  4205. // the int parameters are for orderings.
  4206. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  4207. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  4208. "need to update code for modified forms");
  4209. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  4210. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  4211. AtomicExpr::AO__atomic_load,
  4212. "need to update code for modified C11 atomics");
  4213. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  4214. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  4215. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  4216. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  4217. IsOpenCL;
  4218. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  4219. Op == AtomicExpr::AO__atomic_store_n ||
  4220. Op == AtomicExpr::AO__atomic_exchange_n ||
  4221. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  4222. bool IsAddSub = false;
  4223. bool IsMinMax = false;
  4224. switch (Op) {
  4225. case AtomicExpr::AO__c11_atomic_init:
  4226. case AtomicExpr::AO__opencl_atomic_init:
  4227. Form = Init;
  4228. break;
  4229. case AtomicExpr::AO__c11_atomic_load:
  4230. case AtomicExpr::AO__opencl_atomic_load:
  4231. case AtomicExpr::AO__atomic_load_n:
  4232. Form = Load;
  4233. break;
  4234. case AtomicExpr::AO__atomic_load:
  4235. Form = LoadCopy;
  4236. break;
  4237. case AtomicExpr::AO__c11_atomic_store:
  4238. case AtomicExpr::AO__opencl_atomic_store:
  4239. case AtomicExpr::AO__atomic_store:
  4240. case AtomicExpr::AO__atomic_store_n:
  4241. Form = Copy;
  4242. break;
  4243. case AtomicExpr::AO__c11_atomic_fetch_add:
  4244. case AtomicExpr::AO__c11_atomic_fetch_sub:
  4245. case AtomicExpr::AO__opencl_atomic_fetch_add:
  4246. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  4247. case AtomicExpr::AO__opencl_atomic_fetch_min:
  4248. case AtomicExpr::AO__opencl_atomic_fetch_max:
  4249. case AtomicExpr::AO__atomic_fetch_add:
  4250. case AtomicExpr::AO__atomic_fetch_sub:
  4251. case AtomicExpr::AO__atomic_add_fetch:
  4252. case AtomicExpr::AO__atomic_sub_fetch:
  4253. IsAddSub = true;
  4254. LLVM_FALLTHROUGH;
  4255. case AtomicExpr::AO__c11_atomic_fetch_and:
  4256. case AtomicExpr::AO__c11_atomic_fetch_or:
  4257. case AtomicExpr::AO__c11_atomic_fetch_xor:
  4258. case AtomicExpr::AO__opencl_atomic_fetch_and:
  4259. case AtomicExpr::AO__opencl_atomic_fetch_or:
  4260. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  4261. case AtomicExpr::AO__atomic_fetch_and:
  4262. case AtomicExpr::AO__atomic_fetch_or:
  4263. case AtomicExpr::AO__atomic_fetch_xor:
  4264. case AtomicExpr::AO__atomic_fetch_nand:
  4265. case AtomicExpr::AO__atomic_and_fetch:
  4266. case AtomicExpr::AO__atomic_or_fetch:
  4267. case AtomicExpr::AO__atomic_xor_fetch:
  4268. case AtomicExpr::AO__atomic_nand_fetch:
  4269. Form = Arithmetic;
  4270. break;
  4271. case AtomicExpr::AO__atomic_fetch_min:
  4272. case AtomicExpr::AO__atomic_fetch_max:
  4273. IsMinMax = true;
  4274. Form = Arithmetic;
  4275. break;
  4276. case AtomicExpr::AO__c11_atomic_exchange:
  4277. case AtomicExpr::AO__opencl_atomic_exchange:
  4278. case AtomicExpr::AO__atomic_exchange_n:
  4279. Form = Xchg;
  4280. break;
  4281. case AtomicExpr::AO__atomic_exchange:
  4282. Form = GNUXchg;
  4283. break;
  4284. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  4285. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  4286. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  4287. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  4288. Form = C11CmpXchg;
  4289. break;
  4290. case AtomicExpr::AO__atomic_compare_exchange:
  4291. case AtomicExpr::AO__atomic_compare_exchange_n:
  4292. Form = GNUCmpXchg;
  4293. break;
  4294. }
  4295. unsigned AdjustedNumArgs = NumArgs[Form];
  4296. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  4297. ++AdjustedNumArgs;
  4298. // Check we have the right number of arguments.
  4299. if (TheCall->getNumArgs() < AdjustedNumArgs) {
  4300. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  4301. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4302. << TheCall->getCallee()->getSourceRange();
  4303. return ExprError();
  4304. } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
  4305. Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
  4306. diag::err_typecheck_call_too_many_args)
  4307. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4308. << TheCall->getCallee()->getSourceRange();
  4309. return ExprError();
  4310. }
  4311. // Inspect the first argument of the atomic operation.
  4312. Expr *Ptr = TheCall->getArg(0);
  4313. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  4314. if (ConvertedPtr.isInvalid())
  4315. return ExprError();
  4316. Ptr = ConvertedPtr.get();
  4317. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  4318. if (!pointerType) {
  4319. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4320. << Ptr->getType() << Ptr->getSourceRange();
  4321. return ExprError();
  4322. }
  4323. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  4324. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  4325. QualType ValType = AtomTy; // 'C'
  4326. if (IsC11) {
  4327. if (!AtomTy->isAtomicType()) {
  4328. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
  4329. << Ptr->getType() << Ptr->getSourceRange();
  4330. return ExprError();
  4331. }
  4332. if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
  4333. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  4334. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
  4335. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  4336. << Ptr->getSourceRange();
  4337. return ExprError();
  4338. }
  4339. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  4340. } else if (Form != Load && Form != LoadCopy) {
  4341. if (ValType.isConstQualified()) {
  4342. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
  4343. << Ptr->getType() << Ptr->getSourceRange();
  4344. return ExprError();
  4345. }
  4346. }
  4347. // For an arithmetic operation, the implied arithmetic must be well-formed.
  4348. if (Form == Arithmetic) {
  4349. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  4350. if (IsAddSub && !ValType->isIntegerType()
  4351. && !ValType->isPointerType()) {
  4352. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4353. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4354. return ExprError();
  4355. }
  4356. if (IsMinMax) {
  4357. const BuiltinType *BT = ValType->getAs<BuiltinType>();
  4358. if (!BT || (BT->getKind() != BuiltinType::Int &&
  4359. BT->getKind() != BuiltinType::UInt)) {
  4360. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
  4361. return ExprError();
  4362. }
  4363. }
  4364. if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
  4365. Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
  4366. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4367. return ExprError();
  4368. }
  4369. if (IsC11 && ValType->isPointerType() &&
  4370. RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
  4371. diag::err_incomplete_type)) {
  4372. return ExprError();
  4373. }
  4374. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  4375. // For __atomic_*_n operations, the value type must be a scalar integral or
  4376. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  4377. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4378. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4379. return ExprError();
  4380. }
  4381. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  4382. !AtomTy->isScalarType()) {
  4383. // For GNU atomics, require a trivially-copyable type. This is not part of
  4384. // the GNU atomics specification, but we enforce it for sanity.
  4385. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
  4386. << Ptr->getType() << Ptr->getSourceRange();
  4387. return ExprError();
  4388. }
  4389. switch (ValType.getObjCLifetime()) {
  4390. case Qualifiers::OCL_None:
  4391. case Qualifiers::OCL_ExplicitNone:
  4392. // okay
  4393. break;
  4394. case Qualifiers::OCL_Weak:
  4395. case Qualifiers::OCL_Strong:
  4396. case Qualifiers::OCL_Autoreleasing:
  4397. // FIXME: Can this happen? By this point, ValType should be known
  4398. // to be trivially copyable.
  4399. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4400. << ValType << Ptr->getSourceRange();
  4401. return ExprError();
  4402. }
  4403. // All atomic operations have an overload which takes a pointer to a volatile
  4404. // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
  4405. // into the result or the other operands. Similarly atomic_load takes a
  4406. // pointer to a const 'A'.
  4407. ValType.removeLocalVolatile();
  4408. ValType.removeLocalConst();
  4409. QualType ResultType = ValType;
  4410. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  4411. Form == Init)
  4412. ResultType = Context.VoidTy;
  4413. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  4414. ResultType = Context.BoolTy;
  4415. // The type of a parameter passed 'by value'. In the GNU atomics, such
  4416. // arguments are actually passed as pointers.
  4417. QualType ByValType = ValType; // 'CP'
  4418. bool IsPassedByAddress = false;
  4419. if (!IsC11 && !IsN) {
  4420. ByValType = Ptr->getType();
  4421. IsPassedByAddress = true;
  4422. }
  4423. // The first argument's non-CV pointer type is used to deduce the type of
  4424. // subsequent arguments, except for:
  4425. // - weak flag (always converted to bool)
  4426. // - memory order (always converted to int)
  4427. // - scope (always converted to int)
  4428. for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
  4429. QualType Ty;
  4430. if (i < NumVals[Form] + 1) {
  4431. switch (i) {
  4432. case 0:
  4433. // The first argument is always a pointer. It has a fixed type.
  4434. // It is always dereferenced, a nullptr is undefined.
  4435. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4436. // Nothing else to do: we already know all we want about this pointer.
  4437. continue;
  4438. case 1:
  4439. // The second argument is the non-atomic operand. For arithmetic, this
  4440. // is always passed by value, and for a compare_exchange it is always
  4441. // passed by address. For the rest, GNU uses by-address and C11 uses
  4442. // by-value.
  4443. assert(Form != Load);
  4444. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  4445. Ty = ValType;
  4446. else if (Form == Copy || Form == Xchg) {
  4447. if (IsPassedByAddress)
  4448. // The value pointer is always dereferenced, a nullptr is undefined.
  4449. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4450. Ty = ByValType;
  4451. } else if (Form == Arithmetic)
  4452. Ty = Context.getPointerDiffType();
  4453. else {
  4454. Expr *ValArg = TheCall->getArg(i);
  4455. // The value pointer is always dereferenced, a nullptr is undefined.
  4456. CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
  4457. LangAS AS = LangAS::Default;
  4458. // Keep address space of non-atomic pointer type.
  4459. if (const PointerType *PtrTy =
  4460. ValArg->getType()->getAs<PointerType>()) {
  4461. AS = PtrTy->getPointeeType().getAddressSpace();
  4462. }
  4463. Ty = Context.getPointerType(
  4464. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  4465. }
  4466. break;
  4467. case 2:
  4468. // The third argument to compare_exchange / GNU exchange is the desired
  4469. // value, either by-value (for the C11 and *_n variant) or as a pointer.
  4470. if (IsPassedByAddress)
  4471. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4472. Ty = ByValType;
  4473. break;
  4474. case 3:
  4475. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  4476. Ty = Context.BoolTy;
  4477. break;
  4478. }
  4479. } else {
  4480. // The order(s) and scope are always converted to int.
  4481. Ty = Context.IntTy;
  4482. }
  4483. InitializedEntity Entity =
  4484. InitializedEntity::InitializeParameter(Context, Ty, false);
  4485. ExprResult Arg = TheCall->getArg(i);
  4486. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4487. if (Arg.isInvalid())
  4488. return true;
  4489. TheCall->setArg(i, Arg.get());
  4490. }
  4491. // Permute the arguments into a 'consistent' order.
  4492. SmallVector<Expr*, 5> SubExprs;
  4493. SubExprs.push_back(Ptr);
  4494. switch (Form) {
  4495. case Init:
  4496. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  4497. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4498. break;
  4499. case Load:
  4500. SubExprs.push_back(TheCall->getArg(1)); // Order
  4501. break;
  4502. case LoadCopy:
  4503. case Copy:
  4504. case Arithmetic:
  4505. case Xchg:
  4506. SubExprs.push_back(TheCall->getArg(2)); // Order
  4507. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4508. break;
  4509. case GNUXchg:
  4510. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  4511. SubExprs.push_back(TheCall->getArg(3)); // Order
  4512. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4513. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4514. break;
  4515. case C11CmpXchg:
  4516. SubExprs.push_back(TheCall->getArg(3)); // Order
  4517. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4518. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  4519. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4520. break;
  4521. case GNUCmpXchg:
  4522. SubExprs.push_back(TheCall->getArg(4)); // Order
  4523. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4524. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  4525. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4526. SubExprs.push_back(TheCall->getArg(3)); // Weak
  4527. break;
  4528. }
  4529. if (SubExprs.size() >= 2 && Form != Init) {
  4530. llvm::APSInt Result(32);
  4531. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  4532. !isValidOrderingForOp(Result.getSExtValue(), Op))
  4533. Diag(SubExprs[1]->getBeginLoc(),
  4534. diag::warn_atomic_op_has_invalid_memory_order)
  4535. << SubExprs[1]->getSourceRange();
  4536. }
  4537. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  4538. auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
  4539. llvm::APSInt Result(32);
  4540. if (Scope->isIntegerConstantExpr(Result, Context) &&
  4541. !ScopeModel->isValid(Result.getZExtValue())) {
  4542. Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
  4543. << Scope->getSourceRange();
  4544. }
  4545. SubExprs.push_back(Scope);
  4546. }
  4547. AtomicExpr *AE =
  4548. new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
  4549. ResultType, Op, TheCall->getRParenLoc());
  4550. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  4551. Op == AtomicExpr::AO__c11_atomic_store ||
  4552. Op == AtomicExpr::AO__opencl_atomic_load ||
  4553. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  4554. Context.AtomicUsesUnsupportedLibcall(AE))
  4555. Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
  4556. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  4557. Op == AtomicExpr::AO__opencl_atomic_load)
  4558. ? 0
  4559. : 1);
  4560. return AE;
  4561. }
  4562. /// checkBuiltinArgument - Given a call to a builtin function, perform
  4563. /// normal type-checking on the given argument, updating the call in
  4564. /// place. This is useful when a builtin function requires custom
  4565. /// type-checking for some of its arguments but not necessarily all of
  4566. /// them.
  4567. ///
  4568. /// Returns true on error.
  4569. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  4570. FunctionDecl *Fn = E->getDirectCallee();
  4571. assert(Fn && "builtin call without direct callee!");
  4572. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  4573. InitializedEntity Entity =
  4574. InitializedEntity::InitializeParameter(S.Context, Param);
  4575. ExprResult Arg = E->getArg(0);
  4576. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4577. if (Arg.isInvalid())
  4578. return true;
  4579. E->setArg(ArgIndex, Arg.get());
  4580. return false;
  4581. }
  4582. /// We have a call to a function like __sync_fetch_and_add, which is an
  4583. /// overloaded function based on the pointer type of its first argument.
  4584. /// The main BuildCallExpr routines have already promoted the types of
  4585. /// arguments because all of these calls are prototyped as void(...).
  4586. ///
  4587. /// This function goes through and does final semantic checking for these
  4588. /// builtins, as well as generating any warnings.
  4589. ExprResult
  4590. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  4591. CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
  4592. Expr *Callee = TheCall->getCallee();
  4593. DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
  4594. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4595. // Ensure that we have at least one argument to do type inference from.
  4596. if (TheCall->getNumArgs() < 1) {
  4597. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4598. << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
  4599. return ExprError();
  4600. }
  4601. // Inspect the first argument of the atomic builtin. This should always be
  4602. // a pointer type, whose element is an integral scalar or pointer type.
  4603. // Because it is a pointer type, we don't have to worry about any implicit
  4604. // casts here.
  4605. // FIXME: We don't allow floating point scalars as input.
  4606. Expr *FirstArg = TheCall->getArg(0);
  4607. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  4608. if (FirstArgResult.isInvalid())
  4609. return ExprError();
  4610. FirstArg = FirstArgResult.get();
  4611. TheCall->setArg(0, FirstArg);
  4612. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  4613. if (!pointerType) {
  4614. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4615. << FirstArg->getType() << FirstArg->getSourceRange();
  4616. return ExprError();
  4617. }
  4618. QualType ValType = pointerType->getPointeeType();
  4619. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4620. !ValType->isBlockPointerType()) {
  4621. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
  4622. << FirstArg->getType() << FirstArg->getSourceRange();
  4623. return ExprError();
  4624. }
  4625. if (ValType.isConstQualified()) {
  4626. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
  4627. << FirstArg->getType() << FirstArg->getSourceRange();
  4628. return ExprError();
  4629. }
  4630. switch (ValType.getObjCLifetime()) {
  4631. case Qualifiers::OCL_None:
  4632. case Qualifiers::OCL_ExplicitNone:
  4633. // okay
  4634. break;
  4635. case Qualifiers::OCL_Weak:
  4636. case Qualifiers::OCL_Strong:
  4637. case Qualifiers::OCL_Autoreleasing:
  4638. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4639. << ValType << FirstArg->getSourceRange();
  4640. return ExprError();
  4641. }
  4642. // Strip any qualifiers off ValType.
  4643. ValType = ValType.getUnqualifiedType();
  4644. // The majority of builtins return a value, but a few have special return
  4645. // types, so allow them to override appropriately below.
  4646. QualType ResultType = ValType;
  4647. // We need to figure out which concrete builtin this maps onto. For example,
  4648. // __sync_fetch_and_add with a 2 byte object turns into
  4649. // __sync_fetch_and_add_2.
  4650. #define BUILTIN_ROW(x) \
  4651. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  4652. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  4653. static const unsigned BuiltinIndices[][5] = {
  4654. BUILTIN_ROW(__sync_fetch_and_add),
  4655. BUILTIN_ROW(__sync_fetch_and_sub),
  4656. BUILTIN_ROW(__sync_fetch_and_or),
  4657. BUILTIN_ROW(__sync_fetch_and_and),
  4658. BUILTIN_ROW(__sync_fetch_and_xor),
  4659. BUILTIN_ROW(__sync_fetch_and_nand),
  4660. BUILTIN_ROW(__sync_add_and_fetch),
  4661. BUILTIN_ROW(__sync_sub_and_fetch),
  4662. BUILTIN_ROW(__sync_and_and_fetch),
  4663. BUILTIN_ROW(__sync_or_and_fetch),
  4664. BUILTIN_ROW(__sync_xor_and_fetch),
  4665. BUILTIN_ROW(__sync_nand_and_fetch),
  4666. BUILTIN_ROW(__sync_val_compare_and_swap),
  4667. BUILTIN_ROW(__sync_bool_compare_and_swap),
  4668. BUILTIN_ROW(__sync_lock_test_and_set),
  4669. BUILTIN_ROW(__sync_lock_release),
  4670. BUILTIN_ROW(__sync_swap)
  4671. };
  4672. #undef BUILTIN_ROW
  4673. // Determine the index of the size.
  4674. unsigned SizeIndex;
  4675. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  4676. case 1: SizeIndex = 0; break;
  4677. case 2: SizeIndex = 1; break;
  4678. case 4: SizeIndex = 2; break;
  4679. case 8: SizeIndex = 3; break;
  4680. case 16: SizeIndex = 4; break;
  4681. default:
  4682. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
  4683. << FirstArg->getType() << FirstArg->getSourceRange();
  4684. return ExprError();
  4685. }
  4686. // Each of these builtins has one pointer argument, followed by some number of
  4687. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  4688. // that we ignore. Find out which row of BuiltinIndices to read from as well
  4689. // as the number of fixed args.
  4690. unsigned BuiltinID = FDecl->getBuiltinID();
  4691. unsigned BuiltinIndex, NumFixed = 1;
  4692. bool WarnAboutSemanticsChange = false;
  4693. switch (BuiltinID) {
  4694. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  4695. case Builtin::BI__sync_fetch_and_add:
  4696. case Builtin::BI__sync_fetch_and_add_1:
  4697. case Builtin::BI__sync_fetch_and_add_2:
  4698. case Builtin::BI__sync_fetch_and_add_4:
  4699. case Builtin::BI__sync_fetch_and_add_8:
  4700. case Builtin::BI__sync_fetch_and_add_16:
  4701. BuiltinIndex = 0;
  4702. break;
  4703. case Builtin::BI__sync_fetch_and_sub:
  4704. case Builtin::BI__sync_fetch_and_sub_1:
  4705. case Builtin::BI__sync_fetch_and_sub_2:
  4706. case Builtin::BI__sync_fetch_and_sub_4:
  4707. case Builtin::BI__sync_fetch_and_sub_8:
  4708. case Builtin::BI__sync_fetch_and_sub_16:
  4709. BuiltinIndex = 1;
  4710. break;
  4711. case Builtin::BI__sync_fetch_and_or:
  4712. case Builtin::BI__sync_fetch_and_or_1:
  4713. case Builtin::BI__sync_fetch_and_or_2:
  4714. case Builtin::BI__sync_fetch_and_or_4:
  4715. case Builtin::BI__sync_fetch_and_or_8:
  4716. case Builtin::BI__sync_fetch_and_or_16:
  4717. BuiltinIndex = 2;
  4718. break;
  4719. case Builtin::BI__sync_fetch_and_and:
  4720. case Builtin::BI__sync_fetch_and_and_1:
  4721. case Builtin::BI__sync_fetch_and_and_2:
  4722. case Builtin::BI__sync_fetch_and_and_4:
  4723. case Builtin::BI__sync_fetch_and_and_8:
  4724. case Builtin::BI__sync_fetch_and_and_16:
  4725. BuiltinIndex = 3;
  4726. break;
  4727. case Builtin::BI__sync_fetch_and_xor:
  4728. case Builtin::BI__sync_fetch_and_xor_1:
  4729. case Builtin::BI__sync_fetch_and_xor_2:
  4730. case Builtin::BI__sync_fetch_and_xor_4:
  4731. case Builtin::BI__sync_fetch_and_xor_8:
  4732. case Builtin::BI__sync_fetch_and_xor_16:
  4733. BuiltinIndex = 4;
  4734. break;
  4735. case Builtin::BI__sync_fetch_and_nand:
  4736. case Builtin::BI__sync_fetch_and_nand_1:
  4737. case Builtin::BI__sync_fetch_and_nand_2:
  4738. case Builtin::BI__sync_fetch_and_nand_4:
  4739. case Builtin::BI__sync_fetch_and_nand_8:
  4740. case Builtin::BI__sync_fetch_and_nand_16:
  4741. BuiltinIndex = 5;
  4742. WarnAboutSemanticsChange = true;
  4743. break;
  4744. case Builtin::BI__sync_add_and_fetch:
  4745. case Builtin::BI__sync_add_and_fetch_1:
  4746. case Builtin::BI__sync_add_and_fetch_2:
  4747. case Builtin::BI__sync_add_and_fetch_4:
  4748. case Builtin::BI__sync_add_and_fetch_8:
  4749. case Builtin::BI__sync_add_and_fetch_16:
  4750. BuiltinIndex = 6;
  4751. break;
  4752. case Builtin::BI__sync_sub_and_fetch:
  4753. case Builtin::BI__sync_sub_and_fetch_1:
  4754. case Builtin::BI__sync_sub_and_fetch_2:
  4755. case Builtin::BI__sync_sub_and_fetch_4:
  4756. case Builtin::BI__sync_sub_and_fetch_8:
  4757. case Builtin::BI__sync_sub_and_fetch_16:
  4758. BuiltinIndex = 7;
  4759. break;
  4760. case Builtin::BI__sync_and_and_fetch:
  4761. case Builtin::BI__sync_and_and_fetch_1:
  4762. case Builtin::BI__sync_and_and_fetch_2:
  4763. case Builtin::BI__sync_and_and_fetch_4:
  4764. case Builtin::BI__sync_and_and_fetch_8:
  4765. case Builtin::BI__sync_and_and_fetch_16:
  4766. BuiltinIndex = 8;
  4767. break;
  4768. case Builtin::BI__sync_or_and_fetch:
  4769. case Builtin::BI__sync_or_and_fetch_1:
  4770. case Builtin::BI__sync_or_and_fetch_2:
  4771. case Builtin::BI__sync_or_and_fetch_4:
  4772. case Builtin::BI__sync_or_and_fetch_8:
  4773. case Builtin::BI__sync_or_and_fetch_16:
  4774. BuiltinIndex = 9;
  4775. break;
  4776. case Builtin::BI__sync_xor_and_fetch:
  4777. case Builtin::BI__sync_xor_and_fetch_1:
  4778. case Builtin::BI__sync_xor_and_fetch_2:
  4779. case Builtin::BI__sync_xor_and_fetch_4:
  4780. case Builtin::BI__sync_xor_and_fetch_8:
  4781. case Builtin::BI__sync_xor_and_fetch_16:
  4782. BuiltinIndex = 10;
  4783. break;
  4784. case Builtin::BI__sync_nand_and_fetch:
  4785. case Builtin::BI__sync_nand_and_fetch_1:
  4786. case Builtin::BI__sync_nand_and_fetch_2:
  4787. case Builtin::BI__sync_nand_and_fetch_4:
  4788. case Builtin::BI__sync_nand_and_fetch_8:
  4789. case Builtin::BI__sync_nand_and_fetch_16:
  4790. BuiltinIndex = 11;
  4791. WarnAboutSemanticsChange = true;
  4792. break;
  4793. case Builtin::BI__sync_val_compare_and_swap:
  4794. case Builtin::BI__sync_val_compare_and_swap_1:
  4795. case Builtin::BI__sync_val_compare_and_swap_2:
  4796. case Builtin::BI__sync_val_compare_and_swap_4:
  4797. case Builtin::BI__sync_val_compare_and_swap_8:
  4798. case Builtin::BI__sync_val_compare_and_swap_16:
  4799. BuiltinIndex = 12;
  4800. NumFixed = 2;
  4801. break;
  4802. case Builtin::BI__sync_bool_compare_and_swap:
  4803. case Builtin::BI__sync_bool_compare_and_swap_1:
  4804. case Builtin::BI__sync_bool_compare_and_swap_2:
  4805. case Builtin::BI__sync_bool_compare_and_swap_4:
  4806. case Builtin::BI__sync_bool_compare_and_swap_8:
  4807. case Builtin::BI__sync_bool_compare_and_swap_16:
  4808. BuiltinIndex = 13;
  4809. NumFixed = 2;
  4810. ResultType = Context.BoolTy;
  4811. break;
  4812. case Builtin::BI__sync_lock_test_and_set:
  4813. case Builtin::BI__sync_lock_test_and_set_1:
  4814. case Builtin::BI__sync_lock_test_and_set_2:
  4815. case Builtin::BI__sync_lock_test_and_set_4:
  4816. case Builtin::BI__sync_lock_test_and_set_8:
  4817. case Builtin::BI__sync_lock_test_and_set_16:
  4818. BuiltinIndex = 14;
  4819. break;
  4820. case Builtin::BI__sync_lock_release:
  4821. case Builtin::BI__sync_lock_release_1:
  4822. case Builtin::BI__sync_lock_release_2:
  4823. case Builtin::BI__sync_lock_release_4:
  4824. case Builtin::BI__sync_lock_release_8:
  4825. case Builtin::BI__sync_lock_release_16:
  4826. BuiltinIndex = 15;
  4827. NumFixed = 0;
  4828. ResultType = Context.VoidTy;
  4829. break;
  4830. case Builtin::BI__sync_swap:
  4831. case Builtin::BI__sync_swap_1:
  4832. case Builtin::BI__sync_swap_2:
  4833. case Builtin::BI__sync_swap_4:
  4834. case Builtin::BI__sync_swap_8:
  4835. case Builtin::BI__sync_swap_16:
  4836. BuiltinIndex = 16;
  4837. break;
  4838. }
  4839. // Now that we know how many fixed arguments we expect, first check that we
  4840. // have at least that many.
  4841. if (TheCall->getNumArgs() < 1+NumFixed) {
  4842. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4843. << 0 << 1 + NumFixed << TheCall->getNumArgs()
  4844. << Callee->getSourceRange();
  4845. return ExprError();
  4846. }
  4847. Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
  4848. << Callee->getSourceRange();
  4849. if (WarnAboutSemanticsChange) {
  4850. Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
  4851. << Callee->getSourceRange();
  4852. }
  4853. // Get the decl for the concrete builtin from this, we can tell what the
  4854. // concrete integer type we should convert to is.
  4855. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  4856. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  4857. FunctionDecl *NewBuiltinDecl;
  4858. if (NewBuiltinID == BuiltinID)
  4859. NewBuiltinDecl = FDecl;
  4860. else {
  4861. // Perform builtin lookup to avoid redeclaring it.
  4862. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  4863. LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
  4864. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  4865. assert(Res.getFoundDecl());
  4866. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  4867. if (!NewBuiltinDecl)
  4868. return ExprError();
  4869. }
  4870. // The first argument --- the pointer --- has a fixed type; we
  4871. // deduce the types of the rest of the arguments accordingly. Walk
  4872. // the remaining arguments, converting them to the deduced value type.
  4873. for (unsigned i = 0; i != NumFixed; ++i) {
  4874. ExprResult Arg = TheCall->getArg(i+1);
  4875. // GCC does an implicit conversion to the pointer or integer ValType. This
  4876. // can fail in some cases (1i -> int**), check for this error case now.
  4877. // Initialize the argument.
  4878. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  4879. ValType, /*consume*/ false);
  4880. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4881. if (Arg.isInvalid())
  4882. return ExprError();
  4883. // Okay, we have something that *can* be converted to the right type. Check
  4884. // to see if there is a potentially weird extension going on here. This can
  4885. // happen when you do an atomic operation on something like an char* and
  4886. // pass in 42. The 42 gets converted to char. This is even more strange
  4887. // for things like 45.123 -> char, etc.
  4888. // FIXME: Do this check.
  4889. TheCall->setArg(i+1, Arg.get());
  4890. }
  4891. // Create a new DeclRefExpr to refer to the new decl.
  4892. DeclRefExpr *NewDRE = DeclRefExpr::Create(
  4893. Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
  4894. /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
  4895. DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
  4896. // Set the callee in the CallExpr.
  4897. // FIXME: This loses syntactic information.
  4898. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  4899. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  4900. CK_BuiltinFnToFnPtr);
  4901. TheCall->setCallee(PromotedCall.get());
  4902. // Change the result type of the call to match the original value type. This
  4903. // is arbitrary, but the codegen for these builtins ins design to handle it
  4904. // gracefully.
  4905. TheCall->setType(ResultType);
  4906. return TheCallResult;
  4907. }
  4908. /// SemaBuiltinNontemporalOverloaded - We have a call to
  4909. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  4910. /// overloaded function based on the pointer type of its last argument.
  4911. ///
  4912. /// This function goes through and does final semantic checking for these
  4913. /// builtins.
  4914. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  4915. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  4916. DeclRefExpr *DRE =
  4917. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4918. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4919. unsigned BuiltinID = FDecl->getBuiltinID();
  4920. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  4921. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  4922. "Unexpected nontemporal load/store builtin!");
  4923. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  4924. unsigned numArgs = isStore ? 2 : 1;
  4925. // Ensure that we have the proper number of arguments.
  4926. if (checkArgCount(*this, TheCall, numArgs))
  4927. return ExprError();
  4928. // Inspect the last argument of the nontemporal builtin. This should always
  4929. // be a pointer type, from which we imply the type of the memory access.
  4930. // Because it is a pointer type, we don't have to worry about any implicit
  4931. // casts here.
  4932. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  4933. ExprResult PointerArgResult =
  4934. DefaultFunctionArrayLvalueConversion(PointerArg);
  4935. if (PointerArgResult.isInvalid())
  4936. return ExprError();
  4937. PointerArg = PointerArgResult.get();
  4938. TheCall->setArg(numArgs - 1, PointerArg);
  4939. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  4940. if (!pointerType) {
  4941. Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
  4942. << PointerArg->getType() << PointerArg->getSourceRange();
  4943. return ExprError();
  4944. }
  4945. QualType ValType = pointerType->getPointeeType();
  4946. // Strip any qualifiers off ValType.
  4947. ValType = ValType.getUnqualifiedType();
  4948. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4949. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  4950. !ValType->isVectorType()) {
  4951. Diag(DRE->getBeginLoc(),
  4952. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  4953. << PointerArg->getType() << PointerArg->getSourceRange();
  4954. return ExprError();
  4955. }
  4956. if (!isStore) {
  4957. TheCall->setType(ValType);
  4958. return TheCallResult;
  4959. }
  4960. ExprResult ValArg = TheCall->getArg(0);
  4961. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4962. Context, ValType, /*consume*/ false);
  4963. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  4964. if (ValArg.isInvalid())
  4965. return ExprError();
  4966. TheCall->setArg(0, ValArg.get());
  4967. TheCall->setType(Context.VoidTy);
  4968. return TheCallResult;
  4969. }
  4970. /// CheckObjCString - Checks that the argument to the builtin
  4971. /// CFString constructor is correct
  4972. /// Note: It might also make sense to do the UTF-16 conversion here (would
  4973. /// simplify the backend).
  4974. bool Sema::CheckObjCString(Expr *Arg) {
  4975. Arg = Arg->IgnoreParenCasts();
  4976. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  4977. if (!Literal || !Literal->isAscii()) {
  4978. Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
  4979. << Arg->getSourceRange();
  4980. return true;
  4981. }
  4982. if (Literal->containsNonAsciiOrNull()) {
  4983. StringRef String = Literal->getString();
  4984. unsigned NumBytes = String.size();
  4985. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  4986. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  4987. llvm::UTF16 *ToPtr = &ToBuf[0];
  4988. llvm::ConversionResult Result =
  4989. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  4990. ToPtr + NumBytes, llvm::strictConversion);
  4991. // Check for conversion failure.
  4992. if (Result != llvm::conversionOK)
  4993. Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
  4994. << Arg->getSourceRange();
  4995. }
  4996. return false;
  4997. }
  4998. /// CheckObjCString - Checks that the format string argument to the os_log()
  4999. /// and os_trace() functions is correct, and converts it to const char *.
  5000. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  5001. Arg = Arg->IgnoreParenCasts();
  5002. auto *Literal = dyn_cast<StringLiteral>(Arg);
  5003. if (!Literal) {
  5004. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  5005. Literal = ObjcLiteral->getString();
  5006. }
  5007. }
  5008. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  5009. return ExprError(
  5010. Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
  5011. << Arg->getSourceRange());
  5012. }
  5013. ExprResult Result(Literal);
  5014. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  5015. InitializedEntity Entity =
  5016. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  5017. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  5018. return Result;
  5019. }
  5020. /// Check that the user is calling the appropriate va_start builtin for the
  5021. /// target and calling convention.
  5022. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  5023. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  5024. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  5025. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  5026. bool IsWindows = TT.isOSWindows();
  5027. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  5028. if (IsX64 || IsAArch64) {
  5029. CallingConv CC = CC_C;
  5030. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  5031. CC = FD->getType()->getAs<FunctionType>()->getCallConv();
  5032. if (IsMSVAStart) {
  5033. // Don't allow this in System V ABI functions.
  5034. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  5035. return S.Diag(Fn->getBeginLoc(),
  5036. diag::err_ms_va_start_used_in_sysv_function);
  5037. } else {
  5038. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  5039. // On x64 Windows, don't allow this in System V ABI functions.
  5040. // (Yes, that means there's no corresponding way to support variadic
  5041. // System V ABI functions on Windows.)
  5042. if ((IsWindows && CC == CC_X86_64SysV) ||
  5043. (!IsWindows && CC == CC_Win64))
  5044. return S.Diag(Fn->getBeginLoc(),
  5045. diag::err_va_start_used_in_wrong_abi_function)
  5046. << !IsWindows;
  5047. }
  5048. return false;
  5049. }
  5050. if (IsMSVAStart)
  5051. return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
  5052. return false;
  5053. }
  5054. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  5055. ParmVarDecl **LastParam = nullptr) {
  5056. // Determine whether the current function, block, or obj-c method is variadic
  5057. // and get its parameter list.
  5058. bool IsVariadic = false;
  5059. ArrayRef<ParmVarDecl *> Params;
  5060. DeclContext *Caller = S.CurContext;
  5061. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  5062. IsVariadic = Block->isVariadic();
  5063. Params = Block->parameters();
  5064. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  5065. IsVariadic = FD->isVariadic();
  5066. Params = FD->parameters();
  5067. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  5068. IsVariadic = MD->isVariadic();
  5069. // FIXME: This isn't correct for methods (results in bogus warning).
  5070. Params = MD->parameters();
  5071. } else if (isa<CapturedDecl>(Caller)) {
  5072. // We don't support va_start in a CapturedDecl.
  5073. S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
  5074. return true;
  5075. } else {
  5076. // This must be some other declcontext that parses exprs.
  5077. S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
  5078. return true;
  5079. }
  5080. if (!IsVariadic) {
  5081. S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
  5082. return true;
  5083. }
  5084. if (LastParam)
  5085. *LastParam = Params.empty() ? nullptr : Params.back();
  5086. return false;
  5087. }
  5088. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  5089. /// for validity. Emit an error and return true on failure; return false
  5090. /// on success.
  5091. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  5092. Expr *Fn = TheCall->getCallee();
  5093. if (checkVAStartABI(*this, BuiltinID, Fn))
  5094. return true;
  5095. if (TheCall->getNumArgs() > 2) {
  5096. Diag(TheCall->getArg(2)->getBeginLoc(),
  5097. diag::err_typecheck_call_too_many_args)
  5098. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5099. << Fn->getSourceRange()
  5100. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5101. (*(TheCall->arg_end() - 1))->getEndLoc());
  5102. return true;
  5103. }
  5104. if (TheCall->getNumArgs() < 2) {
  5105. return Diag(TheCall->getEndLoc(),
  5106. diag::err_typecheck_call_too_few_args_at_least)
  5107. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  5108. }
  5109. // Type-check the first argument normally.
  5110. if (checkBuiltinArgument(*this, TheCall, 0))
  5111. return true;
  5112. // Check that the current function is variadic, and get its last parameter.
  5113. ParmVarDecl *LastParam;
  5114. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  5115. return true;
  5116. // Verify that the second argument to the builtin is the last argument of the
  5117. // current function or method.
  5118. bool SecondArgIsLastNamedArgument = false;
  5119. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  5120. // These are valid if SecondArgIsLastNamedArgument is false after the next
  5121. // block.
  5122. QualType Type;
  5123. SourceLocation ParamLoc;
  5124. bool IsCRegister = false;
  5125. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  5126. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  5127. SecondArgIsLastNamedArgument = PV == LastParam;
  5128. Type = PV->getType();
  5129. ParamLoc = PV->getLocation();
  5130. IsCRegister =
  5131. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  5132. }
  5133. }
  5134. if (!SecondArgIsLastNamedArgument)
  5135. Diag(TheCall->getArg(1)->getBeginLoc(),
  5136. diag::warn_second_arg_of_va_start_not_last_named_param);
  5137. else if (IsCRegister || Type->isReferenceType() ||
  5138. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  5139. // Promotable integers are UB, but enumerations need a bit of
  5140. // extra checking to see what their promotable type actually is.
  5141. if (!Type->isPromotableIntegerType())
  5142. return false;
  5143. if (!Type->isEnumeralType())
  5144. return true;
  5145. const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
  5146. return !(ED &&
  5147. Context.typesAreCompatible(ED->getPromotionType(), Type));
  5148. }()) {
  5149. unsigned Reason = 0;
  5150. if (Type->isReferenceType()) Reason = 1;
  5151. else if (IsCRegister) Reason = 2;
  5152. Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
  5153. Diag(ParamLoc, diag::note_parameter_type) << Type;
  5154. }
  5155. TheCall->setType(Context.VoidTy);
  5156. return false;
  5157. }
  5158. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  5159. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  5160. // const char *named_addr);
  5161. Expr *Func = Call->getCallee();
  5162. if (Call->getNumArgs() < 3)
  5163. return Diag(Call->getEndLoc(),
  5164. diag::err_typecheck_call_too_few_args_at_least)
  5165. << 0 /*function call*/ << 3 << Call->getNumArgs();
  5166. // Type-check the first argument normally.
  5167. if (checkBuiltinArgument(*this, Call, 0))
  5168. return true;
  5169. // Check that the current function is variadic.
  5170. if (checkVAStartIsInVariadicFunction(*this, Func))
  5171. return true;
  5172. // __va_start on Windows does not validate the parameter qualifiers
  5173. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  5174. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  5175. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  5176. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  5177. const QualType &ConstCharPtrTy =
  5178. Context.getPointerType(Context.CharTy.withConst());
  5179. if (!Arg1Ty->isPointerType() ||
  5180. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  5181. Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5182. << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
  5183. << 0 /* qualifier difference */
  5184. << 3 /* parameter mismatch */
  5185. << 2 << Arg1->getType() << ConstCharPtrTy;
  5186. const QualType SizeTy = Context.getSizeType();
  5187. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  5188. Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5189. << Arg2->getType() << SizeTy << 1 /* different class */
  5190. << 0 /* qualifier difference */
  5191. << 3 /* parameter mismatch */
  5192. << 3 << Arg2->getType() << SizeTy;
  5193. return false;
  5194. }
  5195. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  5196. /// friends. This is declared to take (...), so we have to check everything.
  5197. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  5198. if (TheCall->getNumArgs() < 2)
  5199. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5200. << 0 << 2 << TheCall->getNumArgs() /*function call*/;
  5201. if (TheCall->getNumArgs() > 2)
  5202. return Diag(TheCall->getArg(2)->getBeginLoc(),
  5203. diag::err_typecheck_call_too_many_args)
  5204. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5205. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5206. (*(TheCall->arg_end() - 1))->getEndLoc());
  5207. ExprResult OrigArg0 = TheCall->getArg(0);
  5208. ExprResult OrigArg1 = TheCall->getArg(1);
  5209. // Do standard promotions between the two arguments, returning their common
  5210. // type.
  5211. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  5212. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  5213. return true;
  5214. // Make sure any conversions are pushed back into the call; this is
  5215. // type safe since unordered compare builtins are declared as "_Bool
  5216. // foo(...)".
  5217. TheCall->setArg(0, OrigArg0.get());
  5218. TheCall->setArg(1, OrigArg1.get());
  5219. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  5220. return false;
  5221. // If the common type isn't a real floating type, then the arguments were
  5222. // invalid for this operation.
  5223. if (Res.isNull() || !Res->isRealFloatingType())
  5224. return Diag(OrigArg0.get()->getBeginLoc(),
  5225. diag::err_typecheck_call_invalid_ordered_compare)
  5226. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  5227. << SourceRange(OrigArg0.get()->getBeginLoc(),
  5228. OrigArg1.get()->getEndLoc());
  5229. return false;
  5230. }
  5231. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  5232. /// __builtin_isnan and friends. This is declared to take (...), so we have
  5233. /// to check everything. We expect the last argument to be a floating point
  5234. /// value.
  5235. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  5236. if (TheCall->getNumArgs() < NumArgs)
  5237. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5238. << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
  5239. if (TheCall->getNumArgs() > NumArgs)
  5240. return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
  5241. diag::err_typecheck_call_too_many_args)
  5242. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  5243. << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
  5244. (*(TheCall->arg_end() - 1))->getEndLoc());
  5245. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  5246. if (OrigArg->isTypeDependent())
  5247. return false;
  5248. // This operation requires a non-_Complex floating-point number.
  5249. if (!OrigArg->getType()->isRealFloatingType())
  5250. return Diag(OrigArg->getBeginLoc(),
  5251. diag::err_typecheck_call_invalid_unary_fp)
  5252. << OrigArg->getType() << OrigArg->getSourceRange();
  5253. // If this is an implicit conversion from float -> float, double, or
  5254. // long double, remove it.
  5255. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  5256. // Only remove standard FloatCasts, leaving other casts inplace
  5257. if (Cast->getCastKind() == CK_FloatingCast) {
  5258. Expr *CastArg = Cast->getSubExpr();
  5259. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  5260. assert(
  5261. (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  5262. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
  5263. Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
  5264. "promotion from float to either float, double, or long double is "
  5265. "the only expected cast here");
  5266. Cast->setSubExpr(nullptr);
  5267. TheCall->setArg(NumArgs-1, CastArg);
  5268. }
  5269. }
  5270. }
  5271. return false;
  5272. }
  5273. // Customized Sema Checking for VSX builtins that have the following signature:
  5274. // vector [...] builtinName(vector [...], vector [...], const int);
  5275. // Which takes the same type of vectors (any legal vector type) for the first
  5276. // two arguments and takes compile time constant for the third argument.
  5277. // Example builtins are :
  5278. // vector double vec_xxpermdi(vector double, vector double, int);
  5279. // vector short vec_xxsldwi(vector short, vector short, int);
  5280. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  5281. unsigned ExpectedNumArgs = 3;
  5282. if (TheCall->getNumArgs() < ExpectedNumArgs)
  5283. return Diag(TheCall->getEndLoc(),
  5284. diag::err_typecheck_call_too_few_args_at_least)
  5285. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5286. << TheCall->getSourceRange();
  5287. if (TheCall->getNumArgs() > ExpectedNumArgs)
  5288. return Diag(TheCall->getEndLoc(),
  5289. diag::err_typecheck_call_too_many_args_at_most)
  5290. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5291. << TheCall->getSourceRange();
  5292. // Check the third argument is a compile time constant
  5293. llvm::APSInt Value;
  5294. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  5295. return Diag(TheCall->getBeginLoc(),
  5296. diag::err_vsx_builtin_nonconstant_argument)
  5297. << 3 /* argument index */ << TheCall->getDirectCallee()
  5298. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5299. TheCall->getArg(2)->getEndLoc());
  5300. QualType Arg1Ty = TheCall->getArg(0)->getType();
  5301. QualType Arg2Ty = TheCall->getArg(1)->getType();
  5302. // Check the type of argument 1 and argument 2 are vectors.
  5303. SourceLocation BuiltinLoc = TheCall->getBeginLoc();
  5304. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  5305. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  5306. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  5307. << TheCall->getDirectCallee()
  5308. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5309. TheCall->getArg(1)->getEndLoc());
  5310. }
  5311. // Check the first two arguments are the same type.
  5312. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  5313. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  5314. << TheCall->getDirectCallee()
  5315. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5316. TheCall->getArg(1)->getEndLoc());
  5317. }
  5318. // When default clang type checking is turned off and the customized type
  5319. // checking is used, the returning type of the function must be explicitly
  5320. // set. Otherwise it is _Bool by default.
  5321. TheCall->setType(Arg1Ty);
  5322. return false;
  5323. }
  5324. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  5325. // This is declared to take (...), so we have to check everything.
  5326. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  5327. if (TheCall->getNumArgs() < 2)
  5328. return ExprError(Diag(TheCall->getEndLoc(),
  5329. diag::err_typecheck_call_too_few_args_at_least)
  5330. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5331. << TheCall->getSourceRange());
  5332. // Determine which of the following types of shufflevector we're checking:
  5333. // 1) unary, vector mask: (lhs, mask)
  5334. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  5335. QualType resType = TheCall->getArg(0)->getType();
  5336. unsigned numElements = 0;
  5337. if (!TheCall->getArg(0)->isTypeDependent() &&
  5338. !TheCall->getArg(1)->isTypeDependent()) {
  5339. QualType LHSType = TheCall->getArg(0)->getType();
  5340. QualType RHSType = TheCall->getArg(1)->getType();
  5341. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  5342. return ExprError(
  5343. Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
  5344. << TheCall->getDirectCallee()
  5345. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5346. TheCall->getArg(1)->getEndLoc()));
  5347. numElements = LHSType->getAs<VectorType>()->getNumElements();
  5348. unsigned numResElements = TheCall->getNumArgs() - 2;
  5349. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  5350. // with mask. If so, verify that RHS is an integer vector type with the
  5351. // same number of elts as lhs.
  5352. if (TheCall->getNumArgs() == 2) {
  5353. if (!RHSType->hasIntegerRepresentation() ||
  5354. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  5355. return ExprError(Diag(TheCall->getBeginLoc(),
  5356. diag::err_vec_builtin_incompatible_vector)
  5357. << TheCall->getDirectCallee()
  5358. << SourceRange(TheCall->getArg(1)->getBeginLoc(),
  5359. TheCall->getArg(1)->getEndLoc()));
  5360. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  5361. return ExprError(Diag(TheCall->getBeginLoc(),
  5362. diag::err_vec_builtin_incompatible_vector)
  5363. << TheCall->getDirectCallee()
  5364. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5365. TheCall->getArg(1)->getEndLoc()));
  5366. } else if (numElements != numResElements) {
  5367. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  5368. resType = Context.getVectorType(eltType, numResElements,
  5369. VectorType::GenericVector);
  5370. }
  5371. }
  5372. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  5373. if (TheCall->getArg(i)->isTypeDependent() ||
  5374. TheCall->getArg(i)->isValueDependent())
  5375. continue;
  5376. llvm::APSInt Result(32);
  5377. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  5378. return ExprError(Diag(TheCall->getBeginLoc(),
  5379. diag::err_shufflevector_nonconstant_argument)
  5380. << TheCall->getArg(i)->getSourceRange());
  5381. // Allow -1 which will be translated to undef in the IR.
  5382. if (Result.isSigned() && Result.isAllOnesValue())
  5383. continue;
  5384. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  5385. return ExprError(Diag(TheCall->getBeginLoc(),
  5386. diag::err_shufflevector_argument_too_large)
  5387. << TheCall->getArg(i)->getSourceRange());
  5388. }
  5389. SmallVector<Expr*, 32> exprs;
  5390. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  5391. exprs.push_back(TheCall->getArg(i));
  5392. TheCall->setArg(i, nullptr);
  5393. }
  5394. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  5395. TheCall->getCallee()->getBeginLoc(),
  5396. TheCall->getRParenLoc());
  5397. }
  5398. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  5399. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  5400. SourceLocation BuiltinLoc,
  5401. SourceLocation RParenLoc) {
  5402. ExprValueKind VK = VK_RValue;
  5403. ExprObjectKind OK = OK_Ordinary;
  5404. QualType DstTy = TInfo->getType();
  5405. QualType SrcTy = E->getType();
  5406. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  5407. return ExprError(Diag(BuiltinLoc,
  5408. diag::err_convertvector_non_vector)
  5409. << E->getSourceRange());
  5410. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  5411. return ExprError(Diag(BuiltinLoc,
  5412. diag::err_convertvector_non_vector_type));
  5413. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  5414. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  5415. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  5416. if (SrcElts != DstElts)
  5417. return ExprError(Diag(BuiltinLoc,
  5418. diag::err_convertvector_incompatible_vector)
  5419. << E->getSourceRange());
  5420. }
  5421. return new (Context)
  5422. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5423. }
  5424. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  5425. // This is declared to take (const void*, ...) and can take two
  5426. // optional constant int args.
  5427. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  5428. unsigned NumArgs = TheCall->getNumArgs();
  5429. if (NumArgs > 3)
  5430. return Diag(TheCall->getEndLoc(),
  5431. diag::err_typecheck_call_too_many_args_at_most)
  5432. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5433. // Argument 0 is checked for us and the remaining arguments must be
  5434. // constant integers.
  5435. for (unsigned i = 1; i != NumArgs; ++i)
  5436. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  5437. return true;
  5438. return false;
  5439. }
  5440. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  5441. // __assume does not evaluate its arguments, and should warn if its argument
  5442. // has side effects.
  5443. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  5444. Expr *Arg = TheCall->getArg(0);
  5445. if (Arg->isInstantiationDependent()) return false;
  5446. if (Arg->HasSideEffects(Context))
  5447. Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
  5448. << Arg->getSourceRange()
  5449. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  5450. return false;
  5451. }
  5452. /// Handle __builtin_alloca_with_align. This is declared
  5453. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  5454. /// than 8.
  5455. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  5456. // The alignment must be a constant integer.
  5457. Expr *Arg = TheCall->getArg(1);
  5458. // We can't check the value of a dependent argument.
  5459. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5460. if (const auto *UE =
  5461. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  5462. if (UE->getKind() == UETT_AlignOf ||
  5463. UE->getKind() == UETT_PreferredAlignOf)
  5464. Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
  5465. << Arg->getSourceRange();
  5466. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  5467. if (!Result.isPowerOf2())
  5468. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5469. << Arg->getSourceRange();
  5470. if (Result < Context.getCharWidth())
  5471. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
  5472. << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
  5473. if (Result > std::numeric_limits<int32_t>::max())
  5474. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
  5475. << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
  5476. }
  5477. return false;
  5478. }
  5479. /// Handle __builtin_assume_aligned. This is declared
  5480. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  5481. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  5482. unsigned NumArgs = TheCall->getNumArgs();
  5483. if (NumArgs > 3)
  5484. return Diag(TheCall->getEndLoc(),
  5485. diag::err_typecheck_call_too_many_args_at_most)
  5486. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5487. // The alignment must be a constant integer.
  5488. Expr *Arg = TheCall->getArg(1);
  5489. // We can't check the value of a dependent argument.
  5490. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5491. llvm::APSInt Result;
  5492. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5493. return true;
  5494. if (!Result.isPowerOf2())
  5495. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5496. << Arg->getSourceRange();
  5497. }
  5498. if (NumArgs > 2) {
  5499. ExprResult Arg(TheCall->getArg(2));
  5500. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  5501. Context.getSizeType(), false);
  5502. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5503. if (Arg.isInvalid()) return true;
  5504. TheCall->setArg(2, Arg.get());
  5505. }
  5506. return false;
  5507. }
  5508. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  5509. unsigned BuiltinID =
  5510. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  5511. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  5512. unsigned NumArgs = TheCall->getNumArgs();
  5513. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  5514. if (NumArgs < NumRequiredArgs) {
  5515. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5516. << 0 /* function call */ << NumRequiredArgs << NumArgs
  5517. << TheCall->getSourceRange();
  5518. }
  5519. if (NumArgs >= NumRequiredArgs + 0x100) {
  5520. return Diag(TheCall->getEndLoc(),
  5521. diag::err_typecheck_call_too_many_args_at_most)
  5522. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  5523. << TheCall->getSourceRange();
  5524. }
  5525. unsigned i = 0;
  5526. // For formatting call, check buffer arg.
  5527. if (!IsSizeCall) {
  5528. ExprResult Arg(TheCall->getArg(i));
  5529. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5530. Context, Context.VoidPtrTy, false);
  5531. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5532. if (Arg.isInvalid())
  5533. return true;
  5534. TheCall->setArg(i, Arg.get());
  5535. i++;
  5536. }
  5537. // Check string literal arg.
  5538. unsigned FormatIdx = i;
  5539. {
  5540. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  5541. if (Arg.isInvalid())
  5542. return true;
  5543. TheCall->setArg(i, Arg.get());
  5544. i++;
  5545. }
  5546. // Make sure variadic args are scalar.
  5547. unsigned FirstDataArg = i;
  5548. while (i < NumArgs) {
  5549. ExprResult Arg = DefaultVariadicArgumentPromotion(
  5550. TheCall->getArg(i), VariadicFunction, nullptr);
  5551. if (Arg.isInvalid())
  5552. return true;
  5553. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  5554. if (ArgSize.getQuantity() >= 0x100) {
  5555. return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
  5556. << i << (int)ArgSize.getQuantity() << 0xff
  5557. << TheCall->getSourceRange();
  5558. }
  5559. TheCall->setArg(i, Arg.get());
  5560. i++;
  5561. }
  5562. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  5563. // call to avoid duplicate diagnostics.
  5564. if (!IsSizeCall) {
  5565. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  5566. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  5567. bool Success = CheckFormatArguments(
  5568. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  5569. VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
  5570. CheckedVarArgs);
  5571. if (!Success)
  5572. return true;
  5573. }
  5574. if (IsSizeCall) {
  5575. TheCall->setType(Context.getSizeType());
  5576. } else {
  5577. TheCall->setType(Context.VoidPtrTy);
  5578. }
  5579. return false;
  5580. }
  5581. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  5582. /// TheCall is a constant expression.
  5583. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  5584. llvm::APSInt &Result) {
  5585. Expr *Arg = TheCall->getArg(ArgNum);
  5586. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5587. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  5588. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  5589. if (!Arg->isIntegerConstantExpr(Result, Context))
  5590. return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
  5591. << FDecl->getDeclName() << Arg->getSourceRange();
  5592. return false;
  5593. }
  5594. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  5595. /// TheCall is a constant expression in the range [Low, High].
  5596. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  5597. int Low, int High, bool RangeIsError) {
  5598. if (isConstantEvaluated())
  5599. return false;
  5600. llvm::APSInt Result;
  5601. // We can't check the value of a dependent argument.
  5602. Expr *Arg = TheCall->getArg(ArgNum);
  5603. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5604. return false;
  5605. // Check constant-ness first.
  5606. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5607. return true;
  5608. if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
  5609. if (RangeIsError)
  5610. return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
  5611. << Result.toString(10) << Low << High << Arg->getSourceRange();
  5612. else
  5613. // Defer the warning until we know if the code will be emitted so that
  5614. // dead code can ignore this.
  5615. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  5616. PDiag(diag::warn_argument_invalid_range)
  5617. << Result.toString(10) << Low << High
  5618. << Arg->getSourceRange());
  5619. }
  5620. return false;
  5621. }
  5622. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  5623. /// TheCall is a constant expression is a multiple of Num..
  5624. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  5625. unsigned Num) {
  5626. llvm::APSInt Result;
  5627. // We can't check the value of a dependent argument.
  5628. Expr *Arg = TheCall->getArg(ArgNum);
  5629. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5630. return false;
  5631. // Check constant-ness first.
  5632. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5633. return true;
  5634. if (Result.getSExtValue() % Num != 0)
  5635. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
  5636. << Num << Arg->getSourceRange();
  5637. return false;
  5638. }
  5639. /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
  5640. bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
  5641. if (BuiltinID == AArch64::BI__builtin_arm_irg) {
  5642. if (checkArgCount(*this, TheCall, 2))
  5643. return true;
  5644. Expr *Arg0 = TheCall->getArg(0);
  5645. Expr *Arg1 = TheCall->getArg(1);
  5646. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5647. if (FirstArg.isInvalid())
  5648. return true;
  5649. QualType FirstArgType = FirstArg.get()->getType();
  5650. if (!FirstArgType->isAnyPointerType())
  5651. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5652. << "first" << FirstArgType << Arg0->getSourceRange();
  5653. TheCall->setArg(0, FirstArg.get());
  5654. ExprResult SecArg = DefaultLvalueConversion(Arg1);
  5655. if (SecArg.isInvalid())
  5656. return true;
  5657. QualType SecArgType = SecArg.get()->getType();
  5658. if (!SecArgType->isIntegerType())
  5659. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5660. << "second" << SecArgType << Arg1->getSourceRange();
  5661. // Derive the return type from the pointer argument.
  5662. TheCall->setType(FirstArgType);
  5663. return false;
  5664. }
  5665. if (BuiltinID == AArch64::BI__builtin_arm_addg) {
  5666. if (checkArgCount(*this, TheCall, 2))
  5667. return true;
  5668. Expr *Arg0 = TheCall->getArg(0);
  5669. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5670. if (FirstArg.isInvalid())
  5671. return true;
  5672. QualType FirstArgType = FirstArg.get()->getType();
  5673. if (!FirstArgType->isAnyPointerType())
  5674. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5675. << "first" << FirstArgType << Arg0->getSourceRange();
  5676. TheCall->setArg(0, FirstArg.get());
  5677. // Derive the return type from the pointer argument.
  5678. TheCall->setType(FirstArgType);
  5679. // Second arg must be an constant in range [0,15]
  5680. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5681. }
  5682. if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
  5683. if (checkArgCount(*this, TheCall, 2))
  5684. return true;
  5685. Expr *Arg0 = TheCall->getArg(0);
  5686. Expr *Arg1 = TheCall->getArg(1);
  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. QualType SecArgType = Arg1->getType();
  5695. if (!SecArgType->isIntegerType())
  5696. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5697. << "second" << SecArgType << Arg1->getSourceRange();
  5698. TheCall->setType(Context.IntTy);
  5699. return false;
  5700. }
  5701. if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
  5702. BuiltinID == AArch64::BI__builtin_arm_stg) {
  5703. if (checkArgCount(*this, TheCall, 1))
  5704. return true;
  5705. Expr *Arg0 = TheCall->getArg(0);
  5706. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5707. if (FirstArg.isInvalid())
  5708. return true;
  5709. QualType FirstArgType = FirstArg.get()->getType();
  5710. if (!FirstArgType->isAnyPointerType())
  5711. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5712. << "first" << FirstArgType << Arg0->getSourceRange();
  5713. TheCall->setArg(0, FirstArg.get());
  5714. // Derive the return type from the pointer argument.
  5715. if (BuiltinID == AArch64::BI__builtin_arm_ldg)
  5716. TheCall->setType(FirstArgType);
  5717. return false;
  5718. }
  5719. if (BuiltinID == AArch64::BI__builtin_arm_subp) {
  5720. Expr *ArgA = TheCall->getArg(0);
  5721. Expr *ArgB = TheCall->getArg(1);
  5722. ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
  5723. ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
  5724. if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
  5725. return true;
  5726. QualType ArgTypeA = ArgExprA.get()->getType();
  5727. QualType ArgTypeB = ArgExprB.get()->getType();
  5728. auto isNull = [&] (Expr *E) -> bool {
  5729. return E->isNullPointerConstant(
  5730. Context, Expr::NPC_ValueDependentIsNotNull); };
  5731. // argument should be either a pointer or null
  5732. if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
  5733. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5734. << "first" << ArgTypeA << ArgA->getSourceRange();
  5735. if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
  5736. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5737. << "second" << ArgTypeB << ArgB->getSourceRange();
  5738. // Ensure Pointee types are compatible
  5739. if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
  5740. ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
  5741. QualType pointeeA = ArgTypeA->getPointeeType();
  5742. QualType pointeeB = ArgTypeB->getPointeeType();
  5743. if (!Context.typesAreCompatible(
  5744. Context.getCanonicalType(pointeeA).getUnqualifiedType(),
  5745. Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
  5746. return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
  5747. << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
  5748. << ArgB->getSourceRange();
  5749. }
  5750. }
  5751. // at least one argument should be pointer type
  5752. if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
  5753. return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
  5754. << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
  5755. if (isNull(ArgA)) // adopt type of the other pointer
  5756. ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
  5757. if (isNull(ArgB))
  5758. ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
  5759. TheCall->setArg(0, ArgExprA.get());
  5760. TheCall->setArg(1, ArgExprB.get());
  5761. TheCall->setType(Context.LongLongTy);
  5762. return false;
  5763. }
  5764. assert(false && "Unhandled ARM MTE intrinsic");
  5765. return true;
  5766. }
  5767. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  5768. /// TheCall is an ARM/AArch64 special register string literal.
  5769. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  5770. int ArgNum, unsigned ExpectedFieldNum,
  5771. bool AllowName) {
  5772. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  5773. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  5774. BuiltinID == ARM::BI__builtin_arm_rsr ||
  5775. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  5776. BuiltinID == ARM::BI__builtin_arm_wsr ||
  5777. BuiltinID == ARM::BI__builtin_arm_wsrp;
  5778. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  5779. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  5780. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  5781. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  5782. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  5783. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  5784. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  5785. // We can't check the value of a dependent argument.
  5786. Expr *Arg = TheCall->getArg(ArgNum);
  5787. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5788. return false;
  5789. // Check if the argument is a string literal.
  5790. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  5791. return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  5792. << Arg->getSourceRange();
  5793. // Check the type of special register given.
  5794. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  5795. SmallVector<StringRef, 6> Fields;
  5796. Reg.split(Fields, ":");
  5797. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  5798. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5799. << Arg->getSourceRange();
  5800. // If the string is the name of a register then we cannot check that it is
  5801. // valid here but if the string is of one the forms described in ACLE then we
  5802. // can check that the supplied fields are integers and within the valid
  5803. // ranges.
  5804. if (Fields.size() > 1) {
  5805. bool FiveFields = Fields.size() == 5;
  5806. bool ValidString = true;
  5807. if (IsARMBuiltin) {
  5808. ValidString &= Fields[0].startswith_lower("cp") ||
  5809. Fields[0].startswith_lower("p");
  5810. if (ValidString)
  5811. Fields[0] =
  5812. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  5813. ValidString &= Fields[2].startswith_lower("c");
  5814. if (ValidString)
  5815. Fields[2] = Fields[2].drop_front(1);
  5816. if (FiveFields) {
  5817. ValidString &= Fields[3].startswith_lower("c");
  5818. if (ValidString)
  5819. Fields[3] = Fields[3].drop_front(1);
  5820. }
  5821. }
  5822. SmallVector<int, 5> Ranges;
  5823. if (FiveFields)
  5824. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  5825. else
  5826. Ranges.append({15, 7, 15});
  5827. for (unsigned i=0; i<Fields.size(); ++i) {
  5828. int IntField;
  5829. ValidString &= !Fields[i].getAsInteger(10, IntField);
  5830. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  5831. }
  5832. if (!ValidString)
  5833. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5834. << Arg->getSourceRange();
  5835. } else if (IsAArch64Builtin && Fields.size() == 1) {
  5836. // If the register name is one of those that appear in the condition below
  5837. // and the special register builtin being used is one of the write builtins,
  5838. // then we require that the argument provided for writing to the register
  5839. // is an integer constant expression. This is because it will be lowered to
  5840. // an MSR (immediate) instruction, so we need to know the immediate at
  5841. // compile time.
  5842. if (TheCall->getNumArgs() != 2)
  5843. return false;
  5844. std::string RegLower = Reg.lower();
  5845. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  5846. RegLower != "pan" && RegLower != "uao")
  5847. return false;
  5848. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5849. }
  5850. return false;
  5851. }
  5852. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  5853. /// This checks that the target supports __builtin_longjmp and
  5854. /// that val is a constant 1.
  5855. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  5856. if (!Context.getTargetInfo().hasSjLjLowering())
  5857. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
  5858. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5859. Expr *Arg = TheCall->getArg(1);
  5860. llvm::APSInt Result;
  5861. // TODO: This is less than ideal. Overload this to take a value.
  5862. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5863. return true;
  5864. if (Result != 1)
  5865. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
  5866. << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
  5867. return false;
  5868. }
  5869. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  5870. /// This checks that the target supports __builtin_setjmp.
  5871. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  5872. if (!Context.getTargetInfo().hasSjLjLowering())
  5873. return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
  5874. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5875. return false;
  5876. }
  5877. namespace {
  5878. class UncoveredArgHandler {
  5879. enum { Unknown = -1, AllCovered = -2 };
  5880. signed FirstUncoveredArg = Unknown;
  5881. SmallVector<const Expr *, 4> DiagnosticExprs;
  5882. public:
  5883. UncoveredArgHandler() = default;
  5884. bool hasUncoveredArg() const {
  5885. return (FirstUncoveredArg >= 0);
  5886. }
  5887. unsigned getUncoveredArg() const {
  5888. assert(hasUncoveredArg() && "no uncovered argument");
  5889. return FirstUncoveredArg;
  5890. }
  5891. void setAllCovered() {
  5892. // A string has been found with all arguments covered, so clear out
  5893. // the diagnostics.
  5894. DiagnosticExprs.clear();
  5895. FirstUncoveredArg = AllCovered;
  5896. }
  5897. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  5898. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  5899. // Don't update if a previous string covers all arguments.
  5900. if (FirstUncoveredArg == AllCovered)
  5901. return;
  5902. // UncoveredArgHandler tracks the highest uncovered argument index
  5903. // and with it all the strings that match this index.
  5904. if (NewFirstUncoveredArg == FirstUncoveredArg)
  5905. DiagnosticExprs.push_back(StrExpr);
  5906. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  5907. DiagnosticExprs.clear();
  5908. DiagnosticExprs.push_back(StrExpr);
  5909. FirstUncoveredArg = NewFirstUncoveredArg;
  5910. }
  5911. }
  5912. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  5913. };
  5914. enum StringLiteralCheckType {
  5915. SLCT_NotALiteral,
  5916. SLCT_UncheckedLiteral,
  5917. SLCT_CheckedLiteral
  5918. };
  5919. } // namespace
  5920. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  5921. BinaryOperatorKind BinOpKind,
  5922. bool AddendIsRight) {
  5923. unsigned BitWidth = Offset.getBitWidth();
  5924. unsigned AddendBitWidth = Addend.getBitWidth();
  5925. // There might be negative interim results.
  5926. if (Addend.isUnsigned()) {
  5927. Addend = Addend.zext(++AddendBitWidth);
  5928. Addend.setIsSigned(true);
  5929. }
  5930. // Adjust the bit width of the APSInts.
  5931. if (AddendBitWidth > BitWidth) {
  5932. Offset = Offset.sext(AddendBitWidth);
  5933. BitWidth = AddendBitWidth;
  5934. } else if (BitWidth > AddendBitWidth) {
  5935. Addend = Addend.sext(BitWidth);
  5936. }
  5937. bool Ov = false;
  5938. llvm::APSInt ResOffset = Offset;
  5939. if (BinOpKind == BO_Add)
  5940. ResOffset = Offset.sadd_ov(Addend, Ov);
  5941. else {
  5942. assert(AddendIsRight && BinOpKind == BO_Sub &&
  5943. "operator must be add or sub with addend on the right");
  5944. ResOffset = Offset.ssub_ov(Addend, Ov);
  5945. }
  5946. // We add an offset to a pointer here so we should support an offset as big as
  5947. // possible.
  5948. if (Ov) {
  5949. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  5950. "index (intermediate) result too big");
  5951. Offset = Offset.sext(2 * BitWidth);
  5952. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  5953. return;
  5954. }
  5955. Offset = ResOffset;
  5956. }
  5957. namespace {
  5958. // This is a wrapper class around StringLiteral to support offsetted string
  5959. // literals as format strings. It takes the offset into account when returning
  5960. // the string and its length or the source locations to display notes correctly.
  5961. class FormatStringLiteral {
  5962. const StringLiteral *FExpr;
  5963. int64_t Offset;
  5964. public:
  5965. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  5966. : FExpr(fexpr), Offset(Offset) {}
  5967. StringRef getString() const {
  5968. return FExpr->getString().drop_front(Offset);
  5969. }
  5970. unsigned getByteLength() const {
  5971. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  5972. }
  5973. unsigned getLength() const { return FExpr->getLength() - Offset; }
  5974. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  5975. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  5976. QualType getType() const { return FExpr->getType(); }
  5977. bool isAscii() const { return FExpr->isAscii(); }
  5978. bool isWide() const { return FExpr->isWide(); }
  5979. bool isUTF8() const { return FExpr->isUTF8(); }
  5980. bool isUTF16() const { return FExpr->isUTF16(); }
  5981. bool isUTF32() const { return FExpr->isUTF32(); }
  5982. bool isPascal() const { return FExpr->isPascal(); }
  5983. SourceLocation getLocationOfByte(
  5984. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  5985. const TargetInfo &Target, unsigned *StartToken = nullptr,
  5986. unsigned *StartTokenByteOffset = nullptr) const {
  5987. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  5988. StartToken, StartTokenByteOffset);
  5989. }
  5990. SourceLocation getBeginLoc() const LLVM_READONLY {
  5991. return FExpr->getBeginLoc().getLocWithOffset(Offset);
  5992. }
  5993. SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
  5994. };
  5995. } // namespace
  5996. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  5997. const Expr *OrigFormatExpr,
  5998. ArrayRef<const Expr *> Args,
  5999. bool HasVAListArg, unsigned format_idx,
  6000. unsigned firstDataArg,
  6001. Sema::FormatStringType Type,
  6002. bool inFunctionCall,
  6003. Sema::VariadicCallType CallType,
  6004. llvm::SmallBitVector &CheckedVarArgs,
  6005. UncoveredArgHandler &UncoveredArg,
  6006. bool IgnoreStringsWithoutSpecifiers);
  6007. // Determine if an expression is a string literal or constant string.
  6008. // If this function returns false on the arguments to a function expecting a
  6009. // format string, we will usually need to emit a warning.
  6010. // True string literals are then checked by CheckFormatString.
  6011. static StringLiteralCheckType
  6012. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  6013. bool HasVAListArg, unsigned format_idx,
  6014. unsigned firstDataArg, Sema::FormatStringType Type,
  6015. Sema::VariadicCallType CallType, bool InFunctionCall,
  6016. llvm::SmallBitVector &CheckedVarArgs,
  6017. UncoveredArgHandler &UncoveredArg,
  6018. llvm::APSInt Offset,
  6019. bool IgnoreStringsWithoutSpecifiers = false) {
  6020. if (S.isConstantEvaluated())
  6021. return SLCT_NotALiteral;
  6022. tryAgain:
  6023. assert(Offset.isSigned() && "invalid offset");
  6024. if (E->isTypeDependent() || E->isValueDependent())
  6025. return SLCT_NotALiteral;
  6026. E = E->IgnoreParenCasts();
  6027. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  6028. // Technically -Wformat-nonliteral does not warn about this case.
  6029. // The behavior of printf and friends in this case is implementation
  6030. // dependent. Ideally if the format string cannot be null then
  6031. // it should have a 'nonnull' attribute in the function prototype.
  6032. return SLCT_UncheckedLiteral;
  6033. switch (E->getStmtClass()) {
  6034. case Stmt::BinaryConditionalOperatorClass:
  6035. case Stmt::ConditionalOperatorClass: {
  6036. // The expression is a literal if both sub-expressions were, and it was
  6037. // completely checked only if both sub-expressions were checked.
  6038. const AbstractConditionalOperator *C =
  6039. cast<AbstractConditionalOperator>(E);
  6040. // Determine whether it is necessary to check both sub-expressions, for
  6041. // example, because the condition expression is a constant that can be
  6042. // evaluated at compile time.
  6043. bool CheckLeft = true, CheckRight = true;
  6044. bool Cond;
  6045. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
  6046. S.isConstantEvaluated())) {
  6047. if (Cond)
  6048. CheckRight = false;
  6049. else
  6050. CheckLeft = false;
  6051. }
  6052. // We need to maintain the offsets for the right and the left hand side
  6053. // separately to check if every possible indexed expression is a valid
  6054. // string literal. They might have different offsets for different string
  6055. // literals in the end.
  6056. StringLiteralCheckType Left;
  6057. if (!CheckLeft)
  6058. Left = SLCT_UncheckedLiteral;
  6059. else {
  6060. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  6061. HasVAListArg, format_idx, firstDataArg,
  6062. Type, CallType, InFunctionCall,
  6063. CheckedVarArgs, UncoveredArg, Offset,
  6064. IgnoreStringsWithoutSpecifiers);
  6065. if (Left == SLCT_NotALiteral || !CheckRight) {
  6066. return Left;
  6067. }
  6068. }
  6069. StringLiteralCheckType Right = checkFormatStringExpr(
  6070. S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
  6071. Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  6072. IgnoreStringsWithoutSpecifiers);
  6073. return (CheckLeft && Left < Right) ? Left : Right;
  6074. }
  6075. case Stmt::ImplicitCastExprClass:
  6076. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  6077. goto tryAgain;
  6078. case Stmt::OpaqueValueExprClass:
  6079. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  6080. E = src;
  6081. goto tryAgain;
  6082. }
  6083. return SLCT_NotALiteral;
  6084. case Stmt::PredefinedExprClass:
  6085. // While __func__, etc., are technically not string literals, they
  6086. // cannot contain format specifiers and thus are not a security
  6087. // liability.
  6088. return SLCT_UncheckedLiteral;
  6089. case Stmt::DeclRefExprClass: {
  6090. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  6091. // As an exception, do not flag errors for variables binding to
  6092. // const string literals.
  6093. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  6094. bool isConstant = false;
  6095. QualType T = DR->getType();
  6096. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  6097. isConstant = AT->getElementType().isConstant(S.Context);
  6098. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  6099. isConstant = T.isConstant(S.Context) &&
  6100. PT->getPointeeType().isConstant(S.Context);
  6101. } else if (T->isObjCObjectPointerType()) {
  6102. // In ObjC, there is usually no "const ObjectPointer" type,
  6103. // so don't check if the pointee type is constant.
  6104. isConstant = T.isConstant(S.Context);
  6105. }
  6106. if (isConstant) {
  6107. if (const Expr *Init = VD->getAnyInitializer()) {
  6108. // Look through initializers like const char c[] = { "foo" }
  6109. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  6110. if (InitList->isStringLiteralInit())
  6111. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  6112. }
  6113. return checkFormatStringExpr(S, Init, Args,
  6114. HasVAListArg, format_idx,
  6115. firstDataArg, Type, CallType,
  6116. /*InFunctionCall*/ false, CheckedVarArgs,
  6117. UncoveredArg, Offset);
  6118. }
  6119. }
  6120. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  6121. // special check to see if the format string is a function parameter
  6122. // of the function calling the printf function. If the function
  6123. // has an attribute indicating it is a printf-like function, then we
  6124. // should suppress warnings concerning non-literals being used in a call
  6125. // to a vprintf function. For example:
  6126. //
  6127. // void
  6128. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  6129. // va_list ap;
  6130. // va_start(ap, fmt);
  6131. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  6132. // ...
  6133. // }
  6134. if (HasVAListArg) {
  6135. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  6136. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  6137. int PVIndex = PV->getFunctionScopeIndex() + 1;
  6138. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  6139. // adjust for implicit parameter
  6140. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  6141. if (MD->isInstance())
  6142. ++PVIndex;
  6143. // We also check if the formats are compatible.
  6144. // We can't pass a 'scanf' string to a 'printf' function.
  6145. if (PVIndex == PVFormat->getFormatIdx() &&
  6146. Type == S.GetFormatStringType(PVFormat))
  6147. return SLCT_UncheckedLiteral;
  6148. }
  6149. }
  6150. }
  6151. }
  6152. }
  6153. return SLCT_NotALiteral;
  6154. }
  6155. case Stmt::CallExprClass:
  6156. case Stmt::CXXMemberCallExprClass: {
  6157. const CallExpr *CE = cast<CallExpr>(E);
  6158. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  6159. bool IsFirst = true;
  6160. StringLiteralCheckType CommonResult;
  6161. for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
  6162. const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
  6163. StringLiteralCheckType Result = checkFormatStringExpr(
  6164. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6165. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  6166. IgnoreStringsWithoutSpecifiers);
  6167. if (IsFirst) {
  6168. CommonResult = Result;
  6169. IsFirst = false;
  6170. }
  6171. }
  6172. if (!IsFirst)
  6173. return CommonResult;
  6174. if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
  6175. unsigned BuiltinID = FD->getBuiltinID();
  6176. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  6177. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  6178. const Expr *Arg = CE->getArg(0);
  6179. return checkFormatStringExpr(S, Arg, Args,
  6180. HasVAListArg, format_idx,
  6181. firstDataArg, Type, CallType,
  6182. InFunctionCall, CheckedVarArgs,
  6183. UncoveredArg, Offset,
  6184. IgnoreStringsWithoutSpecifiers);
  6185. }
  6186. }
  6187. }
  6188. return SLCT_NotALiteral;
  6189. }
  6190. case Stmt::ObjCMessageExprClass: {
  6191. const auto *ME = cast<ObjCMessageExpr>(E);
  6192. if (const auto *MD = ME->getMethodDecl()) {
  6193. if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
  6194. // As a special case heuristic, if we're using the method -[NSBundle
  6195. // localizedStringForKey:value:table:], ignore any key strings that lack
  6196. // format specifiers. The idea is that if the key doesn't have any
  6197. // format specifiers then its probably just a key to map to the
  6198. // localized strings. If it does have format specifiers though, then its
  6199. // likely that the text of the key is the format string in the
  6200. // programmer's language, and should be checked.
  6201. const ObjCInterfaceDecl *IFace;
  6202. if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
  6203. IFace->getIdentifier()->isStr("NSBundle") &&
  6204. MD->getSelector().isKeywordSelector(
  6205. {"localizedStringForKey", "value", "table"})) {
  6206. IgnoreStringsWithoutSpecifiers = true;
  6207. }
  6208. const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
  6209. return checkFormatStringExpr(
  6210. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6211. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
  6212. IgnoreStringsWithoutSpecifiers);
  6213. }
  6214. }
  6215. return SLCT_NotALiteral;
  6216. }
  6217. case Stmt::ObjCStringLiteralClass:
  6218. case Stmt::StringLiteralClass: {
  6219. const StringLiteral *StrE = nullptr;
  6220. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  6221. StrE = ObjCFExpr->getString();
  6222. else
  6223. StrE = cast<StringLiteral>(E);
  6224. if (StrE) {
  6225. if (Offset.isNegative() || Offset > StrE->getLength()) {
  6226. // TODO: It would be better to have an explicit warning for out of
  6227. // bounds literals.
  6228. return SLCT_NotALiteral;
  6229. }
  6230. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  6231. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  6232. firstDataArg, Type, InFunctionCall, CallType,
  6233. CheckedVarArgs, UncoveredArg,
  6234. IgnoreStringsWithoutSpecifiers);
  6235. return SLCT_CheckedLiteral;
  6236. }
  6237. return SLCT_NotALiteral;
  6238. }
  6239. case Stmt::BinaryOperatorClass: {
  6240. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  6241. // A string literal + an int offset is still a string literal.
  6242. if (BinOp->isAdditiveOp()) {
  6243. Expr::EvalResult LResult, RResult;
  6244. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
  6245. LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  6246. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
  6247. RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  6248. if (LIsInt != RIsInt) {
  6249. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  6250. if (LIsInt) {
  6251. if (BinOpKind == BO_Add) {
  6252. sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
  6253. E = BinOp->getRHS();
  6254. goto tryAgain;
  6255. }
  6256. } else {
  6257. sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
  6258. E = BinOp->getLHS();
  6259. goto tryAgain;
  6260. }
  6261. }
  6262. }
  6263. return SLCT_NotALiteral;
  6264. }
  6265. case Stmt::UnaryOperatorClass: {
  6266. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  6267. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  6268. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  6269. Expr::EvalResult IndexResult;
  6270. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
  6271. Expr::SE_NoSideEffects,
  6272. S.isConstantEvaluated())) {
  6273. sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
  6274. /*RHS is int*/ true);
  6275. E = ASE->getBase();
  6276. goto tryAgain;
  6277. }
  6278. }
  6279. return SLCT_NotALiteral;
  6280. }
  6281. default:
  6282. return SLCT_NotALiteral;
  6283. }
  6284. }
  6285. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  6286. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  6287. .Case("scanf", FST_Scanf)
  6288. .Cases("printf", "printf0", FST_Printf)
  6289. .Cases("NSString", "CFString", FST_NSString)
  6290. .Case("strftime", FST_Strftime)
  6291. .Case("strfmon", FST_Strfmon)
  6292. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  6293. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  6294. .Case("os_trace", FST_OSLog)
  6295. .Case("os_log", FST_OSLog)
  6296. .Default(FST_Unknown);
  6297. }
  6298. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  6299. /// functions) for correct use of format strings.
  6300. /// Returns true if a format string has been fully checked.
  6301. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  6302. ArrayRef<const Expr *> Args,
  6303. bool IsCXXMember,
  6304. VariadicCallType CallType,
  6305. SourceLocation Loc, SourceRange Range,
  6306. llvm::SmallBitVector &CheckedVarArgs) {
  6307. FormatStringInfo FSI;
  6308. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  6309. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  6310. FSI.FirstDataArg, GetFormatStringType(Format),
  6311. CallType, Loc, Range, CheckedVarArgs);
  6312. return false;
  6313. }
  6314. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  6315. bool HasVAListArg, unsigned format_idx,
  6316. unsigned firstDataArg, FormatStringType Type,
  6317. VariadicCallType CallType,
  6318. SourceLocation Loc, SourceRange Range,
  6319. llvm::SmallBitVector &CheckedVarArgs) {
  6320. // CHECK: printf/scanf-like function is called with no format string.
  6321. if (format_idx >= Args.size()) {
  6322. Diag(Loc, diag::warn_missing_format_string) << Range;
  6323. return false;
  6324. }
  6325. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  6326. // CHECK: format string is not a string literal.
  6327. //
  6328. // Dynamically generated format strings are difficult to
  6329. // automatically vet at compile time. Requiring that format strings
  6330. // are string literals: (1) permits the checking of format strings by
  6331. // the compiler and thereby (2) can practically remove the source of
  6332. // many format string exploits.
  6333. // Format string can be either ObjC string (e.g. @"%d") or
  6334. // C string (e.g. "%d")
  6335. // ObjC string uses the same format specifiers as C string, so we can use
  6336. // the same format string checking logic for both ObjC and C strings.
  6337. UncoveredArgHandler UncoveredArg;
  6338. StringLiteralCheckType CT =
  6339. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  6340. format_idx, firstDataArg, Type, CallType,
  6341. /*IsFunctionCall*/ true, CheckedVarArgs,
  6342. UncoveredArg,
  6343. /*no string offset*/ llvm::APSInt(64, false) = 0);
  6344. // Generate a diagnostic where an uncovered argument is detected.
  6345. if (UncoveredArg.hasUncoveredArg()) {
  6346. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  6347. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  6348. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  6349. }
  6350. if (CT != SLCT_NotALiteral)
  6351. // Literal format string found, check done!
  6352. return CT == SLCT_CheckedLiteral;
  6353. // Strftime is particular as it always uses a single 'time' argument,
  6354. // so it is safe to pass a non-literal string.
  6355. if (Type == FST_Strftime)
  6356. return false;
  6357. // Do not emit diag when the string param is a macro expansion and the
  6358. // format is either NSString or CFString. This is a hack to prevent
  6359. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  6360. // which are usually used in place of NS and CF string literals.
  6361. SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
  6362. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  6363. return false;
  6364. // If there are no arguments specified, warn with -Wformat-security, otherwise
  6365. // warn only with -Wformat-nonliteral.
  6366. if (Args.size() == firstDataArg) {
  6367. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  6368. << OrigFormatExpr->getSourceRange();
  6369. switch (Type) {
  6370. default:
  6371. break;
  6372. case FST_Kprintf:
  6373. case FST_FreeBSDKPrintf:
  6374. case FST_Printf:
  6375. Diag(FormatLoc, diag::note_format_security_fixit)
  6376. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  6377. break;
  6378. case FST_NSString:
  6379. Diag(FormatLoc, diag::note_format_security_fixit)
  6380. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  6381. break;
  6382. }
  6383. } else {
  6384. Diag(FormatLoc, diag::warn_format_nonliteral)
  6385. << OrigFormatExpr->getSourceRange();
  6386. }
  6387. return false;
  6388. }
  6389. namespace {
  6390. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  6391. protected:
  6392. Sema &S;
  6393. const FormatStringLiteral *FExpr;
  6394. const Expr *OrigFormatExpr;
  6395. const Sema::FormatStringType FSType;
  6396. const unsigned FirstDataArg;
  6397. const unsigned NumDataArgs;
  6398. const char *Beg; // Start of format string.
  6399. const bool HasVAListArg;
  6400. ArrayRef<const Expr *> Args;
  6401. unsigned FormatIdx;
  6402. llvm::SmallBitVector CoveredArgs;
  6403. bool usesPositionalArgs = false;
  6404. bool atFirstArg = true;
  6405. bool inFunctionCall;
  6406. Sema::VariadicCallType CallType;
  6407. llvm::SmallBitVector &CheckedVarArgs;
  6408. UncoveredArgHandler &UncoveredArg;
  6409. public:
  6410. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  6411. const Expr *origFormatExpr,
  6412. const Sema::FormatStringType type, unsigned firstDataArg,
  6413. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  6414. ArrayRef<const Expr *> Args, unsigned formatIdx,
  6415. bool inFunctionCall, Sema::VariadicCallType callType,
  6416. llvm::SmallBitVector &CheckedVarArgs,
  6417. UncoveredArgHandler &UncoveredArg)
  6418. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  6419. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  6420. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  6421. inFunctionCall(inFunctionCall), CallType(callType),
  6422. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  6423. CoveredArgs.resize(numDataArgs);
  6424. CoveredArgs.reset();
  6425. }
  6426. void DoneProcessing();
  6427. void HandleIncompleteSpecifier(const char *startSpecifier,
  6428. unsigned specifierLen) override;
  6429. void HandleInvalidLengthModifier(
  6430. const analyze_format_string::FormatSpecifier &FS,
  6431. const analyze_format_string::ConversionSpecifier &CS,
  6432. const char *startSpecifier, unsigned specifierLen,
  6433. unsigned DiagID);
  6434. void HandleNonStandardLengthModifier(
  6435. const analyze_format_string::FormatSpecifier &FS,
  6436. const char *startSpecifier, unsigned specifierLen);
  6437. void HandleNonStandardConversionSpecifier(
  6438. const analyze_format_string::ConversionSpecifier &CS,
  6439. const char *startSpecifier, unsigned specifierLen);
  6440. void HandlePosition(const char *startPos, unsigned posLen) override;
  6441. void HandleInvalidPosition(const char *startSpecifier,
  6442. unsigned specifierLen,
  6443. analyze_format_string::PositionContext p) override;
  6444. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  6445. void HandleNullChar(const char *nullCharacter) override;
  6446. template <typename Range>
  6447. static void
  6448. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  6449. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  6450. bool IsStringLocation, Range StringRange,
  6451. ArrayRef<FixItHint> Fixit = None);
  6452. protected:
  6453. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  6454. const char *startSpec,
  6455. unsigned specifierLen,
  6456. const char *csStart, unsigned csLen);
  6457. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6458. const char *startSpec,
  6459. unsigned specifierLen);
  6460. SourceRange getFormatStringRange();
  6461. CharSourceRange getSpecifierRange(const char *startSpecifier,
  6462. unsigned specifierLen);
  6463. SourceLocation getLocationOfByte(const char *x);
  6464. const Expr *getDataArg(unsigned i) const;
  6465. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  6466. const analyze_format_string::ConversionSpecifier &CS,
  6467. const char *startSpecifier, unsigned specifierLen,
  6468. unsigned argIndex);
  6469. template <typename Range>
  6470. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  6471. bool IsStringLocation, Range StringRange,
  6472. ArrayRef<FixItHint> Fixit = None);
  6473. };
  6474. } // namespace
  6475. SourceRange CheckFormatHandler::getFormatStringRange() {
  6476. return OrigFormatExpr->getSourceRange();
  6477. }
  6478. CharSourceRange CheckFormatHandler::
  6479. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  6480. SourceLocation Start = getLocationOfByte(startSpecifier);
  6481. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  6482. // Advance the end SourceLocation by one due to half-open ranges.
  6483. End = End.getLocWithOffset(1);
  6484. return CharSourceRange::getCharRange(Start, End);
  6485. }
  6486. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  6487. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  6488. S.getLangOpts(), S.Context.getTargetInfo());
  6489. }
  6490. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  6491. unsigned specifierLen){
  6492. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  6493. getLocationOfByte(startSpecifier),
  6494. /*IsStringLocation*/true,
  6495. getSpecifierRange(startSpecifier, specifierLen));
  6496. }
  6497. void CheckFormatHandler::HandleInvalidLengthModifier(
  6498. const analyze_format_string::FormatSpecifier &FS,
  6499. const analyze_format_string::ConversionSpecifier &CS,
  6500. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  6501. using namespace analyze_format_string;
  6502. const LengthModifier &LM = FS.getLengthModifier();
  6503. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6504. // See if we know how to fix this length modifier.
  6505. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6506. if (FixedLM) {
  6507. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6508. getLocationOfByte(LM.getStart()),
  6509. /*IsStringLocation*/true,
  6510. getSpecifierRange(startSpecifier, specifierLen));
  6511. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6512. << FixedLM->toString()
  6513. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6514. } else {
  6515. FixItHint Hint;
  6516. if (DiagID == diag::warn_format_nonsensical_length)
  6517. Hint = FixItHint::CreateRemoval(LMRange);
  6518. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6519. getLocationOfByte(LM.getStart()),
  6520. /*IsStringLocation*/true,
  6521. getSpecifierRange(startSpecifier, specifierLen),
  6522. Hint);
  6523. }
  6524. }
  6525. void CheckFormatHandler::HandleNonStandardLengthModifier(
  6526. const analyze_format_string::FormatSpecifier &FS,
  6527. const char *startSpecifier, unsigned specifierLen) {
  6528. using namespace analyze_format_string;
  6529. const LengthModifier &LM = FS.getLengthModifier();
  6530. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6531. // See if we know how to fix this length modifier.
  6532. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6533. if (FixedLM) {
  6534. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6535. << LM.toString() << 0,
  6536. getLocationOfByte(LM.getStart()),
  6537. /*IsStringLocation*/true,
  6538. getSpecifierRange(startSpecifier, specifierLen));
  6539. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6540. << FixedLM->toString()
  6541. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6542. } else {
  6543. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6544. << LM.toString() << 0,
  6545. getLocationOfByte(LM.getStart()),
  6546. /*IsStringLocation*/true,
  6547. getSpecifierRange(startSpecifier, specifierLen));
  6548. }
  6549. }
  6550. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  6551. const analyze_format_string::ConversionSpecifier &CS,
  6552. const char *startSpecifier, unsigned specifierLen) {
  6553. using namespace analyze_format_string;
  6554. // See if we know how to fix this conversion specifier.
  6555. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  6556. if (FixedCS) {
  6557. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6558. << CS.toString() << /*conversion specifier*/1,
  6559. getLocationOfByte(CS.getStart()),
  6560. /*IsStringLocation*/true,
  6561. getSpecifierRange(startSpecifier, specifierLen));
  6562. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  6563. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  6564. << FixedCS->toString()
  6565. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  6566. } else {
  6567. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6568. << CS.toString() << /*conversion specifier*/1,
  6569. getLocationOfByte(CS.getStart()),
  6570. /*IsStringLocation*/true,
  6571. getSpecifierRange(startSpecifier, specifierLen));
  6572. }
  6573. }
  6574. void CheckFormatHandler::HandlePosition(const char *startPos,
  6575. unsigned posLen) {
  6576. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  6577. getLocationOfByte(startPos),
  6578. /*IsStringLocation*/true,
  6579. getSpecifierRange(startPos, posLen));
  6580. }
  6581. void
  6582. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  6583. analyze_format_string::PositionContext p) {
  6584. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  6585. << (unsigned) p,
  6586. getLocationOfByte(startPos), /*IsStringLocation*/true,
  6587. getSpecifierRange(startPos, posLen));
  6588. }
  6589. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  6590. unsigned posLen) {
  6591. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  6592. getLocationOfByte(startPos),
  6593. /*IsStringLocation*/true,
  6594. getSpecifierRange(startPos, posLen));
  6595. }
  6596. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  6597. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  6598. // The presence of a null character is likely an error.
  6599. EmitFormatDiagnostic(
  6600. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  6601. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  6602. getFormatStringRange());
  6603. }
  6604. }
  6605. // Note that this may return NULL if there was an error parsing or building
  6606. // one of the argument expressions.
  6607. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  6608. return Args[FirstDataArg + i];
  6609. }
  6610. void CheckFormatHandler::DoneProcessing() {
  6611. // Does the number of data arguments exceed the number of
  6612. // format conversions in the format string?
  6613. if (!HasVAListArg) {
  6614. // Find any arguments that weren't covered.
  6615. CoveredArgs.flip();
  6616. signed notCoveredArg = CoveredArgs.find_first();
  6617. if (notCoveredArg >= 0) {
  6618. assert((unsigned)notCoveredArg < NumDataArgs);
  6619. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  6620. } else {
  6621. UncoveredArg.setAllCovered();
  6622. }
  6623. }
  6624. }
  6625. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  6626. const Expr *ArgExpr) {
  6627. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  6628. "Invalid state");
  6629. if (!ArgExpr)
  6630. return;
  6631. SourceLocation Loc = ArgExpr->getBeginLoc();
  6632. if (S.getSourceManager().isInSystemMacro(Loc))
  6633. return;
  6634. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  6635. for (auto E : DiagnosticExprs)
  6636. PDiag << E->getSourceRange();
  6637. CheckFormatHandler::EmitFormatDiagnostic(
  6638. S, IsFunctionCall, DiagnosticExprs[0],
  6639. PDiag, Loc, /*IsStringLocation*/false,
  6640. DiagnosticExprs[0]->getSourceRange());
  6641. }
  6642. bool
  6643. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  6644. SourceLocation Loc,
  6645. const char *startSpec,
  6646. unsigned specifierLen,
  6647. const char *csStart,
  6648. unsigned csLen) {
  6649. bool keepGoing = true;
  6650. if (argIndex < NumDataArgs) {
  6651. // Consider the argument coverered, even though the specifier doesn't
  6652. // make sense.
  6653. CoveredArgs.set(argIndex);
  6654. }
  6655. else {
  6656. // If argIndex exceeds the number of data arguments we
  6657. // don't issue a warning because that is just a cascade of warnings (and
  6658. // they may have intended '%%' anyway). We don't want to continue processing
  6659. // the format string after this point, however, as we will like just get
  6660. // gibberish when trying to match arguments.
  6661. keepGoing = false;
  6662. }
  6663. StringRef Specifier(csStart, csLen);
  6664. // If the specifier in non-printable, it could be the first byte of a UTF-8
  6665. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  6666. // hex value.
  6667. std::string CodePointStr;
  6668. if (!llvm::sys::locale::isPrint(*csStart)) {
  6669. llvm::UTF32 CodePoint;
  6670. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  6671. const llvm::UTF8 *E =
  6672. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  6673. llvm::ConversionResult Result =
  6674. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  6675. if (Result != llvm::conversionOK) {
  6676. unsigned char FirstChar = *csStart;
  6677. CodePoint = (llvm::UTF32)FirstChar;
  6678. }
  6679. llvm::raw_string_ostream OS(CodePointStr);
  6680. if (CodePoint < 256)
  6681. OS << "\\x" << llvm::format("%02x", CodePoint);
  6682. else if (CodePoint <= 0xFFFF)
  6683. OS << "\\u" << llvm::format("%04x", CodePoint);
  6684. else
  6685. OS << "\\U" << llvm::format("%08x", CodePoint);
  6686. OS.flush();
  6687. Specifier = CodePointStr;
  6688. }
  6689. EmitFormatDiagnostic(
  6690. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  6691. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  6692. return keepGoing;
  6693. }
  6694. void
  6695. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6696. const char *startSpec,
  6697. unsigned specifierLen) {
  6698. EmitFormatDiagnostic(
  6699. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  6700. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  6701. }
  6702. bool
  6703. CheckFormatHandler::CheckNumArgs(
  6704. const analyze_format_string::FormatSpecifier &FS,
  6705. const analyze_format_string::ConversionSpecifier &CS,
  6706. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  6707. if (argIndex >= NumDataArgs) {
  6708. PartialDiagnostic PDiag = FS.usesPositionalArg()
  6709. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  6710. << (argIndex+1) << NumDataArgs)
  6711. : S.PDiag(diag::warn_printf_insufficient_data_args);
  6712. EmitFormatDiagnostic(
  6713. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  6714. getSpecifierRange(startSpecifier, specifierLen));
  6715. // Since more arguments than conversion tokens are given, by extension
  6716. // all arguments are covered, so mark this as so.
  6717. UncoveredArg.setAllCovered();
  6718. return false;
  6719. }
  6720. return true;
  6721. }
  6722. template<typename Range>
  6723. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  6724. SourceLocation Loc,
  6725. bool IsStringLocation,
  6726. Range StringRange,
  6727. ArrayRef<FixItHint> FixIt) {
  6728. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  6729. Loc, IsStringLocation, StringRange, FixIt);
  6730. }
  6731. /// If the format string is not within the function call, emit a note
  6732. /// so that the function call and string are in diagnostic messages.
  6733. ///
  6734. /// \param InFunctionCall if true, the format string is within the function
  6735. /// call and only one diagnostic message will be produced. Otherwise, an
  6736. /// extra note will be emitted pointing to location of the format string.
  6737. ///
  6738. /// \param ArgumentExpr the expression that is passed as the format string
  6739. /// argument in the function call. Used for getting locations when two
  6740. /// diagnostics are emitted.
  6741. ///
  6742. /// \param PDiag the callee should already have provided any strings for the
  6743. /// diagnostic message. This function only adds locations and fixits
  6744. /// to diagnostics.
  6745. ///
  6746. /// \param Loc primary location for diagnostic. If two diagnostics are
  6747. /// required, one will be at Loc and a new SourceLocation will be created for
  6748. /// the other one.
  6749. ///
  6750. /// \param IsStringLocation if true, Loc points to the format string should be
  6751. /// used for the note. Otherwise, Loc points to the argument list and will
  6752. /// be used with PDiag.
  6753. ///
  6754. /// \param StringRange some or all of the string to highlight. This is
  6755. /// templated so it can accept either a CharSourceRange or a SourceRange.
  6756. ///
  6757. /// \param FixIt optional fix it hint for the format string.
  6758. template <typename Range>
  6759. void CheckFormatHandler::EmitFormatDiagnostic(
  6760. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  6761. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  6762. Range StringRange, ArrayRef<FixItHint> FixIt) {
  6763. if (InFunctionCall) {
  6764. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  6765. D << StringRange;
  6766. D << FixIt;
  6767. } else {
  6768. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  6769. << ArgumentExpr->getSourceRange();
  6770. const Sema::SemaDiagnosticBuilder &Note =
  6771. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  6772. diag::note_format_string_defined);
  6773. Note << StringRange;
  6774. Note << FixIt;
  6775. }
  6776. }
  6777. //===--- CHECK: Printf format string checking ------------------------------===//
  6778. namespace {
  6779. class CheckPrintfHandler : public CheckFormatHandler {
  6780. public:
  6781. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  6782. const Expr *origFormatExpr,
  6783. const Sema::FormatStringType type, unsigned firstDataArg,
  6784. unsigned numDataArgs, bool isObjC, const char *beg,
  6785. bool hasVAListArg, ArrayRef<const Expr *> Args,
  6786. unsigned formatIdx, bool inFunctionCall,
  6787. Sema::VariadicCallType CallType,
  6788. llvm::SmallBitVector &CheckedVarArgs,
  6789. UncoveredArgHandler &UncoveredArg)
  6790. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  6791. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  6792. inFunctionCall, CallType, CheckedVarArgs,
  6793. UncoveredArg) {}
  6794. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  6795. /// Returns true if '%@' specifiers are allowed in the format string.
  6796. bool allowsObjCArg() const {
  6797. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  6798. FSType == Sema::FST_OSTrace;
  6799. }
  6800. bool HandleInvalidPrintfConversionSpecifier(
  6801. const analyze_printf::PrintfSpecifier &FS,
  6802. const char *startSpecifier,
  6803. unsigned specifierLen) override;
  6804. void handleInvalidMaskType(StringRef MaskType) override;
  6805. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  6806. const char *startSpecifier,
  6807. unsigned specifierLen) override;
  6808. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  6809. const char *StartSpecifier,
  6810. unsigned SpecifierLen,
  6811. const Expr *E);
  6812. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  6813. const char *startSpecifier, unsigned specifierLen);
  6814. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  6815. const analyze_printf::OptionalAmount &Amt,
  6816. unsigned type,
  6817. const char *startSpecifier, unsigned specifierLen);
  6818. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6819. const analyze_printf::OptionalFlag &flag,
  6820. const char *startSpecifier, unsigned specifierLen);
  6821. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  6822. const analyze_printf::OptionalFlag &ignoredFlag,
  6823. const analyze_printf::OptionalFlag &flag,
  6824. const char *startSpecifier, unsigned specifierLen);
  6825. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  6826. const Expr *E);
  6827. void HandleEmptyObjCModifierFlag(const char *startFlag,
  6828. unsigned flagLen) override;
  6829. void HandleInvalidObjCModifierFlag(const char *startFlag,
  6830. unsigned flagLen) override;
  6831. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  6832. const char *flagsEnd,
  6833. const char *conversionPosition)
  6834. override;
  6835. };
  6836. } // namespace
  6837. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  6838. const analyze_printf::PrintfSpecifier &FS,
  6839. const char *startSpecifier,
  6840. unsigned specifierLen) {
  6841. const analyze_printf::PrintfConversionSpecifier &CS =
  6842. FS.getConversionSpecifier();
  6843. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  6844. getLocationOfByte(CS.getStart()),
  6845. startSpecifier, specifierLen,
  6846. CS.getStart(), CS.getLength());
  6847. }
  6848. void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
  6849. S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
  6850. }
  6851. bool CheckPrintfHandler::HandleAmount(
  6852. const analyze_format_string::OptionalAmount &Amt,
  6853. unsigned k, const char *startSpecifier,
  6854. unsigned specifierLen) {
  6855. if (Amt.hasDataArgument()) {
  6856. if (!HasVAListArg) {
  6857. unsigned argIndex = Amt.getArgIndex();
  6858. if (argIndex >= NumDataArgs) {
  6859. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  6860. << k,
  6861. getLocationOfByte(Amt.getStart()),
  6862. /*IsStringLocation*/true,
  6863. getSpecifierRange(startSpecifier, specifierLen));
  6864. // Don't do any more checking. We will just emit
  6865. // spurious errors.
  6866. return false;
  6867. }
  6868. // Type check the data argument. It should be an 'int'.
  6869. // Although not in conformance with C99, we also allow the argument to be
  6870. // an 'unsigned int' as that is a reasonably safe case. GCC also
  6871. // doesn't emit a warning for that case.
  6872. CoveredArgs.set(argIndex);
  6873. const Expr *Arg = getDataArg(argIndex);
  6874. if (!Arg)
  6875. return false;
  6876. QualType T = Arg->getType();
  6877. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  6878. assert(AT.isValid());
  6879. if (!AT.matchesType(S.Context, T)) {
  6880. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  6881. << k << AT.getRepresentativeTypeName(S.Context)
  6882. << T << Arg->getSourceRange(),
  6883. getLocationOfByte(Amt.getStart()),
  6884. /*IsStringLocation*/true,
  6885. getSpecifierRange(startSpecifier, specifierLen));
  6886. // Don't do any more checking. We will just emit
  6887. // spurious errors.
  6888. return false;
  6889. }
  6890. }
  6891. }
  6892. return true;
  6893. }
  6894. void CheckPrintfHandler::HandleInvalidAmount(
  6895. const analyze_printf::PrintfSpecifier &FS,
  6896. const analyze_printf::OptionalAmount &Amt,
  6897. unsigned type,
  6898. const char *startSpecifier,
  6899. unsigned specifierLen) {
  6900. const analyze_printf::PrintfConversionSpecifier &CS =
  6901. FS.getConversionSpecifier();
  6902. FixItHint fixit =
  6903. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  6904. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  6905. Amt.getConstantLength()))
  6906. : FixItHint();
  6907. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  6908. << type << CS.toString(),
  6909. getLocationOfByte(Amt.getStart()),
  6910. /*IsStringLocation*/true,
  6911. getSpecifierRange(startSpecifier, specifierLen),
  6912. fixit);
  6913. }
  6914. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6915. const analyze_printf::OptionalFlag &flag,
  6916. const char *startSpecifier,
  6917. unsigned specifierLen) {
  6918. // Warn about pointless flag with a fixit removal.
  6919. const analyze_printf::PrintfConversionSpecifier &CS =
  6920. FS.getConversionSpecifier();
  6921. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  6922. << flag.toString() << CS.toString(),
  6923. getLocationOfByte(flag.getPosition()),
  6924. /*IsStringLocation*/true,
  6925. getSpecifierRange(startSpecifier, specifierLen),
  6926. FixItHint::CreateRemoval(
  6927. getSpecifierRange(flag.getPosition(), 1)));
  6928. }
  6929. void CheckPrintfHandler::HandleIgnoredFlag(
  6930. const analyze_printf::PrintfSpecifier &FS,
  6931. const analyze_printf::OptionalFlag &ignoredFlag,
  6932. const analyze_printf::OptionalFlag &flag,
  6933. const char *startSpecifier,
  6934. unsigned specifierLen) {
  6935. // Warn about ignored flag with a fixit removal.
  6936. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  6937. << ignoredFlag.toString() << flag.toString(),
  6938. getLocationOfByte(ignoredFlag.getPosition()),
  6939. /*IsStringLocation*/true,
  6940. getSpecifierRange(startSpecifier, specifierLen),
  6941. FixItHint::CreateRemoval(
  6942. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  6943. }
  6944. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  6945. unsigned flagLen) {
  6946. // Warn about an empty flag.
  6947. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  6948. getLocationOfByte(startFlag),
  6949. /*IsStringLocation*/true,
  6950. getSpecifierRange(startFlag, flagLen));
  6951. }
  6952. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  6953. unsigned flagLen) {
  6954. // Warn about an invalid flag.
  6955. auto Range = getSpecifierRange(startFlag, flagLen);
  6956. StringRef flag(startFlag, flagLen);
  6957. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  6958. getLocationOfByte(startFlag),
  6959. /*IsStringLocation*/true,
  6960. Range, FixItHint::CreateRemoval(Range));
  6961. }
  6962. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  6963. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  6964. // Warn about using '[...]' without a '@' conversion.
  6965. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  6966. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  6967. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  6968. getLocationOfByte(conversionPosition),
  6969. /*IsStringLocation*/true,
  6970. Range, FixItHint::CreateRemoval(Range));
  6971. }
  6972. // Determines if the specified is a C++ class or struct containing
  6973. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  6974. // "c_str()").
  6975. template<typename MemberKind>
  6976. static llvm::SmallPtrSet<MemberKind*, 1>
  6977. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  6978. const RecordType *RT = Ty->getAs<RecordType>();
  6979. llvm::SmallPtrSet<MemberKind*, 1> Results;
  6980. if (!RT)
  6981. return Results;
  6982. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  6983. if (!RD || !RD->getDefinition())
  6984. return Results;
  6985. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  6986. Sema::LookupMemberName);
  6987. R.suppressDiagnostics();
  6988. // We just need to include all members of the right kind turned up by the
  6989. // filter, at this point.
  6990. if (S.LookupQualifiedName(R, RT->getDecl()))
  6991. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  6992. NamedDecl *decl = (*I)->getUnderlyingDecl();
  6993. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  6994. Results.insert(FK);
  6995. }
  6996. return Results;
  6997. }
  6998. /// Check if we could call '.c_str()' on an object.
  6999. ///
  7000. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  7001. /// allow the call, or if it would be ambiguous).
  7002. bool Sema::hasCStrMethod(const Expr *E) {
  7003. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  7004. MethodSet Results =
  7005. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  7006. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  7007. MI != ME; ++MI)
  7008. if ((*MI)->getMinRequiredArguments() == 0)
  7009. return true;
  7010. return false;
  7011. }
  7012. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  7013. // better diagnostic if so. AT is assumed to be valid.
  7014. // Returns true when a c_str() conversion method is found.
  7015. bool CheckPrintfHandler::checkForCStrMembers(
  7016. const analyze_printf::ArgType &AT, const Expr *E) {
  7017. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  7018. MethodSet Results =
  7019. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  7020. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  7021. MI != ME; ++MI) {
  7022. const CXXMethodDecl *Method = *MI;
  7023. if (Method->getMinRequiredArguments() == 0 &&
  7024. AT.matchesType(S.Context, Method->getReturnType())) {
  7025. // FIXME: Suggest parens if the expression needs them.
  7026. SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
  7027. S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
  7028. << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  7029. return true;
  7030. }
  7031. }
  7032. return false;
  7033. }
  7034. bool
  7035. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  7036. &FS,
  7037. const char *startSpecifier,
  7038. unsigned specifierLen) {
  7039. using namespace analyze_format_string;
  7040. using namespace analyze_printf;
  7041. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  7042. if (FS.consumesDataArgument()) {
  7043. if (atFirstArg) {
  7044. atFirstArg = false;
  7045. usesPositionalArgs = FS.usesPositionalArg();
  7046. }
  7047. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7048. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7049. startSpecifier, specifierLen);
  7050. return false;
  7051. }
  7052. }
  7053. // First check if the field width, precision, and conversion specifier
  7054. // have matching data arguments.
  7055. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  7056. startSpecifier, specifierLen)) {
  7057. return false;
  7058. }
  7059. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  7060. startSpecifier, specifierLen)) {
  7061. return false;
  7062. }
  7063. if (!CS.consumesDataArgument()) {
  7064. // FIXME: Technically specifying a precision or field width here
  7065. // makes no sense. Worth issuing a warning at some point.
  7066. return true;
  7067. }
  7068. // Consume the argument.
  7069. unsigned argIndex = FS.getArgIndex();
  7070. if (argIndex < NumDataArgs) {
  7071. // The check to see if the argIndex is valid will come later.
  7072. // We set the bit here because we may exit early from this
  7073. // function if we encounter some other error.
  7074. CoveredArgs.set(argIndex);
  7075. }
  7076. // FreeBSD kernel extensions.
  7077. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  7078. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  7079. // We need at least two arguments.
  7080. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  7081. return false;
  7082. // Claim the second argument.
  7083. CoveredArgs.set(argIndex + 1);
  7084. // Type check the first argument (int for %b, pointer for %D)
  7085. const Expr *Ex = getDataArg(argIndex);
  7086. const analyze_printf::ArgType &AT =
  7087. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  7088. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  7089. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  7090. EmitFormatDiagnostic(
  7091. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7092. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  7093. << false << Ex->getSourceRange(),
  7094. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7095. getSpecifierRange(startSpecifier, specifierLen));
  7096. // Type check the second argument (char * for both %b and %D)
  7097. Ex = getDataArg(argIndex + 1);
  7098. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  7099. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  7100. EmitFormatDiagnostic(
  7101. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7102. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  7103. << false << Ex->getSourceRange(),
  7104. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7105. getSpecifierRange(startSpecifier, specifierLen));
  7106. return true;
  7107. }
  7108. // Check for using an Objective-C specific conversion specifier
  7109. // in a non-ObjC literal.
  7110. if (!allowsObjCArg() && CS.isObjCArg()) {
  7111. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7112. specifierLen);
  7113. }
  7114. // %P can only be used with os_log.
  7115. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  7116. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7117. specifierLen);
  7118. }
  7119. // %n is not allowed with os_log.
  7120. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  7121. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  7122. getLocationOfByte(CS.getStart()),
  7123. /*IsStringLocation*/ false,
  7124. getSpecifierRange(startSpecifier, specifierLen));
  7125. return true;
  7126. }
  7127. // Only scalars are allowed for os_trace.
  7128. if (FSType == Sema::FST_OSTrace &&
  7129. (CS.getKind() == ConversionSpecifier::PArg ||
  7130. CS.getKind() == ConversionSpecifier::sArg ||
  7131. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  7132. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7133. specifierLen);
  7134. }
  7135. // Check for use of public/private annotation outside of os_log().
  7136. if (FSType != Sema::FST_OSLog) {
  7137. if (FS.isPublic().isSet()) {
  7138. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7139. << "public",
  7140. getLocationOfByte(FS.isPublic().getPosition()),
  7141. /*IsStringLocation*/ false,
  7142. getSpecifierRange(startSpecifier, specifierLen));
  7143. }
  7144. if (FS.isPrivate().isSet()) {
  7145. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7146. << "private",
  7147. getLocationOfByte(FS.isPrivate().getPosition()),
  7148. /*IsStringLocation*/ false,
  7149. getSpecifierRange(startSpecifier, specifierLen));
  7150. }
  7151. }
  7152. // Check for invalid use of field width
  7153. if (!FS.hasValidFieldWidth()) {
  7154. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  7155. startSpecifier, specifierLen);
  7156. }
  7157. // Check for invalid use of precision
  7158. if (!FS.hasValidPrecision()) {
  7159. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  7160. startSpecifier, specifierLen);
  7161. }
  7162. // Precision is mandatory for %P specifier.
  7163. if (CS.getKind() == ConversionSpecifier::PArg &&
  7164. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  7165. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  7166. getLocationOfByte(startSpecifier),
  7167. /*IsStringLocation*/ false,
  7168. getSpecifierRange(startSpecifier, specifierLen));
  7169. }
  7170. // Check each flag does not conflict with any other component.
  7171. if (!FS.hasValidThousandsGroupingPrefix())
  7172. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  7173. if (!FS.hasValidLeadingZeros())
  7174. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  7175. if (!FS.hasValidPlusPrefix())
  7176. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  7177. if (!FS.hasValidSpacePrefix())
  7178. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  7179. if (!FS.hasValidAlternativeForm())
  7180. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  7181. if (!FS.hasValidLeftJustified())
  7182. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  7183. // Check that flags are not ignored by another flag
  7184. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  7185. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  7186. startSpecifier, specifierLen);
  7187. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  7188. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  7189. startSpecifier, specifierLen);
  7190. // Check the length modifier is valid with the given conversion specifier.
  7191. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7192. S.getLangOpts()))
  7193. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7194. diag::warn_format_nonsensical_length);
  7195. else if (!FS.hasStandardLengthModifier())
  7196. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7197. else if (!FS.hasStandardLengthConversionCombination())
  7198. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7199. diag::warn_format_non_standard_conversion_spec);
  7200. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7201. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7202. // The remaining checks depend on the data arguments.
  7203. if (HasVAListArg)
  7204. return true;
  7205. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7206. return false;
  7207. const Expr *Arg = getDataArg(argIndex);
  7208. if (!Arg)
  7209. return true;
  7210. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  7211. }
  7212. static bool requiresParensToAddCast(const Expr *E) {
  7213. // FIXME: We should have a general way to reason about operator
  7214. // precedence and whether parens are actually needed here.
  7215. // Take care of a few common cases where they aren't.
  7216. const Expr *Inside = E->IgnoreImpCasts();
  7217. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  7218. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  7219. switch (Inside->getStmtClass()) {
  7220. case Stmt::ArraySubscriptExprClass:
  7221. case Stmt::CallExprClass:
  7222. case Stmt::CharacterLiteralClass:
  7223. case Stmt::CXXBoolLiteralExprClass:
  7224. case Stmt::DeclRefExprClass:
  7225. case Stmt::FloatingLiteralClass:
  7226. case Stmt::IntegerLiteralClass:
  7227. case Stmt::MemberExprClass:
  7228. case Stmt::ObjCArrayLiteralClass:
  7229. case Stmt::ObjCBoolLiteralExprClass:
  7230. case Stmt::ObjCBoxedExprClass:
  7231. case Stmt::ObjCDictionaryLiteralClass:
  7232. case Stmt::ObjCEncodeExprClass:
  7233. case Stmt::ObjCIvarRefExprClass:
  7234. case Stmt::ObjCMessageExprClass:
  7235. case Stmt::ObjCPropertyRefExprClass:
  7236. case Stmt::ObjCStringLiteralClass:
  7237. case Stmt::ObjCSubscriptRefExprClass:
  7238. case Stmt::ParenExprClass:
  7239. case Stmt::StringLiteralClass:
  7240. case Stmt::UnaryOperatorClass:
  7241. return false;
  7242. default:
  7243. return true;
  7244. }
  7245. }
  7246. static std::pair<QualType, StringRef>
  7247. shouldNotPrintDirectly(const ASTContext &Context,
  7248. QualType IntendedTy,
  7249. const Expr *E) {
  7250. // Use a 'while' to peel off layers of typedefs.
  7251. QualType TyTy = IntendedTy;
  7252. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  7253. StringRef Name = UserTy->getDecl()->getName();
  7254. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  7255. .Case("CFIndex", Context.getNSIntegerType())
  7256. .Case("NSInteger", Context.getNSIntegerType())
  7257. .Case("NSUInteger", Context.getNSUIntegerType())
  7258. .Case("SInt32", Context.IntTy)
  7259. .Case("UInt32", Context.UnsignedIntTy)
  7260. .Default(QualType());
  7261. if (!CastTy.isNull())
  7262. return std::make_pair(CastTy, Name);
  7263. TyTy = UserTy->desugar();
  7264. }
  7265. // Strip parens if necessary.
  7266. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  7267. return shouldNotPrintDirectly(Context,
  7268. PE->getSubExpr()->getType(),
  7269. PE->getSubExpr());
  7270. // If this is a conditional expression, then its result type is constructed
  7271. // via usual arithmetic conversions and thus there might be no necessary
  7272. // typedef sugar there. Recurse to operands to check for NSInteger &
  7273. // Co. usage condition.
  7274. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  7275. QualType TrueTy, FalseTy;
  7276. StringRef TrueName, FalseName;
  7277. std::tie(TrueTy, TrueName) =
  7278. shouldNotPrintDirectly(Context,
  7279. CO->getTrueExpr()->getType(),
  7280. CO->getTrueExpr());
  7281. std::tie(FalseTy, FalseName) =
  7282. shouldNotPrintDirectly(Context,
  7283. CO->getFalseExpr()->getType(),
  7284. CO->getFalseExpr());
  7285. if (TrueTy == FalseTy)
  7286. return std::make_pair(TrueTy, TrueName);
  7287. else if (TrueTy.isNull())
  7288. return std::make_pair(FalseTy, FalseName);
  7289. else if (FalseTy.isNull())
  7290. return std::make_pair(TrueTy, TrueName);
  7291. }
  7292. return std::make_pair(QualType(), StringRef());
  7293. }
  7294. /// Return true if \p ICE is an implicit argument promotion of an arithmetic
  7295. /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
  7296. /// type do not count.
  7297. static bool
  7298. isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
  7299. QualType From = ICE->getSubExpr()->getType();
  7300. QualType To = ICE->getType();
  7301. // It's an integer promotion if the destination type is the promoted
  7302. // source type.
  7303. if (ICE->getCastKind() == CK_IntegralCast &&
  7304. From->isPromotableIntegerType() &&
  7305. S.Context.getPromotedIntegerType(From) == To)
  7306. return true;
  7307. // Look through vector types, since we do default argument promotion for
  7308. // those in OpenCL.
  7309. if (const auto *VecTy = From->getAs<ExtVectorType>())
  7310. From = VecTy->getElementType();
  7311. if (const auto *VecTy = To->getAs<ExtVectorType>())
  7312. To = VecTy->getElementType();
  7313. // It's a floating promotion if the source type is a lower rank.
  7314. return ICE->getCastKind() == CK_FloatingCast &&
  7315. S.Context.getFloatingTypeOrder(From, To) < 0;
  7316. }
  7317. bool
  7318. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  7319. const char *StartSpecifier,
  7320. unsigned SpecifierLen,
  7321. const Expr *E) {
  7322. using namespace analyze_format_string;
  7323. using namespace analyze_printf;
  7324. // Now type check the data expression that matches the
  7325. // format specifier.
  7326. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  7327. if (!AT.isValid())
  7328. return true;
  7329. QualType ExprTy = E->getType();
  7330. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  7331. ExprTy = TET->getUnderlyingExpr()->getType();
  7332. }
  7333. const analyze_printf::ArgType::MatchKind Match =
  7334. AT.matchesType(S.Context, ExprTy);
  7335. bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
  7336. if (Match == analyze_printf::ArgType::Match)
  7337. return true;
  7338. // Look through argument promotions for our error message's reported type.
  7339. // This includes the integral and floating promotions, but excludes array
  7340. // and function pointer decay (seeing that an argument intended to be a
  7341. // string has type 'char [6]' is probably more confusing than 'char *') and
  7342. // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
  7343. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  7344. if (isArithmeticArgumentPromotion(S, ICE)) {
  7345. E = ICE->getSubExpr();
  7346. ExprTy = E->getType();
  7347. // Check if we didn't match because of an implicit cast from a 'char'
  7348. // or 'short' to an 'int'. This is done because printf is a varargs
  7349. // function.
  7350. if (ICE->getType() == S.Context.IntTy ||
  7351. ICE->getType() == S.Context.UnsignedIntTy) {
  7352. // All further checking is done on the subexpression.
  7353. if (AT.matchesType(S.Context, ExprTy))
  7354. return true;
  7355. }
  7356. }
  7357. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  7358. // Special case for 'a', which has type 'int' in C.
  7359. // Note, however, that we do /not/ want to treat multibyte constants like
  7360. // 'MooV' as characters! This form is deprecated but still exists.
  7361. if (ExprTy == S.Context.IntTy)
  7362. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  7363. ExprTy = S.Context.CharTy;
  7364. }
  7365. // Look through enums to their underlying type.
  7366. bool IsEnum = false;
  7367. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  7368. ExprTy = EnumTy->getDecl()->getIntegerType();
  7369. IsEnum = true;
  7370. }
  7371. // %C in an Objective-C context prints a unichar, not a wchar_t.
  7372. // If the argument is an integer of some kind, believe the %C and suggest
  7373. // a cast instead of changing the conversion specifier.
  7374. QualType IntendedTy = ExprTy;
  7375. if (isObjCContext() &&
  7376. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  7377. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  7378. !ExprTy->isCharType()) {
  7379. // 'unichar' is defined as a typedef of unsigned short, but we should
  7380. // prefer using the typedef if it is visible.
  7381. IntendedTy = S.Context.UnsignedShortTy;
  7382. // While we are here, check if the value is an IntegerLiteral that happens
  7383. // to be within the valid range.
  7384. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  7385. const llvm::APInt &V = IL->getValue();
  7386. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  7387. return true;
  7388. }
  7389. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
  7390. Sema::LookupOrdinaryName);
  7391. if (S.LookupName(Result, S.getCurScope())) {
  7392. NamedDecl *ND = Result.getFoundDecl();
  7393. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  7394. if (TD->getUnderlyingType() == IntendedTy)
  7395. IntendedTy = S.Context.getTypedefType(TD);
  7396. }
  7397. }
  7398. }
  7399. // Special-case some of Darwin's platform-independence types by suggesting
  7400. // casts to primitive types that are known to be large enough.
  7401. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  7402. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  7403. QualType CastTy;
  7404. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  7405. if (!CastTy.isNull()) {
  7406. // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
  7407. // (long in ASTContext). Only complain to pedants.
  7408. if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
  7409. (AT.isSizeT() || AT.isPtrdiffT()) &&
  7410. AT.matchesType(S.Context, CastTy))
  7411. Pedantic = true;
  7412. IntendedTy = CastTy;
  7413. ShouldNotPrintDirectly = true;
  7414. }
  7415. }
  7416. // We may be able to offer a FixItHint if it is a supported type.
  7417. PrintfSpecifier fixedFS = FS;
  7418. bool Success =
  7419. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  7420. if (Success) {
  7421. // Get the fix string from the fixed format specifier
  7422. SmallString<16> buf;
  7423. llvm::raw_svector_ostream os(buf);
  7424. fixedFS.toString(os);
  7425. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  7426. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  7427. unsigned Diag =
  7428. Pedantic
  7429. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7430. : diag::warn_format_conversion_argument_type_mismatch;
  7431. // In this case, the specifier is wrong and should be changed to match
  7432. // the argument.
  7433. EmitFormatDiagnostic(S.PDiag(Diag)
  7434. << AT.getRepresentativeTypeName(S.Context)
  7435. << IntendedTy << IsEnum << E->getSourceRange(),
  7436. E->getBeginLoc(),
  7437. /*IsStringLocation*/ false, SpecRange,
  7438. FixItHint::CreateReplacement(SpecRange, os.str()));
  7439. } else {
  7440. // The canonical type for formatting this value is different from the
  7441. // actual type of the expression. (This occurs, for example, with Darwin's
  7442. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  7443. // should be printed as 'long' for 64-bit compatibility.)
  7444. // Rather than emitting a normal format/argument mismatch, we want to
  7445. // add a cast to the recommended type (and correct the format string
  7446. // if necessary).
  7447. SmallString<16> CastBuf;
  7448. llvm::raw_svector_ostream CastFix(CastBuf);
  7449. CastFix << "(";
  7450. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  7451. CastFix << ")";
  7452. SmallVector<FixItHint,4> Hints;
  7453. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  7454. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  7455. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  7456. // If there's already a cast present, just replace it.
  7457. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  7458. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  7459. } else if (!requiresParensToAddCast(E)) {
  7460. // If the expression has high enough precedence,
  7461. // just write the C-style cast.
  7462. Hints.push_back(
  7463. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7464. } else {
  7465. // Otherwise, add parens around the expression as well as the cast.
  7466. CastFix << "(";
  7467. Hints.push_back(
  7468. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7469. SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
  7470. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  7471. }
  7472. if (ShouldNotPrintDirectly) {
  7473. // The expression has a type that should not be printed directly.
  7474. // We extract the name from the typedef because we don't want to show
  7475. // the underlying type in the diagnostic.
  7476. StringRef Name;
  7477. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  7478. Name = TypedefTy->getDecl()->getName();
  7479. else
  7480. Name = CastTyName;
  7481. unsigned Diag = Pedantic
  7482. ? diag::warn_format_argument_needs_cast_pedantic
  7483. : diag::warn_format_argument_needs_cast;
  7484. EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
  7485. << E->getSourceRange(),
  7486. E->getBeginLoc(), /*IsStringLocation=*/false,
  7487. SpecRange, Hints);
  7488. } else {
  7489. // In this case, the expression could be printed using a different
  7490. // specifier, but we've decided that the specifier is probably correct
  7491. // and we should cast instead. Just use the normal warning message.
  7492. EmitFormatDiagnostic(
  7493. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7494. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  7495. << E->getSourceRange(),
  7496. E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
  7497. }
  7498. }
  7499. } else {
  7500. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  7501. SpecifierLen);
  7502. // Since the warning for passing non-POD types to variadic functions
  7503. // was deferred until now, we emit a warning for non-POD
  7504. // arguments here.
  7505. switch (S.isValidVarArgType(ExprTy)) {
  7506. case Sema::VAK_Valid:
  7507. case Sema::VAK_ValidInCXX11: {
  7508. unsigned Diag =
  7509. Pedantic
  7510. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7511. : diag::warn_format_conversion_argument_type_mismatch;
  7512. EmitFormatDiagnostic(
  7513. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  7514. << IsEnum << CSR << E->getSourceRange(),
  7515. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7516. break;
  7517. }
  7518. case Sema::VAK_Undefined:
  7519. case Sema::VAK_MSVCUndefined:
  7520. EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  7521. << S.getLangOpts().CPlusPlus11 << ExprTy
  7522. << CallType
  7523. << AT.getRepresentativeTypeName(S.Context) << CSR
  7524. << E->getSourceRange(),
  7525. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7526. checkForCStrMembers(AT, E);
  7527. break;
  7528. case Sema::VAK_Invalid:
  7529. if (ExprTy->isObjCObjectType())
  7530. EmitFormatDiagnostic(
  7531. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  7532. << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
  7533. << AT.getRepresentativeTypeName(S.Context) << CSR
  7534. << E->getSourceRange(),
  7535. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7536. else
  7537. // FIXME: If this is an initializer list, suggest removing the braces
  7538. // or inserting a cast to the target type.
  7539. S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
  7540. << isa<InitListExpr>(E) << ExprTy << CallType
  7541. << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
  7542. break;
  7543. }
  7544. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  7545. "format string specifier index out of range");
  7546. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  7547. }
  7548. return true;
  7549. }
  7550. //===--- CHECK: Scanf format string checking ------------------------------===//
  7551. namespace {
  7552. class CheckScanfHandler : public CheckFormatHandler {
  7553. public:
  7554. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  7555. const Expr *origFormatExpr, Sema::FormatStringType type,
  7556. unsigned firstDataArg, unsigned numDataArgs,
  7557. const char *beg, bool hasVAListArg,
  7558. ArrayRef<const Expr *> Args, unsigned formatIdx,
  7559. bool inFunctionCall, Sema::VariadicCallType CallType,
  7560. llvm::SmallBitVector &CheckedVarArgs,
  7561. UncoveredArgHandler &UncoveredArg)
  7562. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  7563. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  7564. inFunctionCall, CallType, CheckedVarArgs,
  7565. UncoveredArg) {}
  7566. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  7567. const char *startSpecifier,
  7568. unsigned specifierLen) override;
  7569. bool HandleInvalidScanfConversionSpecifier(
  7570. const analyze_scanf::ScanfSpecifier &FS,
  7571. const char *startSpecifier,
  7572. unsigned specifierLen) override;
  7573. void HandleIncompleteScanList(const char *start, const char *end) override;
  7574. };
  7575. } // namespace
  7576. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  7577. const char *end) {
  7578. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  7579. getLocationOfByte(end), /*IsStringLocation*/true,
  7580. getSpecifierRange(start, end - start));
  7581. }
  7582. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  7583. const analyze_scanf::ScanfSpecifier &FS,
  7584. const char *startSpecifier,
  7585. unsigned specifierLen) {
  7586. const analyze_scanf::ScanfConversionSpecifier &CS =
  7587. FS.getConversionSpecifier();
  7588. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  7589. getLocationOfByte(CS.getStart()),
  7590. startSpecifier, specifierLen,
  7591. CS.getStart(), CS.getLength());
  7592. }
  7593. bool CheckScanfHandler::HandleScanfSpecifier(
  7594. const analyze_scanf::ScanfSpecifier &FS,
  7595. const char *startSpecifier,
  7596. unsigned specifierLen) {
  7597. using namespace analyze_scanf;
  7598. using namespace analyze_format_string;
  7599. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  7600. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  7601. // be used to decide if we are using positional arguments consistently.
  7602. if (FS.consumesDataArgument()) {
  7603. if (atFirstArg) {
  7604. atFirstArg = false;
  7605. usesPositionalArgs = FS.usesPositionalArg();
  7606. }
  7607. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7608. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7609. startSpecifier, specifierLen);
  7610. return false;
  7611. }
  7612. }
  7613. // Check if the field with is non-zero.
  7614. const OptionalAmount &Amt = FS.getFieldWidth();
  7615. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  7616. if (Amt.getConstantAmount() == 0) {
  7617. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  7618. Amt.getConstantLength());
  7619. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  7620. getLocationOfByte(Amt.getStart()),
  7621. /*IsStringLocation*/true, R,
  7622. FixItHint::CreateRemoval(R));
  7623. }
  7624. }
  7625. if (!FS.consumesDataArgument()) {
  7626. // FIXME: Technically specifying a precision or field width here
  7627. // makes no sense. Worth issuing a warning at some point.
  7628. return true;
  7629. }
  7630. // Consume the argument.
  7631. unsigned argIndex = FS.getArgIndex();
  7632. if (argIndex < NumDataArgs) {
  7633. // The check to see if the argIndex is valid will come later.
  7634. // We set the bit here because we may exit early from this
  7635. // function if we encounter some other error.
  7636. CoveredArgs.set(argIndex);
  7637. }
  7638. // Check the length modifier is valid with the given conversion specifier.
  7639. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7640. S.getLangOpts()))
  7641. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7642. diag::warn_format_nonsensical_length);
  7643. else if (!FS.hasStandardLengthModifier())
  7644. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7645. else if (!FS.hasStandardLengthConversionCombination())
  7646. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7647. diag::warn_format_non_standard_conversion_spec);
  7648. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7649. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7650. // The remaining checks depend on the data arguments.
  7651. if (HasVAListArg)
  7652. return true;
  7653. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7654. return false;
  7655. // Check that the argument type matches the format specifier.
  7656. const Expr *Ex = getDataArg(argIndex);
  7657. if (!Ex)
  7658. return true;
  7659. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  7660. if (!AT.isValid()) {
  7661. return true;
  7662. }
  7663. analyze_format_string::ArgType::MatchKind Match =
  7664. AT.matchesType(S.Context, Ex->getType());
  7665. bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
  7666. if (Match == analyze_format_string::ArgType::Match)
  7667. return true;
  7668. ScanfSpecifier fixedFS = FS;
  7669. bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  7670. S.getLangOpts(), S.Context);
  7671. unsigned Diag =
  7672. Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7673. : diag::warn_format_conversion_argument_type_mismatch;
  7674. if (Success) {
  7675. // Get the fix string from the fixed format specifier.
  7676. SmallString<128> buf;
  7677. llvm::raw_svector_ostream os(buf);
  7678. fixedFS.toString(os);
  7679. EmitFormatDiagnostic(
  7680. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
  7681. << Ex->getType() << false << Ex->getSourceRange(),
  7682. Ex->getBeginLoc(),
  7683. /*IsStringLocation*/ false,
  7684. getSpecifierRange(startSpecifier, specifierLen),
  7685. FixItHint::CreateReplacement(
  7686. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  7687. } else {
  7688. EmitFormatDiagnostic(S.PDiag(Diag)
  7689. << AT.getRepresentativeTypeName(S.Context)
  7690. << Ex->getType() << false << Ex->getSourceRange(),
  7691. Ex->getBeginLoc(),
  7692. /*IsStringLocation*/ false,
  7693. getSpecifierRange(startSpecifier, specifierLen));
  7694. }
  7695. return true;
  7696. }
  7697. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  7698. const Expr *OrigFormatExpr,
  7699. ArrayRef<const Expr *> Args,
  7700. bool HasVAListArg, unsigned format_idx,
  7701. unsigned firstDataArg,
  7702. Sema::FormatStringType Type,
  7703. bool inFunctionCall,
  7704. Sema::VariadicCallType CallType,
  7705. llvm::SmallBitVector &CheckedVarArgs,
  7706. UncoveredArgHandler &UncoveredArg,
  7707. bool IgnoreStringsWithoutSpecifiers) {
  7708. // CHECK: is the format string a wide literal?
  7709. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  7710. CheckFormatHandler::EmitFormatDiagnostic(
  7711. S, inFunctionCall, Args[format_idx],
  7712. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
  7713. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7714. return;
  7715. }
  7716. // Str - The format string. NOTE: this is NOT null-terminated!
  7717. StringRef StrRef = FExpr->getString();
  7718. const char *Str = StrRef.data();
  7719. // Account for cases where the string literal is truncated in a declaration.
  7720. const ConstantArrayType *T =
  7721. S.Context.getAsConstantArrayType(FExpr->getType());
  7722. assert(T && "String literal not of constant array type!");
  7723. size_t TypeSize = T->getSize().getZExtValue();
  7724. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7725. const unsigned numDataArgs = Args.size() - firstDataArg;
  7726. if (IgnoreStringsWithoutSpecifiers &&
  7727. !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
  7728. Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
  7729. return;
  7730. // Emit a warning if the string literal is truncated and does not contain an
  7731. // embedded null character.
  7732. if (TypeSize <= StrRef.size() &&
  7733. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  7734. CheckFormatHandler::EmitFormatDiagnostic(
  7735. S, inFunctionCall, Args[format_idx],
  7736. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  7737. FExpr->getBeginLoc(),
  7738. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  7739. return;
  7740. }
  7741. // CHECK: empty format string?
  7742. if (StrLen == 0 && numDataArgs > 0) {
  7743. CheckFormatHandler::EmitFormatDiagnostic(
  7744. S, inFunctionCall, Args[format_idx],
  7745. S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
  7746. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7747. return;
  7748. }
  7749. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  7750. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  7751. Type == Sema::FST_OSTrace) {
  7752. CheckPrintfHandler H(
  7753. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  7754. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  7755. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  7756. CheckedVarArgs, UncoveredArg);
  7757. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  7758. S.getLangOpts(),
  7759. S.Context.getTargetInfo(),
  7760. Type == Sema::FST_FreeBSDKPrintf))
  7761. H.DoneProcessing();
  7762. } else if (Type == Sema::FST_Scanf) {
  7763. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  7764. numDataArgs, Str, HasVAListArg, Args, format_idx,
  7765. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  7766. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  7767. S.getLangOpts(),
  7768. S.Context.getTargetInfo()))
  7769. H.DoneProcessing();
  7770. } // TODO: handle other formats
  7771. }
  7772. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  7773. // Str - The format string. NOTE: this is NOT null-terminated!
  7774. StringRef StrRef = FExpr->getString();
  7775. const char *Str = StrRef.data();
  7776. // Account for cases where the string literal is truncated in a declaration.
  7777. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  7778. assert(T && "String literal not of constant array type!");
  7779. size_t TypeSize = T->getSize().getZExtValue();
  7780. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7781. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  7782. getLangOpts(),
  7783. Context.getTargetInfo());
  7784. }
  7785. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  7786. // Returns the related absolute value function that is larger, of 0 if one
  7787. // does not exist.
  7788. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  7789. switch (AbsFunction) {
  7790. default:
  7791. return 0;
  7792. case Builtin::BI__builtin_abs:
  7793. return Builtin::BI__builtin_labs;
  7794. case Builtin::BI__builtin_labs:
  7795. return Builtin::BI__builtin_llabs;
  7796. case Builtin::BI__builtin_llabs:
  7797. return 0;
  7798. case Builtin::BI__builtin_fabsf:
  7799. return Builtin::BI__builtin_fabs;
  7800. case Builtin::BI__builtin_fabs:
  7801. return Builtin::BI__builtin_fabsl;
  7802. case Builtin::BI__builtin_fabsl:
  7803. return 0;
  7804. case Builtin::BI__builtin_cabsf:
  7805. return Builtin::BI__builtin_cabs;
  7806. case Builtin::BI__builtin_cabs:
  7807. return Builtin::BI__builtin_cabsl;
  7808. case Builtin::BI__builtin_cabsl:
  7809. return 0;
  7810. case Builtin::BIabs:
  7811. return Builtin::BIlabs;
  7812. case Builtin::BIlabs:
  7813. return Builtin::BIllabs;
  7814. case Builtin::BIllabs:
  7815. return 0;
  7816. case Builtin::BIfabsf:
  7817. return Builtin::BIfabs;
  7818. case Builtin::BIfabs:
  7819. return Builtin::BIfabsl;
  7820. case Builtin::BIfabsl:
  7821. return 0;
  7822. case Builtin::BIcabsf:
  7823. return Builtin::BIcabs;
  7824. case Builtin::BIcabs:
  7825. return Builtin::BIcabsl;
  7826. case Builtin::BIcabsl:
  7827. return 0;
  7828. }
  7829. }
  7830. // Returns the argument type of the absolute value function.
  7831. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  7832. unsigned AbsType) {
  7833. if (AbsType == 0)
  7834. return QualType();
  7835. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  7836. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  7837. if (Error != ASTContext::GE_None)
  7838. return QualType();
  7839. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  7840. if (!FT)
  7841. return QualType();
  7842. if (FT->getNumParams() != 1)
  7843. return QualType();
  7844. return FT->getParamType(0);
  7845. }
  7846. // Returns the best absolute value function, or zero, based on type and
  7847. // current absolute value function.
  7848. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  7849. unsigned AbsFunctionKind) {
  7850. unsigned BestKind = 0;
  7851. uint64_t ArgSize = Context.getTypeSize(ArgType);
  7852. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  7853. Kind = getLargerAbsoluteValueFunction(Kind)) {
  7854. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  7855. if (Context.getTypeSize(ParamType) >= ArgSize) {
  7856. if (BestKind == 0)
  7857. BestKind = Kind;
  7858. else if (Context.hasSameType(ParamType, ArgType)) {
  7859. BestKind = Kind;
  7860. break;
  7861. }
  7862. }
  7863. }
  7864. return BestKind;
  7865. }
  7866. enum AbsoluteValueKind {
  7867. AVK_Integer,
  7868. AVK_Floating,
  7869. AVK_Complex
  7870. };
  7871. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  7872. if (T->isIntegralOrEnumerationType())
  7873. return AVK_Integer;
  7874. if (T->isRealFloatingType())
  7875. return AVK_Floating;
  7876. if (T->isAnyComplexType())
  7877. return AVK_Complex;
  7878. llvm_unreachable("Type not integer, floating, or complex");
  7879. }
  7880. // Changes the absolute value function to a different type. Preserves whether
  7881. // the function is a builtin.
  7882. static unsigned changeAbsFunction(unsigned AbsKind,
  7883. AbsoluteValueKind ValueKind) {
  7884. switch (ValueKind) {
  7885. case AVK_Integer:
  7886. switch (AbsKind) {
  7887. default:
  7888. return 0;
  7889. case Builtin::BI__builtin_fabsf:
  7890. case Builtin::BI__builtin_fabs:
  7891. case Builtin::BI__builtin_fabsl:
  7892. case Builtin::BI__builtin_cabsf:
  7893. case Builtin::BI__builtin_cabs:
  7894. case Builtin::BI__builtin_cabsl:
  7895. return Builtin::BI__builtin_abs;
  7896. case Builtin::BIfabsf:
  7897. case Builtin::BIfabs:
  7898. case Builtin::BIfabsl:
  7899. case Builtin::BIcabsf:
  7900. case Builtin::BIcabs:
  7901. case Builtin::BIcabsl:
  7902. return Builtin::BIabs;
  7903. }
  7904. case AVK_Floating:
  7905. switch (AbsKind) {
  7906. default:
  7907. return 0;
  7908. case Builtin::BI__builtin_abs:
  7909. case Builtin::BI__builtin_labs:
  7910. case Builtin::BI__builtin_llabs:
  7911. case Builtin::BI__builtin_cabsf:
  7912. case Builtin::BI__builtin_cabs:
  7913. case Builtin::BI__builtin_cabsl:
  7914. return Builtin::BI__builtin_fabsf;
  7915. case Builtin::BIabs:
  7916. case Builtin::BIlabs:
  7917. case Builtin::BIllabs:
  7918. case Builtin::BIcabsf:
  7919. case Builtin::BIcabs:
  7920. case Builtin::BIcabsl:
  7921. return Builtin::BIfabsf;
  7922. }
  7923. case AVK_Complex:
  7924. switch (AbsKind) {
  7925. default:
  7926. return 0;
  7927. case Builtin::BI__builtin_abs:
  7928. case Builtin::BI__builtin_labs:
  7929. case Builtin::BI__builtin_llabs:
  7930. case Builtin::BI__builtin_fabsf:
  7931. case Builtin::BI__builtin_fabs:
  7932. case Builtin::BI__builtin_fabsl:
  7933. return Builtin::BI__builtin_cabsf;
  7934. case Builtin::BIabs:
  7935. case Builtin::BIlabs:
  7936. case Builtin::BIllabs:
  7937. case Builtin::BIfabsf:
  7938. case Builtin::BIfabs:
  7939. case Builtin::BIfabsl:
  7940. return Builtin::BIcabsf;
  7941. }
  7942. }
  7943. llvm_unreachable("Unable to convert function");
  7944. }
  7945. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  7946. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  7947. if (!FnInfo)
  7948. return 0;
  7949. switch (FDecl->getBuiltinID()) {
  7950. default:
  7951. return 0;
  7952. case Builtin::BI__builtin_abs:
  7953. case Builtin::BI__builtin_fabs:
  7954. case Builtin::BI__builtin_fabsf:
  7955. case Builtin::BI__builtin_fabsl:
  7956. case Builtin::BI__builtin_labs:
  7957. case Builtin::BI__builtin_llabs:
  7958. case Builtin::BI__builtin_cabs:
  7959. case Builtin::BI__builtin_cabsf:
  7960. case Builtin::BI__builtin_cabsl:
  7961. case Builtin::BIabs:
  7962. case Builtin::BIlabs:
  7963. case Builtin::BIllabs:
  7964. case Builtin::BIfabs:
  7965. case Builtin::BIfabsf:
  7966. case Builtin::BIfabsl:
  7967. case Builtin::BIcabs:
  7968. case Builtin::BIcabsf:
  7969. case Builtin::BIcabsl:
  7970. return FDecl->getBuiltinID();
  7971. }
  7972. llvm_unreachable("Unknown Builtin type");
  7973. }
  7974. // If the replacement is valid, emit a note with replacement function.
  7975. // Additionally, suggest including the proper header if not already included.
  7976. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  7977. unsigned AbsKind, QualType ArgType) {
  7978. bool EmitHeaderHint = true;
  7979. const char *HeaderName = nullptr;
  7980. const char *FunctionName = nullptr;
  7981. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  7982. FunctionName = "std::abs";
  7983. if (ArgType->isIntegralOrEnumerationType()) {
  7984. HeaderName = "cstdlib";
  7985. } else if (ArgType->isRealFloatingType()) {
  7986. HeaderName = "cmath";
  7987. } else {
  7988. llvm_unreachable("Invalid Type");
  7989. }
  7990. // Lookup all std::abs
  7991. if (NamespaceDecl *Std = S.getStdNamespace()) {
  7992. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  7993. R.suppressDiagnostics();
  7994. S.LookupQualifiedName(R, Std);
  7995. for (const auto *I : R) {
  7996. const FunctionDecl *FDecl = nullptr;
  7997. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  7998. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  7999. } else {
  8000. FDecl = dyn_cast<FunctionDecl>(I);
  8001. }
  8002. if (!FDecl)
  8003. continue;
  8004. // Found std::abs(), check that they are the right ones.
  8005. if (FDecl->getNumParams() != 1)
  8006. continue;
  8007. // Check that the parameter type can handle the argument.
  8008. QualType ParamType = FDecl->getParamDecl(0)->getType();
  8009. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  8010. S.Context.getTypeSize(ArgType) <=
  8011. S.Context.getTypeSize(ParamType)) {
  8012. // Found a function, don't need the header hint.
  8013. EmitHeaderHint = false;
  8014. break;
  8015. }
  8016. }
  8017. }
  8018. } else {
  8019. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  8020. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  8021. if (HeaderName) {
  8022. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  8023. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  8024. R.suppressDiagnostics();
  8025. S.LookupName(R, S.getCurScope());
  8026. if (R.isSingleResult()) {
  8027. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  8028. if (FD && FD->getBuiltinID() == AbsKind) {
  8029. EmitHeaderHint = false;
  8030. } else {
  8031. return;
  8032. }
  8033. } else if (!R.empty()) {
  8034. return;
  8035. }
  8036. }
  8037. }
  8038. S.Diag(Loc, diag::note_replace_abs_function)
  8039. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  8040. if (!HeaderName)
  8041. return;
  8042. if (!EmitHeaderHint)
  8043. return;
  8044. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  8045. << FunctionName;
  8046. }
  8047. template <std::size_t StrLen>
  8048. static bool IsStdFunction(const FunctionDecl *FDecl,
  8049. const char (&Str)[StrLen]) {
  8050. if (!FDecl)
  8051. return false;
  8052. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  8053. return false;
  8054. if (!FDecl->isInStdNamespace())
  8055. return false;
  8056. return true;
  8057. }
  8058. // Warn when using the wrong abs() function.
  8059. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  8060. const FunctionDecl *FDecl) {
  8061. if (Call->getNumArgs() != 1)
  8062. return;
  8063. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  8064. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  8065. if (AbsKind == 0 && !IsStdAbs)
  8066. return;
  8067. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8068. QualType ParamType = Call->getArg(0)->getType();
  8069. // Unsigned types cannot be negative. Suggest removing the absolute value
  8070. // function call.
  8071. if (ArgType->isUnsignedIntegerType()) {
  8072. const char *FunctionName =
  8073. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  8074. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  8075. Diag(Call->getExprLoc(), diag::note_remove_abs)
  8076. << FunctionName
  8077. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  8078. return;
  8079. }
  8080. // Taking the absolute value of a pointer is very suspicious, they probably
  8081. // wanted to index into an array, dereference a pointer, call a function, etc.
  8082. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  8083. unsigned DiagType = 0;
  8084. if (ArgType->isFunctionType())
  8085. DiagType = 1;
  8086. else if (ArgType->isArrayType())
  8087. DiagType = 2;
  8088. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  8089. return;
  8090. }
  8091. // std::abs has overloads which prevent most of the absolute value problems
  8092. // from occurring.
  8093. if (IsStdAbs)
  8094. return;
  8095. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  8096. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  8097. // The argument and parameter are the same kind. Check if they are the right
  8098. // size.
  8099. if (ArgValueKind == ParamValueKind) {
  8100. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  8101. return;
  8102. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  8103. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  8104. << FDecl << ArgType << ParamType;
  8105. if (NewAbsKind == 0)
  8106. return;
  8107. emitReplacement(*this, Call->getExprLoc(),
  8108. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8109. return;
  8110. }
  8111. // ArgValueKind != ParamValueKind
  8112. // The wrong type of absolute value function was used. Attempt to find the
  8113. // proper one.
  8114. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  8115. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  8116. if (NewAbsKind == 0)
  8117. return;
  8118. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  8119. << FDecl << ParamValueKind << ArgValueKind;
  8120. emitReplacement(*this, Call->getExprLoc(),
  8121. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8122. }
  8123. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  8124. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  8125. const FunctionDecl *FDecl) {
  8126. if (!Call || !FDecl) return;
  8127. // Ignore template specializations and macros.
  8128. if (inTemplateInstantiation()) return;
  8129. if (Call->getExprLoc().isMacroID()) return;
  8130. // Only care about the one template argument, two function parameter std::max
  8131. if (Call->getNumArgs() != 2) return;
  8132. if (!IsStdFunction(FDecl, "max")) return;
  8133. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  8134. if (!ArgList) return;
  8135. if (ArgList->size() != 1) return;
  8136. // Check that template type argument is unsigned integer.
  8137. const auto& TA = ArgList->get(0);
  8138. if (TA.getKind() != TemplateArgument::Type) return;
  8139. QualType ArgType = TA.getAsType();
  8140. if (!ArgType->isUnsignedIntegerType()) return;
  8141. // See if either argument is a literal zero.
  8142. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  8143. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  8144. if (!MTE) return false;
  8145. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  8146. if (!Num) return false;
  8147. if (Num->getValue() != 0) return false;
  8148. return true;
  8149. };
  8150. const Expr *FirstArg = Call->getArg(0);
  8151. const Expr *SecondArg = Call->getArg(1);
  8152. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  8153. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  8154. // Only warn when exactly one argument is zero.
  8155. if (IsFirstArgZero == IsSecondArgZero) return;
  8156. SourceRange FirstRange = FirstArg->getSourceRange();
  8157. SourceRange SecondRange = SecondArg->getSourceRange();
  8158. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  8159. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  8160. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  8161. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  8162. SourceRange RemovalRange;
  8163. if (IsFirstArgZero) {
  8164. RemovalRange = SourceRange(FirstRange.getBegin(),
  8165. SecondRange.getBegin().getLocWithOffset(-1));
  8166. } else {
  8167. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  8168. SecondRange.getEnd());
  8169. }
  8170. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  8171. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  8172. << FixItHint::CreateRemoval(RemovalRange);
  8173. }
  8174. //===--- CHECK: Standard memory functions ---------------------------------===//
  8175. /// Takes the expression passed to the size_t parameter of functions
  8176. /// such as memcmp, strncat, etc and warns if it's a comparison.
  8177. ///
  8178. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  8179. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  8180. IdentifierInfo *FnName,
  8181. SourceLocation FnLoc,
  8182. SourceLocation RParenLoc) {
  8183. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  8184. if (!Size)
  8185. return false;
  8186. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  8187. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  8188. return false;
  8189. SourceRange SizeRange = Size->getSourceRange();
  8190. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  8191. << SizeRange << FnName;
  8192. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  8193. << FnName
  8194. << FixItHint::CreateInsertion(
  8195. S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
  8196. << FixItHint::CreateRemoval(RParenLoc);
  8197. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  8198. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  8199. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  8200. ")");
  8201. return true;
  8202. }
  8203. /// Determine whether the given type is or contains a dynamic class type
  8204. /// (e.g., whether it has a vtable).
  8205. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  8206. bool &IsContained) {
  8207. // Look through array types while ignoring qualifiers.
  8208. const Type *Ty = T->getBaseElementTypeUnsafe();
  8209. IsContained = false;
  8210. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  8211. RD = RD ? RD->getDefinition() : nullptr;
  8212. if (!RD || RD->isInvalidDecl())
  8213. return nullptr;
  8214. if (RD->isDynamicClass())
  8215. return RD;
  8216. // Check all the fields. If any bases were dynamic, the class is dynamic.
  8217. // It's impossible for a class to transitively contain itself by value, so
  8218. // infinite recursion is impossible.
  8219. for (auto *FD : RD->fields()) {
  8220. bool SubContained;
  8221. if (const CXXRecordDecl *ContainedRD =
  8222. getContainedDynamicClass(FD->getType(), SubContained)) {
  8223. IsContained = true;
  8224. return ContainedRD;
  8225. }
  8226. }
  8227. return nullptr;
  8228. }
  8229. static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
  8230. if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  8231. if (Unary->getKind() == UETT_SizeOf)
  8232. return Unary;
  8233. return nullptr;
  8234. }
  8235. /// If E is a sizeof expression, returns its argument expression,
  8236. /// otherwise returns NULL.
  8237. static const Expr *getSizeOfExprArg(const Expr *E) {
  8238. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8239. if (!SizeOf->isArgumentType())
  8240. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  8241. return nullptr;
  8242. }
  8243. /// If E is a sizeof expression, returns its argument type.
  8244. static QualType getSizeOfArgType(const Expr *E) {
  8245. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8246. return SizeOf->getTypeOfArgument();
  8247. return QualType();
  8248. }
  8249. namespace {
  8250. struct SearchNonTrivialToInitializeField
  8251. : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
  8252. using Super =
  8253. DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
  8254. SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
  8255. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
  8256. SourceLocation SL) {
  8257. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8258. asDerived().visitArray(PDIK, AT, SL);
  8259. return;
  8260. }
  8261. Super::visitWithKind(PDIK, FT, SL);
  8262. }
  8263. void visitARCStrong(QualType FT, SourceLocation SL) {
  8264. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8265. }
  8266. void visitARCWeak(QualType FT, SourceLocation SL) {
  8267. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8268. }
  8269. void visitStruct(QualType FT, SourceLocation SL) {
  8270. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8271. visit(FD->getType(), FD->getLocation());
  8272. }
  8273. void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
  8274. const ArrayType *AT, SourceLocation SL) {
  8275. visit(getContext().getBaseElementType(AT), SL);
  8276. }
  8277. void visitTrivial(QualType FT, SourceLocation SL) {}
  8278. static void diag(QualType RT, const Expr *E, Sema &S) {
  8279. SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
  8280. }
  8281. ASTContext &getContext() { return S.getASTContext(); }
  8282. const Expr *E;
  8283. Sema &S;
  8284. };
  8285. struct SearchNonTrivialToCopyField
  8286. : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
  8287. using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
  8288. SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
  8289. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
  8290. SourceLocation SL) {
  8291. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8292. asDerived().visitArray(PCK, AT, SL);
  8293. return;
  8294. }
  8295. Super::visitWithKind(PCK, FT, SL);
  8296. }
  8297. void visitARCStrong(QualType FT, SourceLocation SL) {
  8298. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8299. }
  8300. void visitARCWeak(QualType FT, SourceLocation SL) {
  8301. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8302. }
  8303. void visitStruct(QualType FT, SourceLocation SL) {
  8304. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8305. visit(FD->getType(), FD->getLocation());
  8306. }
  8307. void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
  8308. SourceLocation SL) {
  8309. visit(getContext().getBaseElementType(AT), SL);
  8310. }
  8311. void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
  8312. SourceLocation SL) {}
  8313. void visitTrivial(QualType FT, SourceLocation SL) {}
  8314. void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
  8315. static void diag(QualType RT, const Expr *E, Sema &S) {
  8316. SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
  8317. }
  8318. ASTContext &getContext() { return S.getASTContext(); }
  8319. const Expr *E;
  8320. Sema &S;
  8321. };
  8322. }
  8323. /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
  8324. static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
  8325. SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
  8326. if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
  8327. if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
  8328. return false;
  8329. return doesExprLikelyComputeSize(BO->getLHS()) ||
  8330. doesExprLikelyComputeSize(BO->getRHS());
  8331. }
  8332. return getAsSizeOfExpr(SizeofExpr) != nullptr;
  8333. }
  8334. /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
  8335. ///
  8336. /// \code
  8337. /// #define MACRO 0
  8338. /// foo(MACRO);
  8339. /// foo(0);
  8340. /// \endcode
  8341. ///
  8342. /// This should return true for the first call to foo, but not for the second
  8343. /// (regardless of whether foo is a macro or function).
  8344. static bool isArgumentExpandedFromMacro(SourceManager &SM,
  8345. SourceLocation CallLoc,
  8346. SourceLocation ArgLoc) {
  8347. if (!CallLoc.isMacroID())
  8348. return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
  8349. return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
  8350. SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
  8351. }
  8352. /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
  8353. /// last two arguments transposed.
  8354. static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
  8355. if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
  8356. return;
  8357. const Expr *SizeArg =
  8358. Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
  8359. auto isLiteralZero = [](const Expr *E) {
  8360. return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
  8361. };
  8362. // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
  8363. SourceLocation CallLoc = Call->getRParenLoc();
  8364. SourceManager &SM = S.getSourceManager();
  8365. if (isLiteralZero(SizeArg) &&
  8366. !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
  8367. SourceLocation DiagLoc = SizeArg->getExprLoc();
  8368. // Some platforms #define bzero to __builtin_memset. See if this is the
  8369. // case, and if so, emit a better diagnostic.
  8370. if (BId == Builtin::BIbzero ||
  8371. (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
  8372. CallLoc, SM, S.getLangOpts()) == "bzero")) {
  8373. S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
  8374. S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
  8375. } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
  8376. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
  8377. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
  8378. }
  8379. return;
  8380. }
  8381. // If the second argument to a memset is a sizeof expression and the third
  8382. // isn't, this is also likely an error. This should catch
  8383. // 'memset(buf, sizeof(buf), 0xff)'.
  8384. if (BId == Builtin::BImemset &&
  8385. doesExprLikelyComputeSize(Call->getArg(1)) &&
  8386. !doesExprLikelyComputeSize(Call->getArg(2))) {
  8387. SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
  8388. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
  8389. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
  8390. return;
  8391. }
  8392. }
  8393. /// Check for dangerous or invalid arguments to memset().
  8394. ///
  8395. /// This issues warnings on known problematic, dangerous or unspecified
  8396. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  8397. /// function calls.
  8398. ///
  8399. /// \param Call The call expression to diagnose.
  8400. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  8401. unsigned BId,
  8402. IdentifierInfo *FnName) {
  8403. assert(BId != 0);
  8404. // It is possible to have a non-standard definition of memset. Validate
  8405. // we have enough arguments, and if not, abort further checking.
  8406. unsigned ExpectedNumArgs =
  8407. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  8408. if (Call->getNumArgs() < ExpectedNumArgs)
  8409. return;
  8410. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  8411. BId == Builtin::BIstrndup ? 1 : 2);
  8412. unsigned LenArg =
  8413. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  8414. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  8415. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  8416. Call->getBeginLoc(), Call->getRParenLoc()))
  8417. return;
  8418. // Catch cases like 'memset(buf, sizeof(buf), 0)'.
  8419. CheckMemaccessSize(*this, BId, Call);
  8420. // We have special checking when the length is a sizeof expression.
  8421. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  8422. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  8423. llvm::FoldingSetNodeID SizeOfArgID;
  8424. // Although widely used, 'bzero' is not a standard function. Be more strict
  8425. // with the argument types before allowing diagnostics and only allow the
  8426. // form bzero(ptr, sizeof(...)).
  8427. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8428. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  8429. return;
  8430. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  8431. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  8432. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  8433. QualType DestTy = Dest->getType();
  8434. QualType PointeeTy;
  8435. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  8436. PointeeTy = DestPtrTy->getPointeeType();
  8437. // Never warn about void type pointers. This can be used to suppress
  8438. // false positives.
  8439. if (PointeeTy->isVoidType())
  8440. continue;
  8441. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  8442. // actually comparing the expressions for equality. Because computing the
  8443. // expression IDs can be expensive, we only do this if the diagnostic is
  8444. // enabled.
  8445. if (SizeOfArg &&
  8446. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  8447. SizeOfArg->getExprLoc())) {
  8448. // We only compute IDs for expressions if the warning is enabled, and
  8449. // cache the sizeof arg's ID.
  8450. if (SizeOfArgID == llvm::FoldingSetNodeID())
  8451. SizeOfArg->Profile(SizeOfArgID, Context, true);
  8452. llvm::FoldingSetNodeID DestID;
  8453. Dest->Profile(DestID, Context, true);
  8454. if (DestID == SizeOfArgID) {
  8455. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  8456. // over sizeof(src) as well.
  8457. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  8458. StringRef ReadableName = FnName->getName();
  8459. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  8460. if (UnaryOp->getOpcode() == UO_AddrOf)
  8461. ActionIdx = 1; // If its an address-of operator, just remove it.
  8462. if (!PointeeTy->isIncompleteType() &&
  8463. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  8464. ActionIdx = 2; // If the pointee's size is sizeof(char),
  8465. // suggest an explicit length.
  8466. // If the function is defined as a builtin macro, do not show macro
  8467. // expansion.
  8468. SourceLocation SL = SizeOfArg->getExprLoc();
  8469. SourceRange DSR = Dest->getSourceRange();
  8470. SourceRange SSR = SizeOfArg->getSourceRange();
  8471. SourceManager &SM = getSourceManager();
  8472. if (SM.isMacroArgExpansion(SL)) {
  8473. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  8474. SL = SM.getSpellingLoc(SL);
  8475. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  8476. SM.getSpellingLoc(DSR.getEnd()));
  8477. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  8478. SM.getSpellingLoc(SSR.getEnd()));
  8479. }
  8480. DiagRuntimeBehavior(SL, SizeOfArg,
  8481. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  8482. << ReadableName
  8483. << PointeeTy
  8484. << DestTy
  8485. << DSR
  8486. << SSR);
  8487. DiagRuntimeBehavior(SL, SizeOfArg,
  8488. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  8489. << ActionIdx
  8490. << SSR);
  8491. break;
  8492. }
  8493. }
  8494. // Also check for cases where the sizeof argument is the exact same
  8495. // type as the memory argument, and where it points to a user-defined
  8496. // record type.
  8497. if (SizeOfArgTy != QualType()) {
  8498. if (PointeeTy->isRecordType() &&
  8499. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  8500. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  8501. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  8502. << FnName << SizeOfArgTy << ArgIdx
  8503. << PointeeTy << Dest->getSourceRange()
  8504. << LenExpr->getSourceRange());
  8505. break;
  8506. }
  8507. }
  8508. } else if (DestTy->isArrayType()) {
  8509. PointeeTy = DestTy;
  8510. }
  8511. if (PointeeTy == QualType())
  8512. continue;
  8513. // Always complain about dynamic classes.
  8514. bool IsContained;
  8515. if (const CXXRecordDecl *ContainedRD =
  8516. getContainedDynamicClass(PointeeTy, IsContained)) {
  8517. unsigned OperationType = 0;
  8518. const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
  8519. // "overwritten" if we're warning about the destination for any call
  8520. // but memcmp; otherwise a verb appropriate to the call.
  8521. if (ArgIdx != 0 || IsCmp) {
  8522. if (BId == Builtin::BImemcpy)
  8523. OperationType = 1;
  8524. else if(BId == Builtin::BImemmove)
  8525. OperationType = 2;
  8526. else if (IsCmp)
  8527. OperationType = 3;
  8528. }
  8529. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8530. PDiag(diag::warn_dyn_class_memaccess)
  8531. << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
  8532. << IsContained << ContainedRD << OperationType
  8533. << Call->getCallee()->getSourceRange());
  8534. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  8535. BId != Builtin::BImemset)
  8536. DiagRuntimeBehavior(
  8537. Dest->getExprLoc(), Dest,
  8538. PDiag(diag::warn_arc_object_memaccess)
  8539. << ArgIdx << FnName << PointeeTy
  8540. << Call->getCallee()->getSourceRange());
  8541. else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
  8542. if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
  8543. RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
  8544. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8545. PDiag(diag::warn_cstruct_memaccess)
  8546. << ArgIdx << FnName << PointeeTy << 0);
  8547. SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
  8548. } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  8549. RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
  8550. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8551. PDiag(diag::warn_cstruct_memaccess)
  8552. << ArgIdx << FnName << PointeeTy << 1);
  8553. SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
  8554. } else {
  8555. continue;
  8556. }
  8557. } else
  8558. continue;
  8559. DiagRuntimeBehavior(
  8560. Dest->getExprLoc(), Dest,
  8561. PDiag(diag::note_bad_memaccess_silence)
  8562. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  8563. break;
  8564. }
  8565. }
  8566. // A little helper routine: ignore addition and subtraction of integer literals.
  8567. // This intentionally does not ignore all integer constant expressions because
  8568. // we don't want to remove sizeof().
  8569. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  8570. Ex = Ex->IgnoreParenCasts();
  8571. while (true) {
  8572. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  8573. if (!BO || !BO->isAdditiveOp())
  8574. break;
  8575. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  8576. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  8577. if (isa<IntegerLiteral>(RHS))
  8578. Ex = LHS;
  8579. else if (isa<IntegerLiteral>(LHS))
  8580. Ex = RHS;
  8581. else
  8582. break;
  8583. }
  8584. return Ex;
  8585. }
  8586. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  8587. ASTContext &Context) {
  8588. // Only handle constant-sized or VLAs, but not flexible members.
  8589. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  8590. // Only issue the FIXIT for arrays of size > 1.
  8591. if (CAT->getSize().getSExtValue() <= 1)
  8592. return false;
  8593. } else if (!Ty->isVariableArrayType()) {
  8594. return false;
  8595. }
  8596. return true;
  8597. }
  8598. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  8599. // be the size of the source, instead of the destination.
  8600. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  8601. IdentifierInfo *FnName) {
  8602. // Don't crash if the user has the wrong number of arguments
  8603. unsigned NumArgs = Call->getNumArgs();
  8604. if ((NumArgs != 3) && (NumArgs != 4))
  8605. return;
  8606. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  8607. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  8608. const Expr *CompareWithSrc = nullptr;
  8609. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  8610. Call->getBeginLoc(), Call->getRParenLoc()))
  8611. return;
  8612. // Look for 'strlcpy(dst, x, sizeof(x))'
  8613. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  8614. CompareWithSrc = Ex;
  8615. else {
  8616. // Look for 'strlcpy(dst, x, strlen(x))'
  8617. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  8618. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  8619. SizeCall->getNumArgs() == 1)
  8620. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  8621. }
  8622. }
  8623. if (!CompareWithSrc)
  8624. return;
  8625. // Determine if the argument to sizeof/strlen is equal to the source
  8626. // argument. In principle there's all kinds of things you could do
  8627. // here, for instance creating an == expression and evaluating it with
  8628. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  8629. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  8630. if (!SrcArgDRE)
  8631. return;
  8632. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  8633. if (!CompareWithSrcDRE ||
  8634. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  8635. return;
  8636. const Expr *OriginalSizeArg = Call->getArg(2);
  8637. Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
  8638. << OriginalSizeArg->getSourceRange() << FnName;
  8639. // Output a FIXIT hint if the destination is an array (rather than a
  8640. // pointer to an array). This could be enhanced to handle some
  8641. // pointers if we know the actual size, like if DstArg is 'array+2'
  8642. // we could say 'sizeof(array)-2'.
  8643. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  8644. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  8645. return;
  8646. SmallString<128> sizeString;
  8647. llvm::raw_svector_ostream OS(sizeString);
  8648. OS << "sizeof(";
  8649. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8650. OS << ")";
  8651. Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
  8652. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  8653. OS.str());
  8654. }
  8655. /// Check if two expressions refer to the same declaration.
  8656. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  8657. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  8658. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  8659. return D1->getDecl() == D2->getDecl();
  8660. return false;
  8661. }
  8662. static const Expr *getStrlenExprArg(const Expr *E) {
  8663. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8664. const FunctionDecl *FD = CE->getDirectCallee();
  8665. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  8666. return nullptr;
  8667. return CE->getArg(0)->IgnoreParenCasts();
  8668. }
  8669. return nullptr;
  8670. }
  8671. // Warn on anti-patterns as the 'size' argument to strncat.
  8672. // The correct size argument should look like following:
  8673. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  8674. void Sema::CheckStrncatArguments(const CallExpr *CE,
  8675. IdentifierInfo *FnName) {
  8676. // Don't crash if the user has the wrong number of arguments.
  8677. if (CE->getNumArgs() < 3)
  8678. return;
  8679. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  8680. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  8681. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  8682. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
  8683. CE->getRParenLoc()))
  8684. return;
  8685. // Identify common expressions, which are wrongly used as the size argument
  8686. // to strncat and may lead to buffer overflows.
  8687. unsigned PatternType = 0;
  8688. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  8689. // - sizeof(dst)
  8690. if (referToTheSameDecl(SizeOfArg, DstArg))
  8691. PatternType = 1;
  8692. // - sizeof(src)
  8693. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  8694. PatternType = 2;
  8695. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  8696. if (BE->getOpcode() == BO_Sub) {
  8697. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  8698. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  8699. // - sizeof(dst) - strlen(dst)
  8700. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  8701. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  8702. PatternType = 1;
  8703. // - sizeof(src) - (anything)
  8704. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  8705. PatternType = 2;
  8706. }
  8707. }
  8708. if (PatternType == 0)
  8709. return;
  8710. // Generate the diagnostic.
  8711. SourceLocation SL = LenArg->getBeginLoc();
  8712. SourceRange SR = LenArg->getSourceRange();
  8713. SourceManager &SM = getSourceManager();
  8714. // If the function is defined as a builtin macro, do not show macro expansion.
  8715. if (SM.isMacroArgExpansion(SL)) {
  8716. SL = SM.getSpellingLoc(SL);
  8717. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  8718. SM.getSpellingLoc(SR.getEnd()));
  8719. }
  8720. // Check if the destination is an array (rather than a pointer to an array).
  8721. QualType DstTy = DstArg->getType();
  8722. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  8723. Context);
  8724. if (!isKnownSizeArray) {
  8725. if (PatternType == 1)
  8726. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  8727. else
  8728. Diag(SL, diag::warn_strncat_src_size) << SR;
  8729. return;
  8730. }
  8731. if (PatternType == 1)
  8732. Diag(SL, diag::warn_strncat_large_size) << SR;
  8733. else
  8734. Diag(SL, diag::warn_strncat_src_size) << SR;
  8735. SmallString<128> sizeString;
  8736. llvm::raw_svector_ostream OS(sizeString);
  8737. OS << "sizeof(";
  8738. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8739. OS << ") - ";
  8740. OS << "strlen(";
  8741. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8742. OS << ") - 1";
  8743. Diag(SL, diag::note_strncat_wrong_size)
  8744. << FixItHint::CreateReplacement(SR, OS.str());
  8745. }
  8746. void
  8747. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  8748. SourceLocation ReturnLoc,
  8749. bool isObjCMethod,
  8750. const AttrVec *Attrs,
  8751. const FunctionDecl *FD) {
  8752. // Check if the return value is null but should not be.
  8753. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  8754. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  8755. CheckNonNullExpr(*this, RetValExp))
  8756. Diag(ReturnLoc, diag::warn_null_ret)
  8757. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  8758. // C++11 [basic.stc.dynamic.allocation]p4:
  8759. // If an allocation function declared with a non-throwing
  8760. // exception-specification fails to allocate storage, it shall return
  8761. // a null pointer. Any other allocation function that fails to allocate
  8762. // storage shall indicate failure only by throwing an exception [...]
  8763. if (FD) {
  8764. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  8765. if (Op == OO_New || Op == OO_Array_New) {
  8766. const FunctionProtoType *Proto
  8767. = FD->getType()->castAs<FunctionProtoType>();
  8768. if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
  8769. CheckNonNullExpr(*this, RetValExp))
  8770. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  8771. << FD << getLangOpts().CPlusPlus11;
  8772. }
  8773. }
  8774. }
  8775. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  8776. /// Check for comparisons of floating point operands using != and ==.
  8777. /// Issue a warning if these are no self-comparisons, as they are not likely
  8778. /// to do what the programmer intended.
  8779. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  8780. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  8781. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  8782. // Special case: check for x == x (which is OK).
  8783. // Do not emit warnings for such cases.
  8784. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  8785. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  8786. if (DRL->getDecl() == DRR->getDecl())
  8787. return;
  8788. // Special case: check for comparisons against literals that can be exactly
  8789. // represented by APFloat. In such cases, do not emit a warning. This
  8790. // is a heuristic: often comparison against such literals are used to
  8791. // detect if a value in a variable has not changed. This clearly can
  8792. // lead to false negatives.
  8793. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  8794. if (FLL->isExact())
  8795. return;
  8796. } else
  8797. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  8798. if (FLR->isExact())
  8799. return;
  8800. // Check for comparisons with builtin types.
  8801. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  8802. if (CL->getBuiltinCallee())
  8803. return;
  8804. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  8805. if (CR->getBuiltinCallee())
  8806. return;
  8807. // Emit the diagnostic.
  8808. Diag(Loc, diag::warn_floatingpoint_eq)
  8809. << LHS->getSourceRange() << RHS->getSourceRange();
  8810. }
  8811. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  8812. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  8813. namespace {
  8814. /// Structure recording the 'active' range of an integer-valued
  8815. /// expression.
  8816. struct IntRange {
  8817. /// The number of bits active in the int.
  8818. unsigned Width;
  8819. /// True if the int is known not to have negative values.
  8820. bool NonNegative;
  8821. IntRange(unsigned Width, bool NonNegative)
  8822. : Width(Width), NonNegative(NonNegative) {}
  8823. /// Returns the range of the bool type.
  8824. static IntRange forBoolType() {
  8825. return IntRange(1, true);
  8826. }
  8827. /// Returns the range of an opaque value of the given integral type.
  8828. static IntRange forValueOfType(ASTContext &C, QualType T) {
  8829. return forValueOfCanonicalType(C,
  8830. T->getCanonicalTypeInternal().getTypePtr());
  8831. }
  8832. /// Returns the range of an opaque value of a canonical integral type.
  8833. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  8834. assert(T->isCanonicalUnqualified());
  8835. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8836. T = VT->getElementType().getTypePtr();
  8837. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8838. T = CT->getElementType().getTypePtr();
  8839. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8840. T = AT->getValueType().getTypePtr();
  8841. if (!C.getLangOpts().CPlusPlus) {
  8842. // For enum types in C code, use the underlying datatype.
  8843. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8844. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  8845. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  8846. // For enum types in C++, use the known bit width of the enumerators.
  8847. EnumDecl *Enum = ET->getDecl();
  8848. // In C++11, enums can have a fixed underlying type. Use this type to
  8849. // compute the range.
  8850. if (Enum->isFixed()) {
  8851. return IntRange(C.getIntWidth(QualType(T, 0)),
  8852. !ET->isSignedIntegerOrEnumerationType());
  8853. }
  8854. unsigned NumPositive = Enum->getNumPositiveBits();
  8855. unsigned NumNegative = Enum->getNumNegativeBits();
  8856. if (NumNegative == 0)
  8857. return IntRange(NumPositive, true/*NonNegative*/);
  8858. else
  8859. return IntRange(std::max(NumPositive + 1, NumNegative),
  8860. false/*NonNegative*/);
  8861. }
  8862. const BuiltinType *BT = cast<BuiltinType>(T);
  8863. assert(BT->isInteger());
  8864. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8865. }
  8866. /// Returns the "target" range of a canonical integral type, i.e.
  8867. /// the range of values expressible in the type.
  8868. ///
  8869. /// This matches forValueOfCanonicalType except that enums have the
  8870. /// full range of their type, not the range of their enumerators.
  8871. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  8872. assert(T->isCanonicalUnqualified());
  8873. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8874. T = VT->getElementType().getTypePtr();
  8875. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8876. T = CT->getElementType().getTypePtr();
  8877. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8878. T = AT->getValueType().getTypePtr();
  8879. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8880. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  8881. const BuiltinType *BT = cast<BuiltinType>(T);
  8882. assert(BT->isInteger());
  8883. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8884. }
  8885. /// Returns the supremum of two ranges: i.e. their conservative merge.
  8886. static IntRange join(IntRange L, IntRange R) {
  8887. return IntRange(std::max(L.Width, R.Width),
  8888. L.NonNegative && R.NonNegative);
  8889. }
  8890. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  8891. static IntRange meet(IntRange L, IntRange R) {
  8892. return IntRange(std::min(L.Width, R.Width),
  8893. L.NonNegative || R.NonNegative);
  8894. }
  8895. };
  8896. } // namespace
  8897. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  8898. unsigned MaxWidth) {
  8899. if (value.isSigned() && value.isNegative())
  8900. return IntRange(value.getMinSignedBits(), false);
  8901. if (value.getBitWidth() > MaxWidth)
  8902. value = value.trunc(MaxWidth);
  8903. // isNonNegative() just checks the sign bit without considering
  8904. // signedness.
  8905. return IntRange(value.getActiveBits(), true);
  8906. }
  8907. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  8908. unsigned MaxWidth) {
  8909. if (result.isInt())
  8910. return GetValueRange(C, result.getInt(), MaxWidth);
  8911. if (result.isVector()) {
  8912. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  8913. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  8914. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  8915. R = IntRange::join(R, El);
  8916. }
  8917. return R;
  8918. }
  8919. if (result.isComplexInt()) {
  8920. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  8921. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  8922. return IntRange::join(R, I);
  8923. }
  8924. // This can happen with lossless casts to intptr_t of "based" lvalues.
  8925. // Assume it might use arbitrary bits.
  8926. // FIXME: The only reason we need to pass the type in here is to get
  8927. // the sign right on this one case. It would be nice if APValue
  8928. // preserved this.
  8929. assert(result.isLValue() || result.isAddrLabelDiff());
  8930. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  8931. }
  8932. static QualType GetExprType(const Expr *E) {
  8933. QualType Ty = E->getType();
  8934. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  8935. Ty = AtomicRHS->getValueType();
  8936. return Ty;
  8937. }
  8938. /// Pseudo-evaluate the given integer expression, estimating the
  8939. /// range of values it might take.
  8940. ///
  8941. /// \param MaxWidth - the width to which the value will be truncated
  8942. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
  8943. bool InConstantContext) {
  8944. E = E->IgnoreParens();
  8945. // Try a full evaluation first.
  8946. Expr::EvalResult result;
  8947. if (E->EvaluateAsRValue(result, C, InConstantContext))
  8948. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  8949. // I think we only want to look through implicit casts here; if the
  8950. // user has an explicit widening cast, we should treat the value as
  8951. // being of the new, wider type.
  8952. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  8953. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  8954. return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
  8955. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  8956. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  8957. CE->getCastKind() == CK_BooleanToSignedIntegral;
  8958. // Assume that non-integer casts can span the full range of the type.
  8959. if (!isIntegerCast)
  8960. return OutputTypeRange;
  8961. IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
  8962. std::min(MaxWidth, OutputTypeRange.Width),
  8963. InConstantContext);
  8964. // Bail out if the subexpr's range is as wide as the cast type.
  8965. if (SubRange.Width >= OutputTypeRange.Width)
  8966. return OutputTypeRange;
  8967. // Otherwise, we take the smaller width, and we're non-negative if
  8968. // either the output type or the subexpr is.
  8969. return IntRange(SubRange.Width,
  8970. SubRange.NonNegative || OutputTypeRange.NonNegative);
  8971. }
  8972. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  8973. // If we can fold the condition, just take that operand.
  8974. bool CondResult;
  8975. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  8976. return GetExprRange(C,
  8977. CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
  8978. MaxWidth, InConstantContext);
  8979. // Otherwise, conservatively merge.
  8980. IntRange L =
  8981. GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
  8982. IntRange R =
  8983. GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
  8984. return IntRange::join(L, R);
  8985. }
  8986. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  8987. switch (BO->getOpcode()) {
  8988. case BO_Cmp:
  8989. llvm_unreachable("builtin <=> should have class type");
  8990. // Boolean-valued operations are single-bit and positive.
  8991. case BO_LAnd:
  8992. case BO_LOr:
  8993. case BO_LT:
  8994. case BO_GT:
  8995. case BO_LE:
  8996. case BO_GE:
  8997. case BO_EQ:
  8998. case BO_NE:
  8999. return IntRange::forBoolType();
  9000. // The type of the assignments is the type of the LHS, so the RHS
  9001. // is not necessarily the same type.
  9002. case BO_MulAssign:
  9003. case BO_DivAssign:
  9004. case BO_RemAssign:
  9005. case BO_AddAssign:
  9006. case BO_SubAssign:
  9007. case BO_XorAssign:
  9008. case BO_OrAssign:
  9009. // TODO: bitfields?
  9010. return IntRange::forValueOfType(C, GetExprType(E));
  9011. // Simple assignments just pass through the RHS, which will have
  9012. // been coerced to the LHS type.
  9013. case BO_Assign:
  9014. // TODO: bitfields?
  9015. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  9016. // Operations with opaque sources are black-listed.
  9017. case BO_PtrMemD:
  9018. case BO_PtrMemI:
  9019. return IntRange::forValueOfType(C, GetExprType(E));
  9020. // Bitwise-and uses the *infinum* of the two source ranges.
  9021. case BO_And:
  9022. case BO_AndAssign:
  9023. return IntRange::meet(
  9024. GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
  9025. GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
  9026. // Left shift gets black-listed based on a judgement call.
  9027. case BO_Shl:
  9028. // ...except that we want to treat '1 << (blah)' as logically
  9029. // positive. It's an important idiom.
  9030. if (IntegerLiteral *I
  9031. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  9032. if (I->getValue() == 1) {
  9033. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  9034. return IntRange(R.Width, /*NonNegative*/ true);
  9035. }
  9036. }
  9037. LLVM_FALLTHROUGH;
  9038. case BO_ShlAssign:
  9039. return IntRange::forValueOfType(C, GetExprType(E));
  9040. // Right shift by a constant can narrow its left argument.
  9041. case BO_Shr:
  9042. case BO_ShrAssign: {
  9043. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
  9044. // If the shift amount is a positive constant, drop the width by
  9045. // that much.
  9046. llvm::APSInt shift;
  9047. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  9048. shift.isNonNegative()) {
  9049. unsigned zext = shift.getZExtValue();
  9050. if (zext >= L.Width)
  9051. L.Width = (L.NonNegative ? 0 : 1);
  9052. else
  9053. L.Width -= zext;
  9054. }
  9055. return L;
  9056. }
  9057. // Comma acts as its right operand.
  9058. case BO_Comma:
  9059. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  9060. // Black-list pointer subtractions.
  9061. case BO_Sub:
  9062. if (BO->getLHS()->getType()->isPointerType())
  9063. return IntRange::forValueOfType(C, GetExprType(E));
  9064. break;
  9065. // The width of a division result is mostly determined by the size
  9066. // of the LHS.
  9067. case BO_Div: {
  9068. // Don't 'pre-truncate' the operands.
  9069. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9070. IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
  9071. // If the divisor is constant, use that.
  9072. llvm::APSInt divisor;
  9073. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  9074. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  9075. if (log2 >= L.Width)
  9076. L.Width = (L.NonNegative ? 0 : 1);
  9077. else
  9078. L.Width = std::min(L.Width - log2, MaxWidth);
  9079. return L;
  9080. }
  9081. // Otherwise, just use the LHS's width.
  9082. IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
  9083. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  9084. }
  9085. // The result of a remainder can't be larger than the result of
  9086. // either side.
  9087. case BO_Rem: {
  9088. // Don't 'pre-truncate' the operands.
  9089. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9090. IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
  9091. IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
  9092. IntRange meet = IntRange::meet(L, R);
  9093. meet.Width = std::min(meet.Width, MaxWidth);
  9094. return meet;
  9095. }
  9096. // The default behavior is okay for these.
  9097. case BO_Mul:
  9098. case BO_Add:
  9099. case BO_Xor:
  9100. case BO_Or:
  9101. break;
  9102. }
  9103. // The default case is to treat the operation as if it were closed
  9104. // on the narrowest type that encompasses both operands.
  9105. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
  9106. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  9107. return IntRange::join(L, R);
  9108. }
  9109. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  9110. switch (UO->getOpcode()) {
  9111. // Boolean-valued operations are white-listed.
  9112. case UO_LNot:
  9113. return IntRange::forBoolType();
  9114. // Operations with opaque sources are black-listed.
  9115. case UO_Deref:
  9116. case UO_AddrOf: // should be impossible
  9117. return IntRange::forValueOfType(C, GetExprType(E));
  9118. default:
  9119. return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
  9120. }
  9121. }
  9122. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  9123. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
  9124. if (const auto *BitField = E->getSourceBitField())
  9125. return IntRange(BitField->getBitWidthValue(C),
  9126. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  9127. return IntRange::forValueOfType(C, GetExprType(E));
  9128. }
  9129. static IntRange GetExprRange(ASTContext &C, const Expr *E,
  9130. bool InConstantContext) {
  9131. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
  9132. }
  9133. /// Checks whether the given value, which currently has the given
  9134. /// source semantics, has the same value when coerced through the
  9135. /// target semantics.
  9136. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  9137. const llvm::fltSemantics &Src,
  9138. const llvm::fltSemantics &Tgt) {
  9139. llvm::APFloat truncated = value;
  9140. bool ignored;
  9141. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9142. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9143. return truncated.bitwiseIsEqual(value);
  9144. }
  9145. /// Checks whether the given value, which currently has the given
  9146. /// source semantics, has the same value when coerced through the
  9147. /// target semantics.
  9148. ///
  9149. /// The value might be a vector of floats (or a complex number).
  9150. static bool IsSameFloatAfterCast(const APValue &value,
  9151. const llvm::fltSemantics &Src,
  9152. const llvm::fltSemantics &Tgt) {
  9153. if (value.isFloat())
  9154. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  9155. if (value.isVector()) {
  9156. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  9157. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  9158. return false;
  9159. return true;
  9160. }
  9161. assert(value.isComplexFloat());
  9162. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  9163. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  9164. }
  9165. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
  9166. bool IsListInit = false);
  9167. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  9168. // Suppress cases where we are comparing against an enum constant.
  9169. if (const DeclRefExpr *DR =
  9170. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  9171. if (isa<EnumConstantDecl>(DR->getDecl()))
  9172. return true;
  9173. // Suppress cases where the value is expanded from a macro, unless that macro
  9174. // is how a language represents a boolean literal. This is the case in both C
  9175. // and Objective-C.
  9176. SourceLocation BeginLoc = E->getBeginLoc();
  9177. if (BeginLoc.isMacroID()) {
  9178. StringRef MacroName = Lexer::getImmediateMacroName(
  9179. BeginLoc, S.getSourceManager(), S.getLangOpts());
  9180. return MacroName != "YES" && MacroName != "NO" &&
  9181. MacroName != "true" && MacroName != "false";
  9182. }
  9183. return false;
  9184. }
  9185. static bool isKnownToHaveUnsignedValue(Expr *E) {
  9186. return E->getType()->isIntegerType() &&
  9187. (!E->getType()->isSignedIntegerType() ||
  9188. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  9189. }
  9190. namespace {
  9191. /// The promoted range of values of a type. In general this has the
  9192. /// following structure:
  9193. ///
  9194. /// |-----------| . . . |-----------|
  9195. /// ^ ^ ^ ^
  9196. /// Min HoleMin HoleMax Max
  9197. ///
  9198. /// ... where there is only a hole if a signed type is promoted to unsigned
  9199. /// (in which case Min and Max are the smallest and largest representable
  9200. /// values).
  9201. struct PromotedRange {
  9202. // Min, or HoleMax if there is a hole.
  9203. llvm::APSInt PromotedMin;
  9204. // Max, or HoleMin if there is a hole.
  9205. llvm::APSInt PromotedMax;
  9206. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  9207. if (R.Width == 0)
  9208. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  9209. else if (R.Width >= BitWidth && !Unsigned) {
  9210. // Promotion made the type *narrower*. This happens when promoting
  9211. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  9212. // Treat all values of 'signed int' as being in range for now.
  9213. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  9214. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  9215. } else {
  9216. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  9217. .extOrTrunc(BitWidth);
  9218. PromotedMin.setIsUnsigned(Unsigned);
  9219. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  9220. .extOrTrunc(BitWidth);
  9221. PromotedMax.setIsUnsigned(Unsigned);
  9222. }
  9223. }
  9224. // Determine whether this range is contiguous (has no hole).
  9225. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  9226. // Where a constant value is within the range.
  9227. enum ComparisonResult {
  9228. LT = 0x1,
  9229. LE = 0x2,
  9230. GT = 0x4,
  9231. GE = 0x8,
  9232. EQ = 0x10,
  9233. NE = 0x20,
  9234. InRangeFlag = 0x40,
  9235. Less = LE | LT | NE,
  9236. Min = LE | InRangeFlag,
  9237. InRange = InRangeFlag,
  9238. Max = GE | InRangeFlag,
  9239. Greater = GE | GT | NE,
  9240. OnlyValue = LE | GE | EQ | InRangeFlag,
  9241. InHole = NE
  9242. };
  9243. ComparisonResult compare(const llvm::APSInt &Value) const {
  9244. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  9245. Value.isUnsigned() == PromotedMin.isUnsigned());
  9246. if (!isContiguous()) {
  9247. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  9248. if (Value.isMinValue()) return Min;
  9249. if (Value.isMaxValue()) return Max;
  9250. if (Value >= PromotedMin) return InRange;
  9251. if (Value <= PromotedMax) return InRange;
  9252. return InHole;
  9253. }
  9254. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  9255. case -1: return Less;
  9256. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  9257. case 1:
  9258. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  9259. case -1: return InRange;
  9260. case 0: return Max;
  9261. case 1: return Greater;
  9262. }
  9263. }
  9264. llvm_unreachable("impossible compare result");
  9265. }
  9266. static llvm::Optional<StringRef>
  9267. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  9268. if (Op == BO_Cmp) {
  9269. ComparisonResult LTFlag = LT, GTFlag = GT;
  9270. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  9271. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  9272. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  9273. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  9274. return llvm::None;
  9275. }
  9276. ComparisonResult TrueFlag, FalseFlag;
  9277. if (Op == BO_EQ) {
  9278. TrueFlag = EQ;
  9279. FalseFlag = NE;
  9280. } else if (Op == BO_NE) {
  9281. TrueFlag = NE;
  9282. FalseFlag = EQ;
  9283. } else {
  9284. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  9285. TrueFlag = LT;
  9286. FalseFlag = GE;
  9287. } else {
  9288. TrueFlag = GT;
  9289. FalseFlag = LE;
  9290. }
  9291. if (Op == BO_GE || Op == BO_LE)
  9292. std::swap(TrueFlag, FalseFlag);
  9293. }
  9294. if (R & TrueFlag)
  9295. return StringRef("true");
  9296. if (R & FalseFlag)
  9297. return StringRef("false");
  9298. return llvm::None;
  9299. }
  9300. };
  9301. }
  9302. static bool HasEnumType(Expr *E) {
  9303. // Strip off implicit integral promotions.
  9304. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  9305. if (ICE->getCastKind() != CK_IntegralCast &&
  9306. ICE->getCastKind() != CK_NoOp)
  9307. break;
  9308. E = ICE->getSubExpr();
  9309. }
  9310. return E->getType()->isEnumeralType();
  9311. }
  9312. static int classifyConstantValue(Expr *Constant) {
  9313. // The values of this enumeration are used in the diagnostics
  9314. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  9315. enum ConstantValueKind {
  9316. Miscellaneous = 0,
  9317. LiteralTrue,
  9318. LiteralFalse
  9319. };
  9320. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  9321. return BL->getValue() ? ConstantValueKind::LiteralTrue
  9322. : ConstantValueKind::LiteralFalse;
  9323. return ConstantValueKind::Miscellaneous;
  9324. }
  9325. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  9326. Expr *Constant, Expr *Other,
  9327. const llvm::APSInt &Value,
  9328. bool RhsConstant) {
  9329. if (S.inTemplateInstantiation())
  9330. return false;
  9331. Expr *OriginalOther = Other;
  9332. Constant = Constant->IgnoreParenImpCasts();
  9333. Other = Other->IgnoreParenImpCasts();
  9334. // Suppress warnings on tautological comparisons between values of the same
  9335. // enumeration type. There are only two ways we could warn on this:
  9336. // - If the constant is outside the range of representable values of
  9337. // the enumeration. In such a case, we should warn about the cast
  9338. // to enumeration type, not about the comparison.
  9339. // - If the constant is the maximum / minimum in-range value. For an
  9340. // enumeratin type, such comparisons can be meaningful and useful.
  9341. if (Constant->getType()->isEnumeralType() &&
  9342. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  9343. return false;
  9344. // TODO: Investigate using GetExprRange() to get tighter bounds
  9345. // on the bit ranges.
  9346. QualType OtherT = Other->getType();
  9347. if (const auto *AT = OtherT->getAs<AtomicType>())
  9348. OtherT = AT->getValueType();
  9349. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  9350. // Special case for ObjC BOOL on targets where its a typedef for a signed char
  9351. // (Namely, macOS).
  9352. bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
  9353. S.NSAPIObj->isObjCBOOLType(OtherT) &&
  9354. OtherT->isSpecificBuiltinType(BuiltinType::SChar);
  9355. // Whether we're treating Other as being a bool because of the form of
  9356. // expression despite it having another type (typically 'int' in C).
  9357. bool OtherIsBooleanDespiteType =
  9358. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  9359. if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
  9360. OtherRange = IntRange::forBoolType();
  9361. // Determine the promoted range of the other type and see if a comparison of
  9362. // the constant against that range is tautological.
  9363. PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
  9364. Value.isUnsigned());
  9365. auto Cmp = OtherPromotedRange.compare(Value);
  9366. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  9367. if (!Result)
  9368. return false;
  9369. // Suppress the diagnostic for an in-range comparison if the constant comes
  9370. // from a macro or enumerator. We don't want to diagnose
  9371. //
  9372. // some_long_value <= INT_MAX
  9373. //
  9374. // when sizeof(int) == sizeof(long).
  9375. bool InRange = Cmp & PromotedRange::InRangeFlag;
  9376. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  9377. return false;
  9378. // If this is a comparison to an enum constant, include that
  9379. // constant in the diagnostic.
  9380. const EnumConstantDecl *ED = nullptr;
  9381. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  9382. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  9383. // Should be enough for uint128 (39 decimal digits)
  9384. SmallString<64> PrettySourceValue;
  9385. llvm::raw_svector_ostream OS(PrettySourceValue);
  9386. if (ED) {
  9387. OS << '\'' << *ED << "' (" << Value << ")";
  9388. } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
  9389. Constant->IgnoreParenImpCasts())) {
  9390. OS << (BL->getValue() ? "YES" : "NO");
  9391. } else {
  9392. OS << Value;
  9393. }
  9394. if (IsObjCSignedCharBool) {
  9395. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9396. S.PDiag(diag::warn_tautological_compare_objc_bool)
  9397. << OS.str() << *Result);
  9398. return true;
  9399. }
  9400. // FIXME: We use a somewhat different formatting for the in-range cases and
  9401. // cases involving boolean values for historical reasons. We should pick a
  9402. // consistent way of presenting these diagnostics.
  9403. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  9404. S.DiagRuntimeBehavior(
  9405. E->getOperatorLoc(), E,
  9406. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  9407. : diag::warn_tautological_bool_compare)
  9408. << OS.str() << classifyConstantValue(Constant) << OtherT
  9409. << OtherIsBooleanDespiteType << *Result
  9410. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  9411. } else {
  9412. unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  9413. ? (HasEnumType(OriginalOther)
  9414. ? diag::warn_unsigned_enum_always_true_comparison
  9415. : diag::warn_unsigned_always_true_comparison)
  9416. : diag::warn_tautological_constant_compare;
  9417. S.Diag(E->getOperatorLoc(), Diag)
  9418. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  9419. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  9420. }
  9421. return true;
  9422. }
  9423. /// Analyze the operands of the given comparison. Implements the
  9424. /// fallback case from AnalyzeComparison.
  9425. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  9426. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9427. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9428. }
  9429. /// Implements -Wsign-compare.
  9430. ///
  9431. /// \param E the binary operator to check for warnings
  9432. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  9433. // The type the comparison is being performed in.
  9434. QualType T = E->getLHS()->getType();
  9435. // Only analyze comparison operators where both sides have been converted to
  9436. // the same type.
  9437. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  9438. return AnalyzeImpConvsInComparison(S, E);
  9439. // Don't analyze value-dependent comparisons directly.
  9440. if (E->isValueDependent())
  9441. return AnalyzeImpConvsInComparison(S, E);
  9442. Expr *LHS = E->getLHS();
  9443. Expr *RHS = E->getRHS();
  9444. if (T->isIntegralType(S.Context)) {
  9445. llvm::APSInt RHSValue;
  9446. llvm::APSInt LHSValue;
  9447. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  9448. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  9449. // We don't care about expressions whose result is a constant.
  9450. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  9451. return AnalyzeImpConvsInComparison(S, E);
  9452. // We only care about expressions where just one side is literal
  9453. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  9454. // Is the constant on the RHS or LHS?
  9455. const bool RhsConstant = IsRHSIntegralLiteral;
  9456. Expr *Const = RhsConstant ? RHS : LHS;
  9457. Expr *Other = RhsConstant ? LHS : RHS;
  9458. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  9459. // Check whether an integer constant comparison results in a value
  9460. // of 'true' or 'false'.
  9461. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  9462. return AnalyzeImpConvsInComparison(S, E);
  9463. }
  9464. }
  9465. if (!T->hasUnsignedIntegerRepresentation()) {
  9466. // We don't do anything special if this isn't an unsigned integral
  9467. // comparison: we're only interested in integral comparisons, and
  9468. // signed comparisons only happen in cases we don't care to warn about.
  9469. return AnalyzeImpConvsInComparison(S, E);
  9470. }
  9471. LHS = LHS->IgnoreParenImpCasts();
  9472. RHS = RHS->IgnoreParenImpCasts();
  9473. if (!S.getLangOpts().CPlusPlus) {
  9474. // Avoid warning about comparison of integers with different signs when
  9475. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  9476. // the type of `E`.
  9477. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  9478. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9479. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  9480. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9481. }
  9482. // Check to see if one of the (unmodified) operands is of different
  9483. // signedness.
  9484. Expr *signedOperand, *unsignedOperand;
  9485. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  9486. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  9487. "unsigned comparison between two signed integer expressions?");
  9488. signedOperand = LHS;
  9489. unsignedOperand = RHS;
  9490. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  9491. signedOperand = RHS;
  9492. unsignedOperand = LHS;
  9493. } else {
  9494. return AnalyzeImpConvsInComparison(S, E);
  9495. }
  9496. // Otherwise, calculate the effective range of the signed operand.
  9497. IntRange signedRange =
  9498. GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
  9499. // Go ahead and analyze implicit conversions in the operands. Note
  9500. // that we skip the implicit conversions on both sides.
  9501. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  9502. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  9503. // If the signed range is non-negative, -Wsign-compare won't fire.
  9504. if (signedRange.NonNegative)
  9505. return;
  9506. // For (in)equality comparisons, if the unsigned operand is a
  9507. // constant which cannot collide with a overflowed signed operand,
  9508. // then reinterpreting the signed operand as unsigned will not
  9509. // change the result of the comparison.
  9510. if (E->isEqualityOp()) {
  9511. unsigned comparisonWidth = S.Context.getIntWidth(T);
  9512. IntRange unsignedRange =
  9513. GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
  9514. // We should never be unable to prove that the unsigned operand is
  9515. // non-negative.
  9516. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  9517. if (unsignedRange.Width < comparisonWidth)
  9518. return;
  9519. }
  9520. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9521. S.PDiag(diag::warn_mixed_sign_comparison)
  9522. << LHS->getType() << RHS->getType()
  9523. << LHS->getSourceRange() << RHS->getSourceRange());
  9524. }
  9525. /// Analyzes an attempt to assign the given value to a bitfield.
  9526. ///
  9527. /// Returns true if there was something fishy about the attempt.
  9528. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  9529. SourceLocation InitLoc) {
  9530. assert(Bitfield->isBitField());
  9531. if (Bitfield->isInvalidDecl())
  9532. return false;
  9533. // White-list bool bitfields.
  9534. QualType BitfieldType = Bitfield->getType();
  9535. if (BitfieldType->isBooleanType())
  9536. return false;
  9537. if (BitfieldType->isEnumeralType()) {
  9538. EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
  9539. // If the underlying enum type was not explicitly specified as an unsigned
  9540. // type and the enum contain only positive values, MSVC++ will cause an
  9541. // inconsistency by storing this as a signed type.
  9542. if (S.getLangOpts().CPlusPlus11 &&
  9543. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  9544. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  9545. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  9546. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  9547. << BitfieldEnumDecl->getNameAsString();
  9548. }
  9549. }
  9550. if (Bitfield->getType()->isBooleanType())
  9551. return false;
  9552. // Ignore value- or type-dependent expressions.
  9553. if (Bitfield->getBitWidth()->isValueDependent() ||
  9554. Bitfield->getBitWidth()->isTypeDependent() ||
  9555. Init->isValueDependent() ||
  9556. Init->isTypeDependent())
  9557. return false;
  9558. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  9559. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  9560. Expr::EvalResult Result;
  9561. if (!OriginalInit->EvaluateAsInt(Result, S.Context,
  9562. Expr::SE_AllowSideEffects)) {
  9563. // The RHS is not constant. If the RHS has an enum type, make sure the
  9564. // bitfield is wide enough to hold all the values of the enum without
  9565. // truncation.
  9566. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  9567. EnumDecl *ED = EnumTy->getDecl();
  9568. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  9569. // Enum types are implicitly signed on Windows, so check if there are any
  9570. // negative enumerators to see if the enum was intended to be signed or
  9571. // not.
  9572. bool SignedEnum = ED->getNumNegativeBits() > 0;
  9573. // Check for surprising sign changes when assigning enum values to a
  9574. // bitfield of different signedness. If the bitfield is signed and we
  9575. // have exactly the right number of bits to store this unsigned enum,
  9576. // suggest changing the enum to an unsigned type. This typically happens
  9577. // on Windows where unfixed enums always use an underlying type of 'int'.
  9578. unsigned DiagID = 0;
  9579. if (SignedEnum && !SignedBitfield) {
  9580. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  9581. } else if (SignedBitfield && !SignedEnum &&
  9582. ED->getNumPositiveBits() == FieldWidth) {
  9583. DiagID = diag::warn_signed_bitfield_enum_conversion;
  9584. }
  9585. if (DiagID) {
  9586. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  9587. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  9588. SourceRange TypeRange =
  9589. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  9590. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  9591. << SignedEnum << TypeRange;
  9592. }
  9593. // Compute the required bitwidth. If the enum has negative values, we need
  9594. // one more bit than the normal number of positive bits to represent the
  9595. // sign bit.
  9596. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  9597. ED->getNumNegativeBits())
  9598. : ED->getNumPositiveBits();
  9599. // Check the bitwidth.
  9600. if (BitsNeeded > FieldWidth) {
  9601. Expr *WidthExpr = Bitfield->getBitWidth();
  9602. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  9603. << Bitfield << ED;
  9604. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  9605. << BitsNeeded << ED << WidthExpr->getSourceRange();
  9606. }
  9607. }
  9608. return false;
  9609. }
  9610. llvm::APSInt Value = Result.Val.getInt();
  9611. unsigned OriginalWidth = Value.getBitWidth();
  9612. if (!Value.isSigned() || Value.isNegative())
  9613. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  9614. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  9615. OriginalWidth = Value.getMinSignedBits();
  9616. if (OriginalWidth <= FieldWidth)
  9617. return false;
  9618. // Compute the value which the bitfield will contain.
  9619. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  9620. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  9621. // Check whether the stored value is equal to the original value.
  9622. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  9623. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  9624. return false;
  9625. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  9626. // therefore don't strictly fit into a signed bitfield of width 1.
  9627. if (FieldWidth == 1 && Value == 1)
  9628. return false;
  9629. std::string PrettyValue = Value.toString(10);
  9630. std::string PrettyTrunc = TruncatedValue.toString(10);
  9631. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  9632. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  9633. << Init->getSourceRange();
  9634. return true;
  9635. }
  9636. /// Analyze the given simple or compound assignment for warning-worthy
  9637. /// operations.
  9638. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  9639. // Just recurse on the LHS.
  9640. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9641. // We want to recurse on the RHS as normal unless we're assigning to
  9642. // a bitfield.
  9643. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  9644. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  9645. E->getOperatorLoc())) {
  9646. // Recurse, ignoring any implicit conversions on the RHS.
  9647. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  9648. E->getOperatorLoc());
  9649. }
  9650. }
  9651. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9652. // Diagnose implicitly sequentially-consistent atomic assignment.
  9653. if (E->getLHS()->getType()->isAtomicType())
  9654. S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  9655. }
  9656. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9657. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  9658. SourceLocation CContext, unsigned diag,
  9659. bool pruneControlFlow = false) {
  9660. if (pruneControlFlow) {
  9661. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9662. S.PDiag(diag)
  9663. << SourceType << T << E->getSourceRange()
  9664. << SourceRange(CContext));
  9665. return;
  9666. }
  9667. S.Diag(E->getExprLoc(), diag)
  9668. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  9669. }
  9670. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9671. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  9672. SourceLocation CContext,
  9673. unsigned diag, bool pruneControlFlow = false) {
  9674. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  9675. }
  9676. /// Diagnose an implicit cast from a floating point value to an integer value.
  9677. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  9678. SourceLocation CContext) {
  9679. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  9680. const bool PruneWarnings = S.inTemplateInstantiation();
  9681. Expr *InnerE = E->IgnoreParenImpCasts();
  9682. // We also want to warn on, e.g., "int i = -1.234"
  9683. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  9684. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  9685. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  9686. const bool IsLiteral =
  9687. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  9688. llvm::APFloat Value(0.0);
  9689. bool IsConstant =
  9690. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  9691. if (!IsConstant) {
  9692. return DiagnoseImpCast(S, E, T, CContext,
  9693. diag::warn_impcast_float_integer, PruneWarnings);
  9694. }
  9695. bool isExact = false;
  9696. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  9697. T->hasUnsignedIntegerRepresentation());
  9698. llvm::APFloat::opStatus Result = Value.convertToInteger(
  9699. IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
  9700. if (Result == llvm::APFloat::opOK && isExact) {
  9701. if (IsLiteral) return;
  9702. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  9703. PruneWarnings);
  9704. }
  9705. // Conversion of a floating-point value to a non-bool integer where the
  9706. // integral part cannot be represented by the integer type is undefined.
  9707. if (!IsBool && Result == llvm::APFloat::opInvalidOp)
  9708. return DiagnoseImpCast(
  9709. S, E, T, CContext,
  9710. IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
  9711. : diag::warn_impcast_float_to_integer_out_of_range,
  9712. PruneWarnings);
  9713. unsigned DiagID = 0;
  9714. if (IsLiteral) {
  9715. // Warn on floating point literal to integer.
  9716. DiagID = diag::warn_impcast_literal_float_to_integer;
  9717. } else if (IntegerValue == 0) {
  9718. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  9719. return DiagnoseImpCast(S, E, T, CContext,
  9720. diag::warn_impcast_float_integer, PruneWarnings);
  9721. }
  9722. // Warn on non-zero to zero conversion.
  9723. DiagID = diag::warn_impcast_float_to_integer_zero;
  9724. } else {
  9725. if (IntegerValue.isUnsigned()) {
  9726. if (!IntegerValue.isMaxValue()) {
  9727. return DiagnoseImpCast(S, E, T, CContext,
  9728. diag::warn_impcast_float_integer, PruneWarnings);
  9729. }
  9730. } else { // IntegerValue.isSigned()
  9731. if (!IntegerValue.isMaxSignedValue() &&
  9732. !IntegerValue.isMinSignedValue()) {
  9733. return DiagnoseImpCast(S, E, T, CContext,
  9734. diag::warn_impcast_float_integer, PruneWarnings);
  9735. }
  9736. }
  9737. // Warn on evaluatable floating point expression to integer conversion.
  9738. DiagID = diag::warn_impcast_float_to_integer;
  9739. }
  9740. // FIXME: Force the precision of the source value down so we don't print
  9741. // digits which are usually useless (we don't really care here if we
  9742. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  9743. // would automatically print the shortest representation, but it's a bit
  9744. // tricky to implement.
  9745. SmallString<16> PrettySourceValue;
  9746. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  9747. precision = (precision * 59 + 195) / 196;
  9748. Value.toString(PrettySourceValue, precision);
  9749. SmallString<16> PrettyTargetValue;
  9750. if (IsBool)
  9751. PrettyTargetValue = Value.isZero() ? "false" : "true";
  9752. else
  9753. IntegerValue.toString(PrettyTargetValue);
  9754. if (PruneWarnings) {
  9755. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9756. S.PDiag(DiagID)
  9757. << E->getType() << T.getUnqualifiedType()
  9758. << PrettySourceValue << PrettyTargetValue
  9759. << E->getSourceRange() << SourceRange(CContext));
  9760. } else {
  9761. S.Diag(E->getExprLoc(), DiagID)
  9762. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  9763. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  9764. }
  9765. }
  9766. /// Analyze the given compound assignment for the possible losing of
  9767. /// floating-point precision.
  9768. static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
  9769. assert(isa<CompoundAssignOperator>(E) &&
  9770. "Must be compound assignment operation");
  9771. // Recurse on the LHS and RHS in here
  9772. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9773. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9774. if (E->getLHS()->getType()->isAtomicType())
  9775. S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
  9776. // Now check the outermost expression
  9777. const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
  9778. const auto *RBT = cast<CompoundAssignOperator>(E)
  9779. ->getComputationResultType()
  9780. ->getAs<BuiltinType>();
  9781. // The below checks assume source is floating point.
  9782. if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
  9783. // If source is floating point but target is an integer.
  9784. if (ResultBT->isInteger())
  9785. return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
  9786. E->getExprLoc(), diag::warn_impcast_float_integer);
  9787. if (!ResultBT->isFloatingPoint())
  9788. return;
  9789. // If both source and target are floating points, warn about losing precision.
  9790. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  9791. QualType(ResultBT, 0), QualType(RBT, 0));
  9792. if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
  9793. // warn about dropping FP rank.
  9794. DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
  9795. diag::warn_impcast_float_result_precision);
  9796. }
  9797. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  9798. IntRange Range) {
  9799. if (!Range.Width) return "0";
  9800. llvm::APSInt ValueInRange = Value;
  9801. ValueInRange.setIsSigned(!Range.NonNegative);
  9802. ValueInRange = ValueInRange.trunc(Range.Width);
  9803. return ValueInRange.toString(10);
  9804. }
  9805. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  9806. if (!isa<ImplicitCastExpr>(Ex))
  9807. return false;
  9808. Expr *InnerE = Ex->IgnoreParenImpCasts();
  9809. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  9810. const Type *Source =
  9811. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  9812. if (Target->isDependentType())
  9813. return false;
  9814. const BuiltinType *FloatCandidateBT =
  9815. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  9816. const Type *BoolCandidateType = ToBool ? Target : Source;
  9817. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  9818. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  9819. }
  9820. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  9821. SourceLocation CC) {
  9822. unsigned NumArgs = TheCall->getNumArgs();
  9823. for (unsigned i = 0; i < NumArgs; ++i) {
  9824. Expr *CurrA = TheCall->getArg(i);
  9825. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  9826. continue;
  9827. bool IsSwapped = ((i > 0) &&
  9828. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  9829. IsSwapped |= ((i < (NumArgs - 1)) &&
  9830. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  9831. if (IsSwapped) {
  9832. // Warn on this floating-point to bool conversion.
  9833. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  9834. CurrA->getType(), CC,
  9835. diag::warn_impcast_floating_point_to_bool);
  9836. }
  9837. }
  9838. }
  9839. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  9840. SourceLocation CC) {
  9841. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  9842. E->getExprLoc()))
  9843. return;
  9844. // Don't warn on functions which have return type nullptr_t.
  9845. if (isa<CallExpr>(E))
  9846. return;
  9847. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  9848. const Expr::NullPointerConstantKind NullKind =
  9849. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  9850. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  9851. return;
  9852. // Return if target type is a safe conversion.
  9853. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  9854. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  9855. return;
  9856. SourceLocation Loc = E->getSourceRange().getBegin();
  9857. // Venture through the macro stacks to get to the source of macro arguments.
  9858. // The new location is a better location than the complete location that was
  9859. // passed in.
  9860. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  9861. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  9862. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  9863. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  9864. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  9865. Loc, S.SourceMgr, S.getLangOpts());
  9866. if (MacroName == "NULL")
  9867. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
  9868. }
  9869. // Only warn if the null and context location are in the same macro expansion.
  9870. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  9871. return;
  9872. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  9873. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  9874. << FixItHint::CreateReplacement(Loc,
  9875. S.getFixItZeroLiteralForType(T, Loc));
  9876. }
  9877. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9878. ObjCArrayLiteral *ArrayLiteral);
  9879. static void
  9880. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9881. ObjCDictionaryLiteral *DictionaryLiteral);
  9882. /// Check a single element within a collection literal against the
  9883. /// target element type.
  9884. static void checkObjCCollectionLiteralElement(Sema &S,
  9885. QualType TargetElementType,
  9886. Expr *Element,
  9887. unsigned ElementKind) {
  9888. // Skip a bitcast to 'id' or qualified 'id'.
  9889. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  9890. if (ICE->getCastKind() == CK_BitCast &&
  9891. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  9892. Element = ICE->getSubExpr();
  9893. }
  9894. QualType ElementType = Element->getType();
  9895. ExprResult ElementResult(Element);
  9896. if (ElementType->getAs<ObjCObjectPointerType>() &&
  9897. S.CheckSingleAssignmentConstraints(TargetElementType,
  9898. ElementResult,
  9899. false, false)
  9900. != Sema::Compatible) {
  9901. S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
  9902. << ElementType << ElementKind << TargetElementType
  9903. << Element->getSourceRange();
  9904. }
  9905. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  9906. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  9907. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  9908. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  9909. }
  9910. /// Check an Objective-C array literal being converted to the given
  9911. /// target type.
  9912. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9913. ObjCArrayLiteral *ArrayLiteral) {
  9914. if (!S.NSArrayDecl)
  9915. return;
  9916. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9917. if (!TargetObjCPtr)
  9918. return;
  9919. if (TargetObjCPtr->isUnspecialized() ||
  9920. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9921. != S.NSArrayDecl->getCanonicalDecl())
  9922. return;
  9923. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9924. if (TypeArgs.size() != 1)
  9925. return;
  9926. QualType TargetElementType = TypeArgs[0];
  9927. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  9928. checkObjCCollectionLiteralElement(S, TargetElementType,
  9929. ArrayLiteral->getElement(I),
  9930. 0);
  9931. }
  9932. }
  9933. /// Check an Objective-C dictionary literal being converted to the given
  9934. /// target type.
  9935. static void
  9936. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9937. ObjCDictionaryLiteral *DictionaryLiteral) {
  9938. if (!S.NSDictionaryDecl)
  9939. return;
  9940. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9941. if (!TargetObjCPtr)
  9942. return;
  9943. if (TargetObjCPtr->isUnspecialized() ||
  9944. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9945. != S.NSDictionaryDecl->getCanonicalDecl())
  9946. return;
  9947. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9948. if (TypeArgs.size() != 2)
  9949. return;
  9950. QualType TargetKeyType = TypeArgs[0];
  9951. QualType TargetObjectType = TypeArgs[1];
  9952. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  9953. auto Element = DictionaryLiteral->getKeyValueElement(I);
  9954. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  9955. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  9956. }
  9957. }
  9958. // Helper function to filter out cases for constant width constant conversion.
  9959. // Don't warn on char array initialization or for non-decimal values.
  9960. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  9961. SourceLocation CC) {
  9962. // If initializing from a constant, and the constant starts with '0',
  9963. // then it is a binary, octal, or hexadecimal. Allow these constants
  9964. // to fill all the bits, even if there is a sign change.
  9965. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  9966. const char FirstLiteralCharacter =
  9967. S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
  9968. if (FirstLiteralCharacter == '0')
  9969. return false;
  9970. }
  9971. // If the CC location points to a '{', and the type is char, then assume
  9972. // assume it is an array initialization.
  9973. if (CC.isValid() && T->isCharType()) {
  9974. const char FirstContextCharacter =
  9975. S.getSourceManager().getCharacterData(CC)[0];
  9976. if (FirstContextCharacter == '{')
  9977. return false;
  9978. }
  9979. return true;
  9980. }
  9981. static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
  9982. return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
  9983. S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
  9984. }
  9985. static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  9986. SourceLocation CC,
  9987. bool *ICContext = nullptr,
  9988. bool IsListInit = false) {
  9989. if (E->isTypeDependent() || E->isValueDependent()) return;
  9990. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  9991. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  9992. if (Source == Target) return;
  9993. if (Target->isDependentType()) return;
  9994. // If the conversion context location is invalid don't complain. We also
  9995. // don't want to emit a warning if the issue occurs from the expansion of
  9996. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  9997. // delay this check as long as possible. Once we detect we are in that
  9998. // scenario, we just return.
  9999. if (CC.isInvalid())
  10000. return;
  10001. if (Source->isAtomicType())
  10002. S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
  10003. // Diagnose implicit casts to bool.
  10004. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  10005. if (isa<StringLiteral>(E))
  10006. // Warn on string literal to bool. Checks for string literals in logical
  10007. // and expressions, for instance, assert(0 && "error here"), are
  10008. // prevented by a check in AnalyzeImplicitConversions().
  10009. return DiagnoseImpCast(S, E, T, CC,
  10010. diag::warn_impcast_string_literal_to_bool);
  10011. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  10012. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  10013. // This covers the literal expressions that evaluate to Objective-C
  10014. // objects.
  10015. return DiagnoseImpCast(S, E, T, CC,
  10016. diag::warn_impcast_objective_c_literal_to_bool);
  10017. }
  10018. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  10019. // Warn on pointer to bool conversion that is always true.
  10020. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  10021. SourceRange(CC));
  10022. }
  10023. }
  10024. // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
  10025. // is a typedef for signed char (macOS), then that constant value has to be 1
  10026. // or 0.
  10027. if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
  10028. Expr::EvalResult Result;
  10029. if (E->EvaluateAsInt(Result, S.getASTContext(),
  10030. Expr::SE_AllowSideEffects) &&
  10031. Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
  10032. auto Builder = S.Diag(CC, diag::warn_impcast_constant_int_to_objc_bool)
  10033. << Result.Val.getInt().toString(10);
  10034. Expr *Ignored = E->IgnoreImplicit();
  10035. bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
  10036. isa<BinaryOperator>(Ignored) ||
  10037. isa<CXXOperatorCallExpr>(Ignored);
  10038. SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
  10039. if (NeedsParens)
  10040. Builder << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
  10041. << FixItHint::CreateInsertion(EndLoc, ")");
  10042. Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
  10043. return;
  10044. }
  10045. }
  10046. // Check implicit casts from Objective-C collection literals to specialized
  10047. // collection types, e.g., NSArray<NSString *> *.
  10048. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  10049. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  10050. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  10051. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  10052. // Strip vector types.
  10053. if (isa<VectorType>(Source)) {
  10054. if (!isa<VectorType>(Target)) {
  10055. if (S.SourceMgr.isInSystemMacro(CC))
  10056. return;
  10057. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  10058. }
  10059. // If the vector cast is cast between two vectors of the same size, it is
  10060. // a bitcast, not a conversion.
  10061. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  10062. return;
  10063. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  10064. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  10065. }
  10066. if (auto VecTy = dyn_cast<VectorType>(Target))
  10067. Target = VecTy->getElementType().getTypePtr();
  10068. // Strip complex types.
  10069. if (isa<ComplexType>(Source)) {
  10070. if (!isa<ComplexType>(Target)) {
  10071. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  10072. return;
  10073. return DiagnoseImpCast(S, E, T, CC,
  10074. S.getLangOpts().CPlusPlus
  10075. ? diag::err_impcast_complex_scalar
  10076. : diag::warn_impcast_complex_scalar);
  10077. }
  10078. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  10079. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  10080. }
  10081. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  10082. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  10083. // If the source is floating point...
  10084. if (SourceBT && SourceBT->isFloatingPoint()) {
  10085. // ...and the target is floating point...
  10086. if (TargetBT && TargetBT->isFloatingPoint()) {
  10087. // ...then warn if we're dropping FP rank.
  10088. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  10089. QualType(SourceBT, 0), QualType(TargetBT, 0));
  10090. if (Order > 0) {
  10091. // Don't warn about float constants that are precisely
  10092. // representable in the target type.
  10093. Expr::EvalResult result;
  10094. if (E->EvaluateAsRValue(result, S.Context)) {
  10095. // Value might be a float, a float vector, or a float complex.
  10096. if (IsSameFloatAfterCast(result.Val,
  10097. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  10098. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  10099. return;
  10100. }
  10101. if (S.SourceMgr.isInSystemMacro(CC))
  10102. return;
  10103. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  10104. }
  10105. // ... or possibly if we're increasing rank, too
  10106. else if (Order < 0) {
  10107. if (S.SourceMgr.isInSystemMacro(CC))
  10108. return;
  10109. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  10110. }
  10111. return;
  10112. }
  10113. // If the target is integral, always warn.
  10114. if (TargetBT && TargetBT->isInteger()) {
  10115. if (S.SourceMgr.isInSystemMacro(CC))
  10116. return;
  10117. DiagnoseFloatingImpCast(S, E, T, CC);
  10118. }
  10119. // Detect the case where a call result is converted from floating-point to
  10120. // to bool, and the final argument to the call is converted from bool, to
  10121. // discover this typo:
  10122. //
  10123. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  10124. //
  10125. // FIXME: This is an incredibly special case; is there some more general
  10126. // way to detect this class of misplaced-parentheses bug?
  10127. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  10128. // Check last argument of function call to see if it is an
  10129. // implicit cast from a type matching the type the result
  10130. // is being cast to.
  10131. CallExpr *CEx = cast<CallExpr>(E);
  10132. if (unsigned NumArgs = CEx->getNumArgs()) {
  10133. Expr *LastA = CEx->getArg(NumArgs - 1);
  10134. Expr *InnerE = LastA->IgnoreParenImpCasts();
  10135. if (isa<ImplicitCastExpr>(LastA) &&
  10136. InnerE->getType()->isBooleanType()) {
  10137. // Warn on this floating-point to bool conversion
  10138. DiagnoseImpCast(S, E, T, CC,
  10139. diag::warn_impcast_floating_point_to_bool);
  10140. }
  10141. }
  10142. }
  10143. return;
  10144. }
  10145. // Valid casts involving fixed point types should be accounted for here.
  10146. if (Source->isFixedPointType()) {
  10147. if (Target->isUnsaturatedFixedPointType()) {
  10148. Expr::EvalResult Result;
  10149. if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
  10150. S.isConstantEvaluated())) {
  10151. APFixedPoint Value = Result.Val.getFixedPoint();
  10152. APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
  10153. APFixedPoint MinVal = S.Context.getFixedPointMin(T);
  10154. if (Value > MaxVal || Value < MinVal) {
  10155. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10156. S.PDiag(diag::warn_impcast_fixed_point_range)
  10157. << Value.toString() << T
  10158. << E->getSourceRange()
  10159. << clang::SourceRange(CC));
  10160. return;
  10161. }
  10162. }
  10163. } else if (Target->isIntegerType()) {
  10164. Expr::EvalResult Result;
  10165. if (!S.isConstantEvaluated() &&
  10166. E->EvaluateAsFixedPoint(Result, S.Context,
  10167. Expr::SE_AllowSideEffects)) {
  10168. APFixedPoint FXResult = Result.Val.getFixedPoint();
  10169. bool Overflowed;
  10170. llvm::APSInt IntResult = FXResult.convertToInt(
  10171. S.Context.getIntWidth(T),
  10172. Target->isSignedIntegerOrEnumerationType(), &Overflowed);
  10173. if (Overflowed) {
  10174. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10175. S.PDiag(diag::warn_impcast_fixed_point_range)
  10176. << FXResult.toString() << T
  10177. << E->getSourceRange()
  10178. << clang::SourceRange(CC));
  10179. return;
  10180. }
  10181. }
  10182. }
  10183. } else if (Target->isUnsaturatedFixedPointType()) {
  10184. if (Source->isIntegerType()) {
  10185. Expr::EvalResult Result;
  10186. if (!S.isConstantEvaluated() &&
  10187. E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
  10188. llvm::APSInt Value = Result.Val.getInt();
  10189. bool Overflowed;
  10190. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  10191. Value, S.Context.getFixedPointSemantics(T), &Overflowed);
  10192. if (Overflowed) {
  10193. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10194. S.PDiag(diag::warn_impcast_fixed_point_range)
  10195. << Value.toString(/*Radix=*/10) << T
  10196. << E->getSourceRange()
  10197. << clang::SourceRange(CC));
  10198. return;
  10199. }
  10200. }
  10201. }
  10202. }
  10203. // If we are casting an integer type to a floating point type without
  10204. // initialization-list syntax, we might lose accuracy if the floating
  10205. // point type has a narrower significand than the integer type.
  10206. if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
  10207. TargetBT->isFloatingType() && !IsListInit) {
  10208. // Determine the number of precision bits in the source integer type.
  10209. IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
  10210. unsigned int SourcePrecision = SourceRange.Width;
  10211. // Determine the number of precision bits in the
  10212. // target floating point type.
  10213. unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
  10214. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
  10215. if (SourcePrecision > 0 && TargetPrecision > 0 &&
  10216. SourcePrecision > TargetPrecision) {
  10217. llvm::APSInt SourceInt;
  10218. if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
  10219. // If the source integer is a constant, convert it to the target
  10220. // floating point type. Issue a warning if the value changes
  10221. // during the whole conversion.
  10222. llvm::APFloat TargetFloatValue(
  10223. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
  10224. llvm::APFloat::opStatus ConversionStatus =
  10225. TargetFloatValue.convertFromAPInt(
  10226. SourceInt, SourceBT->isSignedInteger(),
  10227. llvm::APFloat::rmNearestTiesToEven);
  10228. if (ConversionStatus != llvm::APFloat::opOK) {
  10229. std::string PrettySourceValue = SourceInt.toString(10);
  10230. SmallString<32> PrettyTargetValue;
  10231. TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
  10232. S.DiagRuntimeBehavior(
  10233. E->getExprLoc(), E,
  10234. S.PDiag(diag::warn_impcast_integer_float_precision_constant)
  10235. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10236. << E->getSourceRange() << clang::SourceRange(CC));
  10237. }
  10238. } else {
  10239. // Otherwise, the implicit conversion may lose precision.
  10240. DiagnoseImpCast(S, E, T, CC,
  10241. diag::warn_impcast_integer_float_precision);
  10242. }
  10243. }
  10244. }
  10245. DiagnoseNullConversion(S, E, T, CC);
  10246. S.DiscardMisalignedMemberAddress(Target, E);
  10247. if (!Source->isIntegerType() || !Target->isIntegerType())
  10248. return;
  10249. // TODO: remove this early return once the false positives for constant->bool
  10250. // in templates, macros, etc, are reduced or removed.
  10251. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  10252. return;
  10253. IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
  10254. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  10255. if (SourceRange.Width > TargetRange.Width) {
  10256. // If the source is a constant, use a default-on diagnostic.
  10257. // TODO: this should happen for bitfield stores, too.
  10258. Expr::EvalResult Result;
  10259. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
  10260. S.isConstantEvaluated())) {
  10261. llvm::APSInt Value(32);
  10262. Value = Result.Val.getInt();
  10263. if (S.SourceMgr.isInSystemMacro(CC))
  10264. return;
  10265. std::string PrettySourceValue = Value.toString(10);
  10266. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10267. S.DiagRuntimeBehavior(
  10268. E->getExprLoc(), E,
  10269. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10270. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10271. << E->getSourceRange() << clang::SourceRange(CC));
  10272. return;
  10273. }
  10274. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  10275. if (S.SourceMgr.isInSystemMacro(CC))
  10276. return;
  10277. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  10278. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  10279. /* pruneControlFlow */ true);
  10280. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  10281. }
  10282. if (TargetRange.Width > SourceRange.Width) {
  10283. if (auto *UO = dyn_cast<UnaryOperator>(E))
  10284. if (UO->getOpcode() == UO_Minus)
  10285. if (Source->isUnsignedIntegerType()) {
  10286. if (Target->isUnsignedIntegerType())
  10287. return DiagnoseImpCast(S, E, T, CC,
  10288. diag::warn_impcast_high_order_zero_bits);
  10289. if (Target->isSignedIntegerType())
  10290. return DiagnoseImpCast(S, E, T, CC,
  10291. diag::warn_impcast_nonnegative_result);
  10292. }
  10293. }
  10294. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  10295. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  10296. // Warn when doing a signed to signed conversion, warn if the positive
  10297. // source value is exactly the width of the target type, which will
  10298. // cause a negative value to be stored.
  10299. Expr::EvalResult Result;
  10300. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
  10301. !S.SourceMgr.isInSystemMacro(CC)) {
  10302. llvm::APSInt Value = Result.Val.getInt();
  10303. if (isSameWidthConstantConversion(S, E, T, CC)) {
  10304. std::string PrettySourceValue = Value.toString(10);
  10305. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10306. S.DiagRuntimeBehavior(
  10307. E->getExprLoc(), E,
  10308. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10309. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10310. << E->getSourceRange() << clang::SourceRange(CC));
  10311. return;
  10312. }
  10313. }
  10314. // Fall through for non-constants to give a sign conversion warning.
  10315. }
  10316. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  10317. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  10318. SourceRange.Width == TargetRange.Width)) {
  10319. if (S.SourceMgr.isInSystemMacro(CC))
  10320. return;
  10321. unsigned DiagID = diag::warn_impcast_integer_sign;
  10322. // Traditionally, gcc has warned about this under -Wsign-compare.
  10323. // We also want to warn about it in -Wconversion.
  10324. // So if -Wconversion is off, use a completely identical diagnostic
  10325. // in the sign-compare group.
  10326. // The conditional-checking code will
  10327. if (ICContext) {
  10328. DiagID = diag::warn_impcast_integer_sign_conditional;
  10329. *ICContext = true;
  10330. }
  10331. return DiagnoseImpCast(S, E, T, CC, DiagID);
  10332. }
  10333. // Diagnose conversions between different enumeration types.
  10334. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  10335. // type, to give us better diagnostics.
  10336. QualType SourceType = E->getType();
  10337. if (!S.getLangOpts().CPlusPlus) {
  10338. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10339. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  10340. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  10341. SourceType = S.Context.getTypeDeclType(Enum);
  10342. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  10343. }
  10344. }
  10345. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  10346. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  10347. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  10348. TargetEnum->getDecl()->hasNameForLinkage() &&
  10349. SourceEnum != TargetEnum) {
  10350. if (S.SourceMgr.isInSystemMacro(CC))
  10351. return;
  10352. return DiagnoseImpCast(S, E, SourceType, T, CC,
  10353. diag::warn_impcast_different_enum_types);
  10354. }
  10355. }
  10356. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10357. SourceLocation CC, QualType T);
  10358. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  10359. SourceLocation CC, bool &ICContext) {
  10360. E = E->IgnoreParenImpCasts();
  10361. if (isa<ConditionalOperator>(E))
  10362. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  10363. AnalyzeImplicitConversions(S, E, CC);
  10364. if (E->getType() != T)
  10365. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  10366. }
  10367. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10368. SourceLocation CC, QualType T) {
  10369. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  10370. bool Suspicious = false;
  10371. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  10372. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  10373. // If -Wconversion would have warned about either of the candidates
  10374. // for a signedness conversion to the context type...
  10375. if (!Suspicious) return;
  10376. // ...but it's currently ignored...
  10377. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  10378. return;
  10379. // ...then check whether it would have warned about either of the
  10380. // candidates for a signedness conversion to the condition type.
  10381. if (E->getType() == T) return;
  10382. Suspicious = false;
  10383. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  10384. E->getType(), CC, &Suspicious);
  10385. if (!Suspicious)
  10386. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  10387. E->getType(), CC, &Suspicious);
  10388. }
  10389. /// Check conversion of given expression to boolean.
  10390. /// Input argument E is a logical expression.
  10391. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  10392. if (S.getLangOpts().Bool)
  10393. return;
  10394. if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
  10395. return;
  10396. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  10397. }
  10398. /// AnalyzeImplicitConversions - Find and report any interesting
  10399. /// implicit conversions in the given expression. There are a couple
  10400. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  10401. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
  10402. bool IsListInit/*= false*/) {
  10403. QualType T = OrigE->getType();
  10404. Expr *E = OrigE->IgnoreParenImpCasts();
  10405. // Propagate whether we are in a C++ list initialization expression.
  10406. // If so, we do not issue warnings for implicit int-float conversion
  10407. // precision loss, because C++11 narrowing already handles it.
  10408. IsListInit =
  10409. IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
  10410. if (E->isTypeDependent() || E->isValueDependent())
  10411. return;
  10412. // For conditional operators, we analyze the arguments as if they
  10413. // were being fed directly into the output.
  10414. if (isa<ConditionalOperator>(E)) {
  10415. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  10416. CheckConditionalOperator(S, CO, CC, T);
  10417. return;
  10418. }
  10419. // Check implicit argument conversions for function calls.
  10420. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  10421. CheckImplicitArgumentConversions(S, Call, CC);
  10422. // Go ahead and check any implicit conversions we might have skipped.
  10423. // The non-canonical typecheck is just an optimization;
  10424. // CheckImplicitConversion will filter out dead implicit conversions.
  10425. if (E->getType() != T)
  10426. CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
  10427. // Now continue drilling into this expression.
  10428. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  10429. // The bound subexpressions in a PseudoObjectExpr are not reachable
  10430. // as transitive children.
  10431. // FIXME: Use a more uniform representation for this.
  10432. for (auto *SE : POE->semantics())
  10433. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  10434. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
  10435. }
  10436. // Skip past explicit casts.
  10437. if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
  10438. E = CE->getSubExpr()->IgnoreParenImpCasts();
  10439. if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
  10440. S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  10441. return AnalyzeImplicitConversions(S, E, CC, IsListInit);
  10442. }
  10443. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10444. // Do a somewhat different check with comparison operators.
  10445. if (BO->isComparisonOp())
  10446. return AnalyzeComparison(S, BO);
  10447. // And with simple assignments.
  10448. if (BO->getOpcode() == BO_Assign)
  10449. return AnalyzeAssignment(S, BO);
  10450. // And with compound assignments.
  10451. if (BO->isAssignmentOp())
  10452. return AnalyzeCompoundAssignment(S, BO);
  10453. }
  10454. // These break the otherwise-useful invariant below. Fortunately,
  10455. // we don't really need to recurse into them, because any internal
  10456. // expressions should have been analyzed already when they were
  10457. // built into statements.
  10458. if (isa<StmtExpr>(E)) return;
  10459. // Don't descend into unevaluated contexts.
  10460. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  10461. // Now just recurse over the expression's children.
  10462. CC = E->getExprLoc();
  10463. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  10464. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  10465. for (Stmt *SubStmt : E->children()) {
  10466. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  10467. if (!ChildExpr)
  10468. continue;
  10469. if (IsLogicalAndOperator &&
  10470. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  10471. // Ignore checking string literals that are in logical and operators.
  10472. // This is a common pattern for asserts.
  10473. continue;
  10474. AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
  10475. }
  10476. if (BO && BO->isLogicalOp()) {
  10477. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  10478. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10479. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10480. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  10481. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10482. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10483. }
  10484. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  10485. if (U->getOpcode() == UO_LNot) {
  10486. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  10487. } else if (U->getOpcode() != UO_AddrOf) {
  10488. if (U->getSubExpr()->getType()->isAtomicType())
  10489. S.Diag(U->getSubExpr()->getBeginLoc(),
  10490. diag::warn_atomic_implicit_seq_cst);
  10491. }
  10492. }
  10493. }
  10494. /// Diagnose integer type and any valid implicit conversion to it.
  10495. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  10496. // Taking into account implicit conversions,
  10497. // allow any integer.
  10498. if (!E->getType()->isIntegerType()) {
  10499. S.Diag(E->getBeginLoc(),
  10500. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  10501. return true;
  10502. }
  10503. // Potentially emit standard warnings for implicit conversions if enabled
  10504. // using -Wconversion.
  10505. CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
  10506. return false;
  10507. }
  10508. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  10509. // Returns true when emitting a warning about taking the address of a reference.
  10510. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  10511. const PartialDiagnostic &PD) {
  10512. E = E->IgnoreParenImpCasts();
  10513. const FunctionDecl *FD = nullptr;
  10514. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  10515. if (!DRE->getDecl()->getType()->isReferenceType())
  10516. return false;
  10517. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10518. if (!M->getMemberDecl()->getType()->isReferenceType())
  10519. return false;
  10520. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  10521. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  10522. return false;
  10523. FD = Call->getDirectCallee();
  10524. } else {
  10525. return false;
  10526. }
  10527. SemaRef.Diag(E->getExprLoc(), PD);
  10528. // If possible, point to location of function.
  10529. if (FD) {
  10530. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  10531. }
  10532. return true;
  10533. }
  10534. // Returns true if the SourceLocation is expanded from any macro body.
  10535. // Returns false if the SourceLocation is invalid, is from not in a macro
  10536. // expansion, or is from expanded from a top-level macro argument.
  10537. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  10538. if (Loc.isInvalid())
  10539. return false;
  10540. while (Loc.isMacroID()) {
  10541. if (SM.isMacroBodyExpansion(Loc))
  10542. return true;
  10543. Loc = SM.getImmediateMacroCallerLoc(Loc);
  10544. }
  10545. return false;
  10546. }
  10547. /// Diagnose pointers that are always non-null.
  10548. /// \param E the expression containing the pointer
  10549. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  10550. /// compared to a null pointer
  10551. /// \param IsEqual True when the comparison is equal to a null pointer
  10552. /// \param Range Extra SourceRange to highlight in the diagnostic
  10553. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  10554. Expr::NullPointerConstantKind NullKind,
  10555. bool IsEqual, SourceRange Range) {
  10556. if (!E)
  10557. return;
  10558. // Don't warn inside macros.
  10559. if (E->getExprLoc().isMacroID()) {
  10560. const SourceManager &SM = getSourceManager();
  10561. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  10562. IsInAnyMacroBody(SM, Range.getBegin()))
  10563. return;
  10564. }
  10565. E = E->IgnoreImpCasts();
  10566. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  10567. if (isa<CXXThisExpr>(E)) {
  10568. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  10569. : diag::warn_this_bool_conversion;
  10570. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  10571. return;
  10572. }
  10573. bool IsAddressOf = false;
  10574. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10575. if (UO->getOpcode() != UO_AddrOf)
  10576. return;
  10577. IsAddressOf = true;
  10578. E = UO->getSubExpr();
  10579. }
  10580. if (IsAddressOf) {
  10581. unsigned DiagID = IsCompare
  10582. ? diag::warn_address_of_reference_null_compare
  10583. : diag::warn_address_of_reference_bool_conversion;
  10584. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  10585. << IsEqual;
  10586. if (CheckForReference(*this, E, PD)) {
  10587. return;
  10588. }
  10589. }
  10590. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  10591. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  10592. std::string Str;
  10593. llvm::raw_string_ostream S(Str);
  10594. E->printPretty(S, nullptr, getPrintingPolicy());
  10595. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  10596. : diag::warn_cast_nonnull_to_bool;
  10597. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  10598. << E->getSourceRange() << Range << IsEqual;
  10599. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  10600. };
  10601. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  10602. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  10603. if (auto *Callee = Call->getDirectCallee()) {
  10604. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  10605. ComplainAboutNonnullParamOrCall(A);
  10606. return;
  10607. }
  10608. }
  10609. }
  10610. // Expect to find a single Decl. Skip anything more complicated.
  10611. ValueDecl *D = nullptr;
  10612. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  10613. D = R->getDecl();
  10614. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10615. D = M->getMemberDecl();
  10616. }
  10617. // Weak Decls can be null.
  10618. if (!D || D->isWeak())
  10619. return;
  10620. // Check for parameter decl with nonnull attribute
  10621. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  10622. if (getCurFunction() &&
  10623. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  10624. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  10625. ComplainAboutNonnullParamOrCall(A);
  10626. return;
  10627. }
  10628. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  10629. // Skip function template not specialized yet.
  10630. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  10631. return;
  10632. auto ParamIter = llvm::find(FD->parameters(), PV);
  10633. assert(ParamIter != FD->param_end());
  10634. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  10635. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  10636. if (!NonNull->args_size()) {
  10637. ComplainAboutNonnullParamOrCall(NonNull);
  10638. return;
  10639. }
  10640. for (const ParamIdx &ArgNo : NonNull->args()) {
  10641. if (ArgNo.getASTIndex() == ParamNo) {
  10642. ComplainAboutNonnullParamOrCall(NonNull);
  10643. return;
  10644. }
  10645. }
  10646. }
  10647. }
  10648. }
  10649. }
  10650. QualType T = D->getType();
  10651. const bool IsArray = T->isArrayType();
  10652. const bool IsFunction = T->isFunctionType();
  10653. // Address of function is used to silence the function warning.
  10654. if (IsAddressOf && IsFunction) {
  10655. return;
  10656. }
  10657. // Found nothing.
  10658. if (!IsAddressOf && !IsFunction && !IsArray)
  10659. return;
  10660. // Pretty print the expression for the diagnostic.
  10661. std::string Str;
  10662. llvm::raw_string_ostream S(Str);
  10663. E->printPretty(S, nullptr, getPrintingPolicy());
  10664. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  10665. : diag::warn_impcast_pointer_to_bool;
  10666. enum {
  10667. AddressOf,
  10668. FunctionPointer,
  10669. ArrayPointer
  10670. } DiagType;
  10671. if (IsAddressOf)
  10672. DiagType = AddressOf;
  10673. else if (IsFunction)
  10674. DiagType = FunctionPointer;
  10675. else if (IsArray)
  10676. DiagType = ArrayPointer;
  10677. else
  10678. llvm_unreachable("Could not determine diagnostic.");
  10679. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  10680. << Range << IsEqual;
  10681. if (!IsFunction)
  10682. return;
  10683. // Suggest '&' to silence the function warning.
  10684. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  10685. << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
  10686. // Check to see if '()' fixit should be emitted.
  10687. QualType ReturnType;
  10688. UnresolvedSet<4> NonTemplateOverloads;
  10689. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  10690. if (ReturnType.isNull())
  10691. return;
  10692. if (IsCompare) {
  10693. // There are two cases here. If there is null constant, the only suggest
  10694. // for a pointer return type. If the null is 0, then suggest if the return
  10695. // type is a pointer or an integer type.
  10696. if (!ReturnType->isPointerType()) {
  10697. if (NullKind == Expr::NPCK_ZeroExpression ||
  10698. NullKind == Expr::NPCK_ZeroLiteral) {
  10699. if (!ReturnType->isIntegerType())
  10700. return;
  10701. } else {
  10702. return;
  10703. }
  10704. }
  10705. } else { // !IsCompare
  10706. // For function to bool, only suggest if the function pointer has bool
  10707. // return type.
  10708. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  10709. return;
  10710. }
  10711. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  10712. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
  10713. }
  10714. /// Diagnoses "dangerous" implicit conversions within the given
  10715. /// expression (which is a full expression). Implements -Wconversion
  10716. /// and -Wsign-compare.
  10717. ///
  10718. /// \param CC the "context" location of the implicit conversion, i.e.
  10719. /// the most location of the syntactic entity requiring the implicit
  10720. /// conversion
  10721. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  10722. // Don't diagnose in unevaluated contexts.
  10723. if (isUnevaluatedContext())
  10724. return;
  10725. // Don't diagnose for value- or type-dependent expressions.
  10726. if (E->isTypeDependent() || E->isValueDependent())
  10727. return;
  10728. // Check for array bounds violations in cases where the check isn't triggered
  10729. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  10730. // ArraySubscriptExpr is on the RHS of a variable initialization.
  10731. CheckArrayAccess(E);
  10732. // This is not the right CC for (e.g.) a variable initialization.
  10733. AnalyzeImplicitConversions(*this, E, CC);
  10734. }
  10735. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  10736. /// Input argument E is a logical expression.
  10737. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  10738. ::CheckBoolLikeConversion(*this, E, CC);
  10739. }
  10740. /// Diagnose when expression is an integer constant expression and its evaluation
  10741. /// results in integer overflow
  10742. void Sema::CheckForIntOverflow (Expr *E) {
  10743. // Use a work list to deal with nested struct initializers.
  10744. SmallVector<Expr *, 2> Exprs(1, E);
  10745. do {
  10746. Expr *OriginalE = Exprs.pop_back_val();
  10747. Expr *E = OriginalE->IgnoreParenCasts();
  10748. if (isa<BinaryOperator>(E)) {
  10749. E->EvaluateForOverflow(Context);
  10750. continue;
  10751. }
  10752. if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
  10753. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  10754. else if (isa<ObjCBoxedExpr>(OriginalE))
  10755. E->EvaluateForOverflow(Context);
  10756. else if (auto Call = dyn_cast<CallExpr>(E))
  10757. Exprs.append(Call->arg_begin(), Call->arg_end());
  10758. else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
  10759. Exprs.append(Message->arg_begin(), Message->arg_end());
  10760. } while (!Exprs.empty());
  10761. }
  10762. namespace {
  10763. /// Visitor for expressions which looks for unsequenced operations on the
  10764. /// same object.
  10765. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  10766. using Base = EvaluatedExprVisitor<SequenceChecker>;
  10767. /// A tree of sequenced regions within an expression. Two regions are
  10768. /// unsequenced if one is an ancestor or a descendent of the other. When we
  10769. /// finish processing an expression with sequencing, such as a comma
  10770. /// expression, we fold its tree nodes into its parent, since they are
  10771. /// unsequenced with respect to nodes we will visit later.
  10772. class SequenceTree {
  10773. struct Value {
  10774. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  10775. unsigned Parent : 31;
  10776. unsigned Merged : 1;
  10777. };
  10778. SmallVector<Value, 8> Values;
  10779. public:
  10780. /// A region within an expression which may be sequenced with respect
  10781. /// to some other region.
  10782. class Seq {
  10783. friend class SequenceTree;
  10784. unsigned Index;
  10785. explicit Seq(unsigned N) : Index(N) {}
  10786. public:
  10787. Seq() : Index(0) {}
  10788. };
  10789. SequenceTree() { Values.push_back(Value(0)); }
  10790. Seq root() const { return Seq(0); }
  10791. /// Create a new sequence of operations, which is an unsequenced
  10792. /// subset of \p Parent. This sequence of operations is sequenced with
  10793. /// respect to other children of \p Parent.
  10794. Seq allocate(Seq Parent) {
  10795. Values.push_back(Value(Parent.Index));
  10796. return Seq(Values.size() - 1);
  10797. }
  10798. /// Merge a sequence of operations into its parent.
  10799. void merge(Seq S) {
  10800. Values[S.Index].Merged = true;
  10801. }
  10802. /// Determine whether two operations are unsequenced. This operation
  10803. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  10804. /// should have been merged into its parent as appropriate.
  10805. bool isUnsequenced(Seq Cur, Seq Old) {
  10806. unsigned C = representative(Cur.Index);
  10807. unsigned Target = representative(Old.Index);
  10808. while (C >= Target) {
  10809. if (C == Target)
  10810. return true;
  10811. C = Values[C].Parent;
  10812. }
  10813. return false;
  10814. }
  10815. private:
  10816. /// Pick a representative for a sequence.
  10817. unsigned representative(unsigned K) {
  10818. if (Values[K].Merged)
  10819. // Perform path compression as we go.
  10820. return Values[K].Parent = representative(Values[K].Parent);
  10821. return K;
  10822. }
  10823. };
  10824. /// An object for which we can track unsequenced uses.
  10825. using Object = NamedDecl *;
  10826. /// Different flavors of object usage which we track. We only track the
  10827. /// least-sequenced usage of each kind.
  10828. enum UsageKind {
  10829. /// A read of an object. Multiple unsequenced reads are OK.
  10830. UK_Use,
  10831. /// A modification of an object which is sequenced before the value
  10832. /// computation of the expression, such as ++n in C++.
  10833. UK_ModAsValue,
  10834. /// A modification of an object which is not sequenced before the value
  10835. /// computation of the expression, such as n++.
  10836. UK_ModAsSideEffect,
  10837. UK_Count = UK_ModAsSideEffect + 1
  10838. };
  10839. struct Usage {
  10840. Expr *Use;
  10841. SequenceTree::Seq Seq;
  10842. Usage() : Use(nullptr), Seq() {}
  10843. };
  10844. struct UsageInfo {
  10845. Usage Uses[UK_Count];
  10846. /// Have we issued a diagnostic for this variable already?
  10847. bool Diagnosed;
  10848. UsageInfo() : Uses(), Diagnosed(false) {}
  10849. };
  10850. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  10851. Sema &SemaRef;
  10852. /// Sequenced regions within the expression.
  10853. SequenceTree Tree;
  10854. /// Declaration modifications and references which we have seen.
  10855. UsageInfoMap UsageMap;
  10856. /// The region we are currently within.
  10857. SequenceTree::Seq Region;
  10858. /// Filled in with declarations which were modified as a side-effect
  10859. /// (that is, post-increment operations).
  10860. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  10861. /// Expressions to check later. We defer checking these to reduce
  10862. /// stack usage.
  10863. SmallVectorImpl<Expr *> &WorkList;
  10864. /// RAII object wrapping the visitation of a sequenced subexpression of an
  10865. /// expression. At the end of this process, the side-effects of the evaluation
  10866. /// become sequenced with respect to the value computation of the result, so
  10867. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  10868. /// UK_ModAsValue.
  10869. struct SequencedSubexpression {
  10870. SequencedSubexpression(SequenceChecker &Self)
  10871. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  10872. Self.ModAsSideEffect = &ModAsSideEffect;
  10873. }
  10874. ~SequencedSubexpression() {
  10875. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  10876. UsageInfo &U = Self.UsageMap[M.first];
  10877. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  10878. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  10879. SideEffectUsage = M.second;
  10880. }
  10881. Self.ModAsSideEffect = OldModAsSideEffect;
  10882. }
  10883. SequenceChecker &Self;
  10884. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  10885. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  10886. };
  10887. /// RAII object wrapping the visitation of a subexpression which we might
  10888. /// choose to evaluate as a constant. If any subexpression is evaluated and
  10889. /// found to be non-constant, this allows us to suppress the evaluation of
  10890. /// the outer expression.
  10891. class EvaluationTracker {
  10892. public:
  10893. EvaluationTracker(SequenceChecker &Self)
  10894. : Self(Self), Prev(Self.EvalTracker) {
  10895. Self.EvalTracker = this;
  10896. }
  10897. ~EvaluationTracker() {
  10898. Self.EvalTracker = Prev;
  10899. if (Prev)
  10900. Prev->EvalOK &= EvalOK;
  10901. }
  10902. bool evaluate(const Expr *E, bool &Result) {
  10903. if (!EvalOK || E->isValueDependent())
  10904. return false;
  10905. EvalOK = E->EvaluateAsBooleanCondition(
  10906. Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
  10907. return EvalOK;
  10908. }
  10909. private:
  10910. SequenceChecker &Self;
  10911. EvaluationTracker *Prev;
  10912. bool EvalOK = true;
  10913. } *EvalTracker = nullptr;
  10914. /// Find the object which is produced by the specified expression,
  10915. /// if any.
  10916. Object getObject(Expr *E, bool Mod) const {
  10917. E = E->IgnoreParenCasts();
  10918. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10919. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  10920. return getObject(UO->getSubExpr(), Mod);
  10921. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10922. if (BO->getOpcode() == BO_Comma)
  10923. return getObject(BO->getRHS(), Mod);
  10924. if (Mod && BO->isAssignmentOp())
  10925. return getObject(BO->getLHS(), Mod);
  10926. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  10927. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  10928. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  10929. return ME->getMemberDecl();
  10930. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10931. // FIXME: If this is a reference, map through to its value.
  10932. return DRE->getDecl();
  10933. return nullptr;
  10934. }
  10935. /// Note that an object was modified or used by an expression.
  10936. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  10937. Usage &U = UI.Uses[UK];
  10938. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  10939. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  10940. ModAsSideEffect->push_back(std::make_pair(O, U));
  10941. U.Use = Ref;
  10942. U.Seq = Region;
  10943. }
  10944. }
  10945. /// Check whether a modification or use conflicts with a prior usage.
  10946. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  10947. bool IsModMod) {
  10948. if (UI.Diagnosed)
  10949. return;
  10950. const Usage &U = UI.Uses[OtherKind];
  10951. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  10952. return;
  10953. Expr *Mod = U.Use;
  10954. Expr *ModOrUse = Ref;
  10955. if (OtherKind == UK_Use)
  10956. std::swap(Mod, ModOrUse);
  10957. SemaRef.DiagRuntimeBehavior(
  10958. Mod->getExprLoc(), {Mod, ModOrUse},
  10959. SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
  10960. : diag::warn_unsequenced_mod_use)
  10961. << O << SourceRange(ModOrUse->getExprLoc()));
  10962. UI.Diagnosed = true;
  10963. }
  10964. void notePreUse(Object O, Expr *Use) {
  10965. UsageInfo &U = UsageMap[O];
  10966. // Uses conflict with other modifications.
  10967. checkUsage(O, U, Use, UK_ModAsValue, false);
  10968. }
  10969. void notePostUse(Object O, Expr *Use) {
  10970. UsageInfo &U = UsageMap[O];
  10971. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  10972. addUsage(U, O, Use, UK_Use);
  10973. }
  10974. void notePreMod(Object O, Expr *Mod) {
  10975. UsageInfo &U = UsageMap[O];
  10976. // Modifications conflict with other modifications and with uses.
  10977. checkUsage(O, U, Mod, UK_ModAsValue, true);
  10978. checkUsage(O, U, Mod, UK_Use, false);
  10979. }
  10980. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  10981. UsageInfo &U = UsageMap[O];
  10982. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  10983. addUsage(U, O, Use, UK);
  10984. }
  10985. public:
  10986. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  10987. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  10988. Visit(E);
  10989. }
  10990. void VisitStmt(Stmt *S) {
  10991. // Skip all statements which aren't expressions for now.
  10992. }
  10993. void VisitExpr(Expr *E) {
  10994. // By default, just recurse to evaluated subexpressions.
  10995. Base::VisitStmt(E);
  10996. }
  10997. void VisitCastExpr(CastExpr *E) {
  10998. Object O = Object();
  10999. if (E->getCastKind() == CK_LValueToRValue)
  11000. O = getObject(E->getSubExpr(), false);
  11001. if (O)
  11002. notePreUse(O, E);
  11003. VisitExpr(E);
  11004. if (O)
  11005. notePostUse(O, E);
  11006. }
  11007. void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
  11008. SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
  11009. SequenceTree::Seq AfterRegion = Tree.allocate(Region);
  11010. SequenceTree::Seq OldRegion = Region;
  11011. {
  11012. SequencedSubexpression SeqBefore(*this);
  11013. Region = BeforeRegion;
  11014. Visit(SequencedBefore);
  11015. }
  11016. Region = AfterRegion;
  11017. Visit(SequencedAfter);
  11018. Region = OldRegion;
  11019. Tree.merge(BeforeRegion);
  11020. Tree.merge(AfterRegion);
  11021. }
  11022. void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
  11023. // C++17 [expr.sub]p1:
  11024. // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
  11025. // expression E1 is sequenced before the expression E2.
  11026. if (SemaRef.getLangOpts().CPlusPlus17)
  11027. VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
  11028. else
  11029. Base::VisitStmt(ASE);
  11030. }
  11031. void VisitBinComma(BinaryOperator *BO) {
  11032. // C++11 [expr.comma]p1:
  11033. // Every value computation and side effect associated with the left
  11034. // expression is sequenced before every value computation and side
  11035. // effect associated with the right expression.
  11036. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  11037. }
  11038. void VisitBinAssign(BinaryOperator *BO) {
  11039. // The modification is sequenced after the value computation of the LHS
  11040. // and RHS, so check it before inspecting the operands and update the
  11041. // map afterwards.
  11042. Object O = getObject(BO->getLHS(), true);
  11043. if (!O)
  11044. return VisitExpr(BO);
  11045. notePreMod(O, BO);
  11046. // C++11 [expr.ass]p7:
  11047. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  11048. // only once.
  11049. //
  11050. // Therefore, for a compound assignment operator, O is considered used
  11051. // everywhere except within the evaluation of E1 itself.
  11052. if (isa<CompoundAssignOperator>(BO))
  11053. notePreUse(O, BO);
  11054. Visit(BO->getLHS());
  11055. if (isa<CompoundAssignOperator>(BO))
  11056. notePostUse(O, BO);
  11057. Visit(BO->getRHS());
  11058. // C++11 [expr.ass]p1:
  11059. // the assignment is sequenced [...] before the value computation of the
  11060. // assignment expression.
  11061. // C11 6.5.16/3 has no such rule.
  11062. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  11063. : UK_ModAsSideEffect);
  11064. }
  11065. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  11066. VisitBinAssign(CAO);
  11067. }
  11068. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  11069. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  11070. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  11071. Object O = getObject(UO->getSubExpr(), true);
  11072. if (!O)
  11073. return VisitExpr(UO);
  11074. notePreMod(O, UO);
  11075. Visit(UO->getSubExpr());
  11076. // C++11 [expr.pre.incr]p1:
  11077. // the expression ++x is equivalent to x+=1
  11078. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  11079. : UK_ModAsSideEffect);
  11080. }
  11081. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  11082. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  11083. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  11084. Object O = getObject(UO->getSubExpr(), true);
  11085. if (!O)
  11086. return VisitExpr(UO);
  11087. notePreMod(O, UO);
  11088. Visit(UO->getSubExpr());
  11089. notePostMod(O, UO, UK_ModAsSideEffect);
  11090. }
  11091. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  11092. void VisitBinLOr(BinaryOperator *BO) {
  11093. // The side-effects of the LHS of an '&&' are sequenced before the
  11094. // value computation of the RHS, and hence before the value computation
  11095. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  11096. // as if they were unconditionally sequenced.
  11097. EvaluationTracker Eval(*this);
  11098. {
  11099. SequencedSubexpression Sequenced(*this);
  11100. Visit(BO->getLHS());
  11101. }
  11102. bool Result;
  11103. if (Eval.evaluate(BO->getLHS(), Result)) {
  11104. if (!Result)
  11105. Visit(BO->getRHS());
  11106. } else {
  11107. // Check for unsequenced operations in the RHS, treating it as an
  11108. // entirely separate evaluation.
  11109. //
  11110. // FIXME: If there are operations in the RHS which are unsequenced
  11111. // with respect to operations outside the RHS, and those operations
  11112. // are unconditionally evaluated, diagnose them.
  11113. WorkList.push_back(BO->getRHS());
  11114. }
  11115. }
  11116. void VisitBinLAnd(BinaryOperator *BO) {
  11117. EvaluationTracker Eval(*this);
  11118. {
  11119. SequencedSubexpression Sequenced(*this);
  11120. Visit(BO->getLHS());
  11121. }
  11122. bool Result;
  11123. if (Eval.evaluate(BO->getLHS(), Result)) {
  11124. if (Result)
  11125. Visit(BO->getRHS());
  11126. } else {
  11127. WorkList.push_back(BO->getRHS());
  11128. }
  11129. }
  11130. // Only visit the condition, unless we can be sure which subexpression will
  11131. // be chosen.
  11132. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  11133. EvaluationTracker Eval(*this);
  11134. {
  11135. SequencedSubexpression Sequenced(*this);
  11136. Visit(CO->getCond());
  11137. }
  11138. bool Result;
  11139. if (Eval.evaluate(CO->getCond(), Result))
  11140. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  11141. else {
  11142. WorkList.push_back(CO->getTrueExpr());
  11143. WorkList.push_back(CO->getFalseExpr());
  11144. }
  11145. }
  11146. void VisitCallExpr(CallExpr *CE) {
  11147. // C++11 [intro.execution]p15:
  11148. // When calling a function [...], every value computation and side effect
  11149. // associated with any argument expression, or with the postfix expression
  11150. // designating the called function, is sequenced before execution of every
  11151. // expression or statement in the body of the function [and thus before
  11152. // the value computation of its result].
  11153. SequencedSubexpression Sequenced(*this);
  11154. Base::VisitCallExpr(CE);
  11155. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  11156. }
  11157. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  11158. // This is a call, so all subexpressions are sequenced before the result.
  11159. SequencedSubexpression Sequenced(*this);
  11160. if (!CCE->isListInitialization())
  11161. return VisitExpr(CCE);
  11162. // In C++11, list initializations are sequenced.
  11163. SmallVector<SequenceTree::Seq, 32> Elts;
  11164. SequenceTree::Seq Parent = Region;
  11165. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  11166. E = CCE->arg_end();
  11167. I != E; ++I) {
  11168. Region = Tree.allocate(Parent);
  11169. Elts.push_back(Region);
  11170. Visit(*I);
  11171. }
  11172. // Forget that the initializers are sequenced.
  11173. Region = Parent;
  11174. for (unsigned I = 0; I < Elts.size(); ++I)
  11175. Tree.merge(Elts[I]);
  11176. }
  11177. void VisitInitListExpr(InitListExpr *ILE) {
  11178. if (!SemaRef.getLangOpts().CPlusPlus11)
  11179. return VisitExpr(ILE);
  11180. // In C++11, list initializations are sequenced.
  11181. SmallVector<SequenceTree::Seq, 32> Elts;
  11182. SequenceTree::Seq Parent = Region;
  11183. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  11184. Expr *E = ILE->getInit(I);
  11185. if (!E) continue;
  11186. Region = Tree.allocate(Parent);
  11187. Elts.push_back(Region);
  11188. Visit(E);
  11189. }
  11190. // Forget that the initializers are sequenced.
  11191. Region = Parent;
  11192. for (unsigned I = 0; I < Elts.size(); ++I)
  11193. Tree.merge(Elts[I]);
  11194. }
  11195. };
  11196. } // namespace
  11197. void Sema::CheckUnsequencedOperations(Expr *E) {
  11198. SmallVector<Expr *, 8> WorkList;
  11199. WorkList.push_back(E);
  11200. while (!WorkList.empty()) {
  11201. Expr *Item = WorkList.pop_back_val();
  11202. SequenceChecker(*this, Item, WorkList);
  11203. }
  11204. }
  11205. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  11206. bool IsConstexpr) {
  11207. llvm::SaveAndRestore<bool> ConstantContext(
  11208. isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
  11209. CheckImplicitConversions(E, CheckLoc);
  11210. if (!E->isInstantiationDependent())
  11211. CheckUnsequencedOperations(E);
  11212. if (!IsConstexpr && !E->isValueDependent())
  11213. CheckForIntOverflow(E);
  11214. DiagnoseMisalignedMembers();
  11215. }
  11216. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  11217. FieldDecl *BitField,
  11218. Expr *Init) {
  11219. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  11220. }
  11221. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  11222. SourceLocation Loc) {
  11223. if (!PType->isVariablyModifiedType())
  11224. return;
  11225. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  11226. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  11227. return;
  11228. }
  11229. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  11230. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  11231. return;
  11232. }
  11233. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  11234. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  11235. return;
  11236. }
  11237. const ArrayType *AT = S.Context.getAsArrayType(PType);
  11238. if (!AT)
  11239. return;
  11240. if (AT->getSizeModifier() != ArrayType::Star) {
  11241. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  11242. return;
  11243. }
  11244. S.Diag(Loc, diag::err_array_star_in_function_definition);
  11245. }
  11246. /// CheckParmsForFunctionDef - Check that the parameters of the given
  11247. /// function are appropriate for the definition of a function. This
  11248. /// takes care of any checks that cannot be performed on the
  11249. /// declaration itself, e.g., that the types of each of the function
  11250. /// parameters are complete.
  11251. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  11252. bool CheckParameterNames) {
  11253. bool HasInvalidParm = false;
  11254. for (ParmVarDecl *Param : Parameters) {
  11255. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  11256. // function declarator that is part of a function definition of
  11257. // that function shall not have incomplete type.
  11258. //
  11259. // This is also C++ [dcl.fct]p6.
  11260. if (!Param->isInvalidDecl() &&
  11261. RequireCompleteType(Param->getLocation(), Param->getType(),
  11262. diag::err_typecheck_decl_incomplete_type)) {
  11263. Param->setInvalidDecl();
  11264. HasInvalidParm = true;
  11265. }
  11266. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  11267. // declaration of each parameter shall include an identifier.
  11268. if (CheckParameterNames &&
  11269. Param->getIdentifier() == nullptr &&
  11270. !Param->isImplicit() &&
  11271. !getLangOpts().CPlusPlus)
  11272. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  11273. // C99 6.7.5.3p12:
  11274. // If the function declarator is not part of a definition of that
  11275. // function, parameters may have incomplete type and may use the [*]
  11276. // notation in their sequences of declarator specifiers to specify
  11277. // variable length array types.
  11278. QualType PType = Param->getOriginalType();
  11279. // FIXME: This diagnostic should point the '[*]' if source-location
  11280. // information is added for it.
  11281. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  11282. // If the parameter is a c++ class type and it has to be destructed in the
  11283. // callee function, declare the destructor so that it can be called by the
  11284. // callee function. Do not perform any direct access check on the dtor here.
  11285. if (!Param->isInvalidDecl()) {
  11286. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  11287. if (!ClassDecl->isInvalidDecl() &&
  11288. !ClassDecl->hasIrrelevantDestructor() &&
  11289. !ClassDecl->isDependentContext() &&
  11290. ClassDecl->isParamDestroyedInCallee()) {
  11291. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  11292. MarkFunctionReferenced(Param->getLocation(), Destructor);
  11293. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  11294. }
  11295. }
  11296. }
  11297. // Parameters with the pass_object_size attribute only need to be marked
  11298. // constant at function definitions. Because we lack information about
  11299. // whether we're on a declaration or definition when we're instantiating the
  11300. // attribute, we need to check for constness here.
  11301. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  11302. if (!Param->getType().isConstQualified())
  11303. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  11304. << Attr->getSpelling() << 1;
  11305. // Check for parameter names shadowing fields from the class.
  11306. if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
  11307. // The owning context for the parameter should be the function, but we
  11308. // want to see if this function's declaration context is a record.
  11309. DeclContext *DC = Param->getDeclContext();
  11310. if (DC && DC->isFunctionOrMethod()) {
  11311. if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
  11312. CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
  11313. RD, /*DeclIsField*/ false);
  11314. }
  11315. }
  11316. }
  11317. return HasInvalidParm;
  11318. }
  11319. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  11320. /// or MemberExpr.
  11321. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  11322. ASTContext &Context) {
  11323. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  11324. return Context.getDeclAlign(DRE->getDecl());
  11325. if (const auto *ME = dyn_cast<MemberExpr>(E))
  11326. return Context.getDeclAlign(ME->getMemberDecl());
  11327. return TypeAlign;
  11328. }
  11329. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  11330. /// pointer cast increases the alignment requirements.
  11331. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  11332. // This is actually a lot of work to potentially be doing on every
  11333. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  11334. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  11335. return;
  11336. // Ignore dependent types.
  11337. if (T->isDependentType() || Op->getType()->isDependentType())
  11338. return;
  11339. // Require that the destination be a pointer type.
  11340. const PointerType *DestPtr = T->getAs<PointerType>();
  11341. if (!DestPtr) return;
  11342. // If the destination has alignment 1, we're done.
  11343. QualType DestPointee = DestPtr->getPointeeType();
  11344. if (DestPointee->isIncompleteType()) return;
  11345. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  11346. if (DestAlign.isOne()) return;
  11347. // Require that the source be a pointer type.
  11348. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  11349. if (!SrcPtr) return;
  11350. QualType SrcPointee = SrcPtr->getPointeeType();
  11351. // Whitelist casts from cv void*. We already implicitly
  11352. // whitelisted casts to cv void*, since they have alignment 1.
  11353. // Also whitelist casts involving incomplete types, which implicitly
  11354. // includes 'void'.
  11355. if (SrcPointee->isIncompleteType()) return;
  11356. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  11357. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  11358. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  11359. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  11360. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  11361. if (UO->getOpcode() == UO_AddrOf)
  11362. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  11363. }
  11364. if (SrcAlign >= DestAlign) return;
  11365. Diag(TRange.getBegin(), diag::warn_cast_align)
  11366. << Op->getType() << T
  11367. << static_cast<unsigned>(SrcAlign.getQuantity())
  11368. << static_cast<unsigned>(DestAlign.getQuantity())
  11369. << TRange << Op->getSourceRange();
  11370. }
  11371. /// Check whether this array fits the idiom of a size-one tail padded
  11372. /// array member of a struct.
  11373. ///
  11374. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  11375. /// commonly used to emulate flexible arrays in C89 code.
  11376. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  11377. const NamedDecl *ND) {
  11378. if (Size != 1 || !ND) return false;
  11379. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  11380. if (!FD) return false;
  11381. // Don't consider sizes resulting from macro expansions or template argument
  11382. // substitution to form C89 tail-padded arrays.
  11383. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  11384. while (TInfo) {
  11385. TypeLoc TL = TInfo->getTypeLoc();
  11386. // Look through typedefs.
  11387. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  11388. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  11389. TInfo = TDL->getTypeSourceInfo();
  11390. continue;
  11391. }
  11392. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  11393. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  11394. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  11395. return false;
  11396. }
  11397. break;
  11398. }
  11399. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  11400. if (!RD) return false;
  11401. if (RD->isUnion()) return false;
  11402. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  11403. if (!CRD->isStandardLayout()) return false;
  11404. }
  11405. // See if this is the last field decl in the record.
  11406. const Decl *D = FD;
  11407. while ((D = D->getNextDeclInContext()))
  11408. if (isa<FieldDecl>(D))
  11409. return false;
  11410. return true;
  11411. }
  11412. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  11413. const ArraySubscriptExpr *ASE,
  11414. bool AllowOnePastEnd, bool IndexNegated) {
  11415. // Already diagnosed by the constant evaluator.
  11416. if (isConstantEvaluated())
  11417. return;
  11418. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  11419. if (IndexExpr->isValueDependent())
  11420. return;
  11421. const Type *EffectiveType =
  11422. BaseExpr->getType()->getPointeeOrArrayElementType();
  11423. BaseExpr = BaseExpr->IgnoreParenCasts();
  11424. const ConstantArrayType *ArrayTy =
  11425. Context.getAsConstantArrayType(BaseExpr->getType());
  11426. if (!ArrayTy)
  11427. return;
  11428. const Type *BaseType = ArrayTy->getElementType().getTypePtr();
  11429. if (EffectiveType->isDependentType() || BaseType->isDependentType())
  11430. return;
  11431. Expr::EvalResult Result;
  11432. if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
  11433. return;
  11434. llvm::APSInt index = Result.Val.getInt();
  11435. if (IndexNegated)
  11436. index = -index;
  11437. const NamedDecl *ND = nullptr;
  11438. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11439. ND = DRE->getDecl();
  11440. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11441. ND = ME->getMemberDecl();
  11442. if (index.isUnsigned() || !index.isNegative()) {
  11443. // It is possible that the type of the base expression after
  11444. // IgnoreParenCasts is incomplete, even though the type of the base
  11445. // expression before IgnoreParenCasts is complete (see PR39746 for an
  11446. // example). In this case we have no information about whether the array
  11447. // access exceeds the array bounds. However we can still diagnose an array
  11448. // access which precedes the array bounds.
  11449. if (BaseType->isIncompleteType())
  11450. return;
  11451. llvm::APInt size = ArrayTy->getSize();
  11452. if (!size.isStrictlyPositive())
  11453. return;
  11454. if (BaseType != EffectiveType) {
  11455. // Make sure we're comparing apples to apples when comparing index to size
  11456. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  11457. uint64_t array_typesize = Context.getTypeSize(BaseType);
  11458. // Handle ptrarith_typesize being zero, such as when casting to void*
  11459. if (!ptrarith_typesize) ptrarith_typesize = 1;
  11460. if (ptrarith_typesize != array_typesize) {
  11461. // There's a cast to a different size type involved
  11462. uint64_t ratio = array_typesize / ptrarith_typesize;
  11463. // TODO: Be smarter about handling cases where array_typesize is not a
  11464. // multiple of ptrarith_typesize
  11465. if (ptrarith_typesize * ratio == array_typesize)
  11466. size *= llvm::APInt(size.getBitWidth(), ratio);
  11467. }
  11468. }
  11469. if (size.getBitWidth() > index.getBitWidth())
  11470. index = index.zext(size.getBitWidth());
  11471. else if (size.getBitWidth() < index.getBitWidth())
  11472. size = size.zext(index.getBitWidth());
  11473. // For array subscripting the index must be less than size, but for pointer
  11474. // arithmetic also allow the index (offset) to be equal to size since
  11475. // computing the next address after the end of the array is legal and
  11476. // commonly done e.g. in C++ iterators and range-based for loops.
  11477. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  11478. return;
  11479. // Also don't warn for arrays of size 1 which are members of some
  11480. // structure. These are often used to approximate flexible arrays in C89
  11481. // code.
  11482. if (IsTailPaddedMemberArray(*this, size, ND))
  11483. return;
  11484. // Suppress the warning if the subscript expression (as identified by the
  11485. // ']' location) and the index expression are both from macro expansions
  11486. // within a system header.
  11487. if (ASE) {
  11488. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  11489. ASE->getRBracketLoc());
  11490. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  11491. SourceLocation IndexLoc =
  11492. SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
  11493. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  11494. return;
  11495. }
  11496. }
  11497. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  11498. if (ASE)
  11499. DiagID = diag::warn_array_index_exceeds_bounds;
  11500. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11501. PDiag(DiagID) << index.toString(10, true)
  11502. << size.toString(10, true)
  11503. << (unsigned)size.getLimitedValue(~0U)
  11504. << IndexExpr->getSourceRange());
  11505. } else {
  11506. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  11507. if (!ASE) {
  11508. DiagID = diag::warn_ptr_arith_precedes_bounds;
  11509. if (index.isNegative()) index = -index;
  11510. }
  11511. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11512. PDiag(DiagID) << index.toString(10, true)
  11513. << IndexExpr->getSourceRange());
  11514. }
  11515. if (!ND) {
  11516. // Try harder to find a NamedDecl to point at in the note.
  11517. while (const ArraySubscriptExpr *ASE =
  11518. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  11519. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  11520. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11521. ND = DRE->getDecl();
  11522. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11523. ND = ME->getMemberDecl();
  11524. }
  11525. if (ND)
  11526. DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
  11527. PDiag(diag::note_array_index_out_of_bounds)
  11528. << ND->getDeclName());
  11529. }
  11530. void Sema::CheckArrayAccess(const Expr *expr) {
  11531. int AllowOnePastEnd = 0;
  11532. while (expr) {
  11533. expr = expr->IgnoreParenImpCasts();
  11534. switch (expr->getStmtClass()) {
  11535. case Stmt::ArraySubscriptExprClass: {
  11536. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  11537. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  11538. AllowOnePastEnd > 0);
  11539. expr = ASE->getBase();
  11540. break;
  11541. }
  11542. case Stmt::MemberExprClass: {
  11543. expr = cast<MemberExpr>(expr)->getBase();
  11544. break;
  11545. }
  11546. case Stmt::OMPArraySectionExprClass: {
  11547. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  11548. if (ASE->getLowerBound())
  11549. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  11550. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  11551. return;
  11552. }
  11553. case Stmt::UnaryOperatorClass: {
  11554. // Only unwrap the * and & unary operators
  11555. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  11556. expr = UO->getSubExpr();
  11557. switch (UO->getOpcode()) {
  11558. case UO_AddrOf:
  11559. AllowOnePastEnd++;
  11560. break;
  11561. case UO_Deref:
  11562. AllowOnePastEnd--;
  11563. break;
  11564. default:
  11565. return;
  11566. }
  11567. break;
  11568. }
  11569. case Stmt::ConditionalOperatorClass: {
  11570. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  11571. if (const Expr *lhs = cond->getLHS())
  11572. CheckArrayAccess(lhs);
  11573. if (const Expr *rhs = cond->getRHS())
  11574. CheckArrayAccess(rhs);
  11575. return;
  11576. }
  11577. case Stmt::CXXOperatorCallExprClass: {
  11578. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  11579. for (const auto *Arg : OCE->arguments())
  11580. CheckArrayAccess(Arg);
  11581. return;
  11582. }
  11583. default:
  11584. return;
  11585. }
  11586. }
  11587. }
  11588. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  11589. namespace {
  11590. struct RetainCycleOwner {
  11591. VarDecl *Variable = nullptr;
  11592. SourceRange Range;
  11593. SourceLocation Loc;
  11594. bool Indirect = false;
  11595. RetainCycleOwner() = default;
  11596. void setLocsFrom(Expr *e) {
  11597. Loc = e->getExprLoc();
  11598. Range = e->getSourceRange();
  11599. }
  11600. };
  11601. } // namespace
  11602. /// Consider whether capturing the given variable can possibly lead to
  11603. /// a retain cycle.
  11604. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  11605. // In ARC, it's captured strongly iff the variable has __strong
  11606. // lifetime. In MRR, it's captured strongly if the variable is
  11607. // __block and has an appropriate type.
  11608. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11609. return false;
  11610. owner.Variable = var;
  11611. if (ref)
  11612. owner.setLocsFrom(ref);
  11613. return true;
  11614. }
  11615. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11616. while (true) {
  11617. e = e->IgnoreParens();
  11618. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  11619. switch (cast->getCastKind()) {
  11620. case CK_BitCast:
  11621. case CK_LValueBitCast:
  11622. case CK_LValueToRValue:
  11623. case CK_ARCReclaimReturnedObject:
  11624. e = cast->getSubExpr();
  11625. continue;
  11626. default:
  11627. return false;
  11628. }
  11629. }
  11630. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  11631. ObjCIvarDecl *ivar = ref->getDecl();
  11632. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11633. return false;
  11634. // Try to find a retain cycle in the base.
  11635. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  11636. return false;
  11637. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  11638. owner.Indirect = true;
  11639. return true;
  11640. }
  11641. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  11642. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  11643. if (!var) return false;
  11644. return considerVariable(var, ref, owner);
  11645. }
  11646. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  11647. if (member->isArrow()) return false;
  11648. // Don't count this as an indirect ownership.
  11649. e = member->getBase();
  11650. continue;
  11651. }
  11652. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  11653. // Only pay attention to pseudo-objects on property references.
  11654. ObjCPropertyRefExpr *pre
  11655. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  11656. ->IgnoreParens());
  11657. if (!pre) return false;
  11658. if (pre->isImplicitProperty()) return false;
  11659. ObjCPropertyDecl *property = pre->getExplicitProperty();
  11660. if (!property->isRetaining() &&
  11661. !(property->getPropertyIvarDecl() &&
  11662. property->getPropertyIvarDecl()->getType()
  11663. .getObjCLifetime() == Qualifiers::OCL_Strong))
  11664. return false;
  11665. owner.Indirect = true;
  11666. if (pre->isSuperReceiver()) {
  11667. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  11668. if (!owner.Variable)
  11669. return false;
  11670. owner.Loc = pre->getLocation();
  11671. owner.Range = pre->getSourceRange();
  11672. return true;
  11673. }
  11674. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  11675. ->getSourceExpr());
  11676. continue;
  11677. }
  11678. // Array ivars?
  11679. return false;
  11680. }
  11681. }
  11682. namespace {
  11683. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  11684. ASTContext &Context;
  11685. VarDecl *Variable;
  11686. Expr *Capturer = nullptr;
  11687. bool VarWillBeReased = false;
  11688. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  11689. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  11690. Context(Context), Variable(variable) {}
  11691. void VisitDeclRefExpr(DeclRefExpr *ref) {
  11692. if (ref->getDecl() == Variable && !Capturer)
  11693. Capturer = ref;
  11694. }
  11695. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  11696. if (Capturer) return;
  11697. Visit(ref->getBase());
  11698. if (Capturer && ref->isFreeIvar())
  11699. Capturer = ref;
  11700. }
  11701. void VisitBlockExpr(BlockExpr *block) {
  11702. // Look inside nested blocks
  11703. if (block->getBlockDecl()->capturesVariable(Variable))
  11704. Visit(block->getBlockDecl()->getBody());
  11705. }
  11706. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  11707. if (Capturer) return;
  11708. if (OVE->getSourceExpr())
  11709. Visit(OVE->getSourceExpr());
  11710. }
  11711. void VisitBinaryOperator(BinaryOperator *BinOp) {
  11712. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  11713. return;
  11714. Expr *LHS = BinOp->getLHS();
  11715. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  11716. if (DRE->getDecl() != Variable)
  11717. return;
  11718. if (Expr *RHS = BinOp->getRHS()) {
  11719. RHS = RHS->IgnoreParenCasts();
  11720. llvm::APSInt Value;
  11721. VarWillBeReased =
  11722. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  11723. }
  11724. }
  11725. }
  11726. };
  11727. } // namespace
  11728. /// Check whether the given argument is a block which captures a
  11729. /// variable.
  11730. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11731. assert(owner.Variable && owner.Loc.isValid());
  11732. e = e->IgnoreParenCasts();
  11733. // Look through [^{...} copy] and Block_copy(^{...}).
  11734. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  11735. Selector Cmd = ME->getSelector();
  11736. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  11737. e = ME->getInstanceReceiver();
  11738. if (!e)
  11739. return nullptr;
  11740. e = e->IgnoreParenCasts();
  11741. }
  11742. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  11743. if (CE->getNumArgs() == 1) {
  11744. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  11745. if (Fn) {
  11746. const IdentifierInfo *FnI = Fn->getIdentifier();
  11747. if (FnI && FnI->isStr("_Block_copy")) {
  11748. e = CE->getArg(0)->IgnoreParenCasts();
  11749. }
  11750. }
  11751. }
  11752. }
  11753. BlockExpr *block = dyn_cast<BlockExpr>(e);
  11754. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  11755. return nullptr;
  11756. FindCaptureVisitor visitor(S.Context, owner.Variable);
  11757. visitor.Visit(block->getBlockDecl()->getBody());
  11758. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  11759. }
  11760. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  11761. RetainCycleOwner &owner) {
  11762. assert(capturer);
  11763. assert(owner.Variable && owner.Loc.isValid());
  11764. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  11765. << owner.Variable << capturer->getSourceRange();
  11766. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  11767. << owner.Indirect << owner.Range;
  11768. }
  11769. /// Check for a keyword selector that starts with the word 'add' or
  11770. /// 'set'.
  11771. static bool isSetterLikeSelector(Selector sel) {
  11772. if (sel.isUnarySelector()) return false;
  11773. StringRef str = sel.getNameForSlot(0);
  11774. while (!str.empty() && str.front() == '_') str = str.substr(1);
  11775. if (str.startswith("set"))
  11776. str = str.substr(3);
  11777. else if (str.startswith("add")) {
  11778. // Specially whitelist 'addOperationWithBlock:'.
  11779. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  11780. return false;
  11781. str = str.substr(3);
  11782. }
  11783. else
  11784. return false;
  11785. if (str.empty()) return true;
  11786. return !isLowercase(str.front());
  11787. }
  11788. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  11789. ObjCMessageExpr *Message) {
  11790. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  11791. Message->getReceiverInterface(),
  11792. NSAPI::ClassId_NSMutableArray);
  11793. if (!IsMutableArray) {
  11794. return None;
  11795. }
  11796. Selector Sel = Message->getSelector();
  11797. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  11798. S.NSAPIObj->getNSArrayMethodKind(Sel);
  11799. if (!MKOpt) {
  11800. return None;
  11801. }
  11802. NSAPI::NSArrayMethodKind MK = *MKOpt;
  11803. switch (MK) {
  11804. case NSAPI::NSMutableArr_addObject:
  11805. case NSAPI::NSMutableArr_insertObjectAtIndex:
  11806. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  11807. return 0;
  11808. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  11809. return 1;
  11810. default:
  11811. return None;
  11812. }
  11813. return None;
  11814. }
  11815. static
  11816. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  11817. ObjCMessageExpr *Message) {
  11818. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  11819. Message->getReceiverInterface(),
  11820. NSAPI::ClassId_NSMutableDictionary);
  11821. if (!IsMutableDictionary) {
  11822. return None;
  11823. }
  11824. Selector Sel = Message->getSelector();
  11825. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  11826. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  11827. if (!MKOpt) {
  11828. return None;
  11829. }
  11830. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  11831. switch (MK) {
  11832. case NSAPI::NSMutableDict_setObjectForKey:
  11833. case NSAPI::NSMutableDict_setValueForKey:
  11834. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  11835. return 0;
  11836. default:
  11837. return None;
  11838. }
  11839. return None;
  11840. }
  11841. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  11842. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  11843. Message->getReceiverInterface(),
  11844. NSAPI::ClassId_NSMutableSet);
  11845. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  11846. Message->getReceiverInterface(),
  11847. NSAPI::ClassId_NSMutableOrderedSet);
  11848. if (!IsMutableSet && !IsMutableOrderedSet) {
  11849. return None;
  11850. }
  11851. Selector Sel = Message->getSelector();
  11852. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  11853. if (!MKOpt) {
  11854. return None;
  11855. }
  11856. NSAPI::NSSetMethodKind MK = *MKOpt;
  11857. switch (MK) {
  11858. case NSAPI::NSMutableSet_addObject:
  11859. case NSAPI::NSOrderedSet_setObjectAtIndex:
  11860. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  11861. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  11862. return 0;
  11863. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  11864. return 1;
  11865. }
  11866. return None;
  11867. }
  11868. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  11869. if (!Message->isInstanceMessage()) {
  11870. return;
  11871. }
  11872. Optional<int> ArgOpt;
  11873. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  11874. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  11875. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  11876. return;
  11877. }
  11878. int ArgIndex = *ArgOpt;
  11879. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  11880. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  11881. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  11882. }
  11883. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  11884. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11885. if (ArgRE->isObjCSelfExpr()) {
  11886. Diag(Message->getSourceRange().getBegin(),
  11887. diag::warn_objc_circular_container)
  11888. << ArgRE->getDecl() << StringRef("'super'");
  11889. }
  11890. }
  11891. } else {
  11892. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  11893. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  11894. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  11895. }
  11896. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  11897. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11898. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  11899. ValueDecl *Decl = ReceiverRE->getDecl();
  11900. Diag(Message->getSourceRange().getBegin(),
  11901. diag::warn_objc_circular_container)
  11902. << Decl << Decl;
  11903. if (!ArgRE->isObjCSelfExpr()) {
  11904. Diag(Decl->getLocation(),
  11905. diag::note_objc_circular_container_declared_here)
  11906. << Decl;
  11907. }
  11908. }
  11909. }
  11910. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  11911. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  11912. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  11913. ObjCIvarDecl *Decl = IvarRE->getDecl();
  11914. Diag(Message->getSourceRange().getBegin(),
  11915. diag::warn_objc_circular_container)
  11916. << Decl << Decl;
  11917. Diag(Decl->getLocation(),
  11918. diag::note_objc_circular_container_declared_here)
  11919. << Decl;
  11920. }
  11921. }
  11922. }
  11923. }
  11924. }
  11925. /// Check a message send to see if it's likely to cause a retain cycle.
  11926. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  11927. // Only check instance methods whose selector looks like a setter.
  11928. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  11929. return;
  11930. // Try to find a variable that the receiver is strongly owned by.
  11931. RetainCycleOwner owner;
  11932. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  11933. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  11934. return;
  11935. } else {
  11936. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  11937. owner.Variable = getCurMethodDecl()->getSelfDecl();
  11938. owner.Loc = msg->getSuperLoc();
  11939. owner.Range = msg->getSuperLoc();
  11940. }
  11941. // Check whether the receiver is captured by any of the arguments.
  11942. const ObjCMethodDecl *MD = msg->getMethodDecl();
  11943. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  11944. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  11945. // noescape blocks should not be retained by the method.
  11946. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  11947. continue;
  11948. return diagnoseRetainCycle(*this, capturer, owner);
  11949. }
  11950. }
  11951. }
  11952. /// Check a property assign to see if it's likely to cause a retain cycle.
  11953. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  11954. RetainCycleOwner owner;
  11955. if (!findRetainCycleOwner(*this, receiver, owner))
  11956. return;
  11957. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  11958. diagnoseRetainCycle(*this, capturer, owner);
  11959. }
  11960. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  11961. RetainCycleOwner Owner;
  11962. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  11963. return;
  11964. // Because we don't have an expression for the variable, we have to set the
  11965. // location explicitly here.
  11966. Owner.Loc = Var->getLocation();
  11967. Owner.Range = Var->getSourceRange();
  11968. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  11969. diagnoseRetainCycle(*this, Capturer, Owner);
  11970. }
  11971. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  11972. Expr *RHS, bool isProperty) {
  11973. // Check if RHS is an Objective-C object literal, which also can get
  11974. // immediately zapped in a weak reference. Note that we explicitly
  11975. // allow ObjCStringLiterals, since those are designed to never really die.
  11976. RHS = RHS->IgnoreParenImpCasts();
  11977. // This enum needs to match with the 'select' in
  11978. // warn_objc_arc_literal_assign (off-by-1).
  11979. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  11980. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  11981. return false;
  11982. S.Diag(Loc, diag::warn_arc_literal_assign)
  11983. << (unsigned) Kind
  11984. << (isProperty ? 0 : 1)
  11985. << RHS->getSourceRange();
  11986. return true;
  11987. }
  11988. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  11989. Qualifiers::ObjCLifetime LT,
  11990. Expr *RHS, bool isProperty) {
  11991. // Strip off any implicit cast added to get to the one ARC-specific.
  11992. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11993. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11994. S.Diag(Loc, diag::warn_arc_retained_assign)
  11995. << (LT == Qualifiers::OCL_ExplicitNone)
  11996. << (isProperty ? 0 : 1)
  11997. << RHS->getSourceRange();
  11998. return true;
  11999. }
  12000. RHS = cast->getSubExpr();
  12001. }
  12002. if (LT == Qualifiers::OCL_Weak &&
  12003. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  12004. return true;
  12005. return false;
  12006. }
  12007. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  12008. QualType LHS, Expr *RHS) {
  12009. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  12010. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  12011. return false;
  12012. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  12013. return true;
  12014. return false;
  12015. }
  12016. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  12017. Expr *LHS, Expr *RHS) {
  12018. QualType LHSType;
  12019. // PropertyRef on LHS type need be directly obtained from
  12020. // its declaration as it has a PseudoType.
  12021. ObjCPropertyRefExpr *PRE
  12022. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  12023. if (PRE && !PRE->isImplicitProperty()) {
  12024. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  12025. if (PD)
  12026. LHSType = PD->getType();
  12027. }
  12028. if (LHSType.isNull())
  12029. LHSType = LHS->getType();
  12030. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  12031. if (LT == Qualifiers::OCL_Weak) {
  12032. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  12033. getCurFunction()->markSafeWeakUse(LHS);
  12034. }
  12035. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  12036. return;
  12037. // FIXME. Check for other life times.
  12038. if (LT != Qualifiers::OCL_None)
  12039. return;
  12040. if (PRE) {
  12041. if (PRE->isImplicitProperty())
  12042. return;
  12043. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  12044. if (!PD)
  12045. return;
  12046. unsigned Attributes = PD->getPropertyAttributes();
  12047. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  12048. // when 'assign' attribute was not explicitly specified
  12049. // by user, ignore it and rely on property type itself
  12050. // for lifetime info.
  12051. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  12052. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  12053. LHSType->isObjCRetainableType())
  12054. return;
  12055. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  12056. if (cast->getCastKind() == CK_ARCConsumeObject) {
  12057. Diag(Loc, diag::warn_arc_retained_property_assign)
  12058. << RHS->getSourceRange();
  12059. return;
  12060. }
  12061. RHS = cast->getSubExpr();
  12062. }
  12063. }
  12064. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  12065. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  12066. return;
  12067. }
  12068. }
  12069. }
  12070. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  12071. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  12072. SourceLocation StmtLoc,
  12073. const NullStmt *Body) {
  12074. // Do not warn if the body is a macro that expands to nothing, e.g:
  12075. //
  12076. // #define CALL(x)
  12077. // if (condition)
  12078. // CALL(0);
  12079. if (Body->hasLeadingEmptyMacro())
  12080. return false;
  12081. // Get line numbers of statement and body.
  12082. bool StmtLineInvalid;
  12083. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  12084. &StmtLineInvalid);
  12085. if (StmtLineInvalid)
  12086. return false;
  12087. bool BodyLineInvalid;
  12088. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  12089. &BodyLineInvalid);
  12090. if (BodyLineInvalid)
  12091. return false;
  12092. // Warn if null statement and body are on the same line.
  12093. if (StmtLine != BodyLine)
  12094. return false;
  12095. return true;
  12096. }
  12097. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  12098. const Stmt *Body,
  12099. unsigned DiagID) {
  12100. // Since this is a syntactic check, don't emit diagnostic for template
  12101. // instantiations, this just adds noise.
  12102. if (CurrentInstantiationScope)
  12103. return;
  12104. // The body should be a null statement.
  12105. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  12106. if (!NBody)
  12107. return;
  12108. // Do the usual checks.
  12109. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  12110. return;
  12111. Diag(NBody->getSemiLoc(), DiagID);
  12112. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  12113. }
  12114. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  12115. const Stmt *PossibleBody) {
  12116. assert(!CurrentInstantiationScope); // Ensured by caller
  12117. SourceLocation StmtLoc;
  12118. const Stmt *Body;
  12119. unsigned DiagID;
  12120. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  12121. StmtLoc = FS->getRParenLoc();
  12122. Body = FS->getBody();
  12123. DiagID = diag::warn_empty_for_body;
  12124. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  12125. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  12126. Body = WS->getBody();
  12127. DiagID = diag::warn_empty_while_body;
  12128. } else
  12129. return; // Neither `for' nor `while'.
  12130. // The body should be a null statement.
  12131. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  12132. if (!NBody)
  12133. return;
  12134. // Skip expensive checks if diagnostic is disabled.
  12135. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  12136. return;
  12137. // Do the usual checks.
  12138. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  12139. return;
  12140. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  12141. // noise level low, emit diagnostics only if for/while is followed by a
  12142. // CompoundStmt, e.g.:
  12143. // for (int i = 0; i < n; i++);
  12144. // {
  12145. // a(i);
  12146. // }
  12147. // or if for/while is followed by a statement with more indentation
  12148. // than for/while itself:
  12149. // for (int i = 0; i < n; i++);
  12150. // a(i);
  12151. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  12152. if (!ProbableTypo) {
  12153. bool BodyColInvalid;
  12154. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  12155. PossibleBody->getBeginLoc(), &BodyColInvalid);
  12156. if (BodyColInvalid)
  12157. return;
  12158. bool StmtColInvalid;
  12159. unsigned StmtCol =
  12160. SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
  12161. if (StmtColInvalid)
  12162. return;
  12163. if (BodyCol > StmtCol)
  12164. ProbableTypo = true;
  12165. }
  12166. if (ProbableTypo) {
  12167. Diag(NBody->getSemiLoc(), DiagID);
  12168. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  12169. }
  12170. }
  12171. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  12172. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  12173. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  12174. SourceLocation OpLoc) {
  12175. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  12176. return;
  12177. if (inTemplateInstantiation())
  12178. return;
  12179. // Strip parens and casts away.
  12180. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  12181. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  12182. // Check for a call expression
  12183. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  12184. if (!CE || CE->getNumArgs() != 1)
  12185. return;
  12186. // Check for a call to std::move
  12187. if (!CE->isCallToStdMove())
  12188. return;
  12189. // Get argument from std::move
  12190. RHSExpr = CE->getArg(0);
  12191. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  12192. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  12193. // Two DeclRefExpr's, check that the decls are the same.
  12194. if (LHSDeclRef && RHSDeclRef) {
  12195. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12196. return;
  12197. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12198. RHSDeclRef->getDecl()->getCanonicalDecl())
  12199. return;
  12200. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12201. << LHSExpr->getSourceRange()
  12202. << RHSExpr->getSourceRange();
  12203. return;
  12204. }
  12205. // Member variables require a different approach to check for self moves.
  12206. // MemberExpr's are the same if every nested MemberExpr refers to the same
  12207. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  12208. // the base Expr's are CXXThisExpr's.
  12209. const Expr *LHSBase = LHSExpr;
  12210. const Expr *RHSBase = RHSExpr;
  12211. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  12212. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  12213. if (!LHSME || !RHSME)
  12214. return;
  12215. while (LHSME && RHSME) {
  12216. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  12217. RHSME->getMemberDecl()->getCanonicalDecl())
  12218. return;
  12219. LHSBase = LHSME->getBase();
  12220. RHSBase = RHSME->getBase();
  12221. LHSME = dyn_cast<MemberExpr>(LHSBase);
  12222. RHSME = dyn_cast<MemberExpr>(RHSBase);
  12223. }
  12224. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  12225. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  12226. if (LHSDeclRef && RHSDeclRef) {
  12227. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12228. return;
  12229. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12230. RHSDeclRef->getDecl()->getCanonicalDecl())
  12231. return;
  12232. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12233. << LHSExpr->getSourceRange()
  12234. << RHSExpr->getSourceRange();
  12235. return;
  12236. }
  12237. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  12238. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12239. << LHSExpr->getSourceRange()
  12240. << RHSExpr->getSourceRange();
  12241. }
  12242. //===--- Layout compatibility ----------------------------------------------//
  12243. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  12244. /// Check if two enumeration types are layout-compatible.
  12245. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  12246. // C++11 [dcl.enum] p8:
  12247. // Two enumeration types are layout-compatible if they have the same
  12248. // underlying type.
  12249. return ED1->isComplete() && ED2->isComplete() &&
  12250. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  12251. }
  12252. /// Check if two fields are layout-compatible.
  12253. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  12254. FieldDecl *Field2) {
  12255. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  12256. return false;
  12257. if (Field1->isBitField() != Field2->isBitField())
  12258. return false;
  12259. if (Field1->isBitField()) {
  12260. // Make sure that the bit-fields are the same length.
  12261. unsigned Bits1 = Field1->getBitWidthValue(C);
  12262. unsigned Bits2 = Field2->getBitWidthValue(C);
  12263. if (Bits1 != Bits2)
  12264. return false;
  12265. }
  12266. return true;
  12267. }
  12268. /// Check if two standard-layout structs are layout-compatible.
  12269. /// (C++11 [class.mem] p17)
  12270. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  12271. RecordDecl *RD2) {
  12272. // If both records are C++ classes, check that base classes match.
  12273. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  12274. // If one of records is a CXXRecordDecl we are in C++ mode,
  12275. // thus the other one is a CXXRecordDecl, too.
  12276. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  12277. // Check number of base classes.
  12278. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  12279. return false;
  12280. // Check the base classes.
  12281. for (CXXRecordDecl::base_class_const_iterator
  12282. Base1 = D1CXX->bases_begin(),
  12283. BaseEnd1 = D1CXX->bases_end(),
  12284. Base2 = D2CXX->bases_begin();
  12285. Base1 != BaseEnd1;
  12286. ++Base1, ++Base2) {
  12287. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  12288. return false;
  12289. }
  12290. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  12291. // If only RD2 is a C++ class, it should have zero base classes.
  12292. if (D2CXX->getNumBases() > 0)
  12293. return false;
  12294. }
  12295. // Check the fields.
  12296. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  12297. Field2End = RD2->field_end(),
  12298. Field1 = RD1->field_begin(),
  12299. Field1End = RD1->field_end();
  12300. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  12301. if (!isLayoutCompatible(C, *Field1, *Field2))
  12302. return false;
  12303. }
  12304. if (Field1 != Field1End || Field2 != Field2End)
  12305. return false;
  12306. return true;
  12307. }
  12308. /// Check if two standard-layout unions are layout-compatible.
  12309. /// (C++11 [class.mem] p18)
  12310. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  12311. RecordDecl *RD2) {
  12312. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  12313. for (auto *Field2 : RD2->fields())
  12314. UnmatchedFields.insert(Field2);
  12315. for (auto *Field1 : RD1->fields()) {
  12316. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  12317. I = UnmatchedFields.begin(),
  12318. E = UnmatchedFields.end();
  12319. for ( ; I != E; ++I) {
  12320. if (isLayoutCompatible(C, Field1, *I)) {
  12321. bool Result = UnmatchedFields.erase(*I);
  12322. (void) Result;
  12323. assert(Result);
  12324. break;
  12325. }
  12326. }
  12327. if (I == E)
  12328. return false;
  12329. }
  12330. return UnmatchedFields.empty();
  12331. }
  12332. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  12333. RecordDecl *RD2) {
  12334. if (RD1->isUnion() != RD2->isUnion())
  12335. return false;
  12336. if (RD1->isUnion())
  12337. return isLayoutCompatibleUnion(C, RD1, RD2);
  12338. else
  12339. return isLayoutCompatibleStruct(C, RD1, RD2);
  12340. }
  12341. /// Check if two types are layout-compatible in C++11 sense.
  12342. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  12343. if (T1.isNull() || T2.isNull())
  12344. return false;
  12345. // C++11 [basic.types] p11:
  12346. // If two types T1 and T2 are the same type, then T1 and T2 are
  12347. // layout-compatible types.
  12348. if (C.hasSameType(T1, T2))
  12349. return true;
  12350. T1 = T1.getCanonicalType().getUnqualifiedType();
  12351. T2 = T2.getCanonicalType().getUnqualifiedType();
  12352. const Type::TypeClass TC1 = T1->getTypeClass();
  12353. const Type::TypeClass TC2 = T2->getTypeClass();
  12354. if (TC1 != TC2)
  12355. return false;
  12356. if (TC1 == Type::Enum) {
  12357. return isLayoutCompatible(C,
  12358. cast<EnumType>(T1)->getDecl(),
  12359. cast<EnumType>(T2)->getDecl());
  12360. } else if (TC1 == Type::Record) {
  12361. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  12362. return false;
  12363. return isLayoutCompatible(C,
  12364. cast<RecordType>(T1)->getDecl(),
  12365. cast<RecordType>(T2)->getDecl());
  12366. }
  12367. return false;
  12368. }
  12369. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  12370. /// Given a type tag expression find the type tag itself.
  12371. ///
  12372. /// \param TypeExpr Type tag expression, as it appears in user's code.
  12373. ///
  12374. /// \param VD Declaration of an identifier that appears in a type tag.
  12375. ///
  12376. /// \param MagicValue Type tag magic value.
  12377. ///
  12378. /// \param isConstantEvaluated wether the evalaution should be performed in
  12379. /// constant context.
  12380. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  12381. const ValueDecl **VD, uint64_t *MagicValue,
  12382. bool isConstantEvaluated) {
  12383. while(true) {
  12384. if (!TypeExpr)
  12385. return false;
  12386. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  12387. switch (TypeExpr->getStmtClass()) {
  12388. case Stmt::UnaryOperatorClass: {
  12389. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  12390. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  12391. TypeExpr = UO->getSubExpr();
  12392. continue;
  12393. }
  12394. return false;
  12395. }
  12396. case Stmt::DeclRefExprClass: {
  12397. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  12398. *VD = DRE->getDecl();
  12399. return true;
  12400. }
  12401. case Stmt::IntegerLiteralClass: {
  12402. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  12403. llvm::APInt MagicValueAPInt = IL->getValue();
  12404. if (MagicValueAPInt.getActiveBits() <= 64) {
  12405. *MagicValue = MagicValueAPInt.getZExtValue();
  12406. return true;
  12407. } else
  12408. return false;
  12409. }
  12410. case Stmt::BinaryConditionalOperatorClass:
  12411. case Stmt::ConditionalOperatorClass: {
  12412. const AbstractConditionalOperator *ACO =
  12413. cast<AbstractConditionalOperator>(TypeExpr);
  12414. bool Result;
  12415. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
  12416. isConstantEvaluated)) {
  12417. if (Result)
  12418. TypeExpr = ACO->getTrueExpr();
  12419. else
  12420. TypeExpr = ACO->getFalseExpr();
  12421. continue;
  12422. }
  12423. return false;
  12424. }
  12425. case Stmt::BinaryOperatorClass: {
  12426. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  12427. if (BO->getOpcode() == BO_Comma) {
  12428. TypeExpr = BO->getRHS();
  12429. continue;
  12430. }
  12431. return false;
  12432. }
  12433. default:
  12434. return false;
  12435. }
  12436. }
  12437. }
  12438. /// Retrieve the C type corresponding to type tag TypeExpr.
  12439. ///
  12440. /// \param TypeExpr Expression that specifies a type tag.
  12441. ///
  12442. /// \param MagicValues Registered magic values.
  12443. ///
  12444. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  12445. /// kind.
  12446. ///
  12447. /// \param TypeInfo Information about the corresponding C type.
  12448. ///
  12449. /// \param isConstantEvaluated wether the evalaution should be performed in
  12450. /// constant context.
  12451. ///
  12452. /// \returns true if the corresponding C type was found.
  12453. static bool GetMatchingCType(
  12454. const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
  12455. const ASTContext &Ctx,
  12456. const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
  12457. *MagicValues,
  12458. bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
  12459. bool isConstantEvaluated) {
  12460. FoundWrongKind = false;
  12461. // Variable declaration that has type_tag_for_datatype attribute.
  12462. const ValueDecl *VD = nullptr;
  12463. uint64_t MagicValue;
  12464. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
  12465. return false;
  12466. if (VD) {
  12467. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  12468. if (I->getArgumentKind() != ArgumentKind) {
  12469. FoundWrongKind = true;
  12470. return false;
  12471. }
  12472. TypeInfo.Type = I->getMatchingCType();
  12473. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  12474. TypeInfo.MustBeNull = I->getMustBeNull();
  12475. return true;
  12476. }
  12477. return false;
  12478. }
  12479. if (!MagicValues)
  12480. return false;
  12481. llvm::DenseMap<Sema::TypeTagMagicValue,
  12482. Sema::TypeTagData>::const_iterator I =
  12483. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  12484. if (I == MagicValues->end())
  12485. return false;
  12486. TypeInfo = I->second;
  12487. return true;
  12488. }
  12489. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  12490. uint64_t MagicValue, QualType Type,
  12491. bool LayoutCompatible,
  12492. bool MustBeNull) {
  12493. if (!TypeTagForDatatypeMagicValues)
  12494. TypeTagForDatatypeMagicValues.reset(
  12495. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  12496. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  12497. (*TypeTagForDatatypeMagicValues)[Magic] =
  12498. TypeTagData(Type, LayoutCompatible, MustBeNull);
  12499. }
  12500. static bool IsSameCharType(QualType T1, QualType T2) {
  12501. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  12502. if (!BT1)
  12503. return false;
  12504. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  12505. if (!BT2)
  12506. return false;
  12507. BuiltinType::Kind T1Kind = BT1->getKind();
  12508. BuiltinType::Kind T2Kind = BT2->getKind();
  12509. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  12510. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  12511. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  12512. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  12513. }
  12514. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  12515. const ArrayRef<const Expr *> ExprArgs,
  12516. SourceLocation CallSiteLoc) {
  12517. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  12518. bool IsPointerAttr = Attr->getIsPointer();
  12519. // Retrieve the argument representing the 'type_tag'.
  12520. unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
  12521. if (TypeTagIdxAST >= ExprArgs.size()) {
  12522. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12523. << 0 << Attr->getTypeTagIdx().getSourceIndex();
  12524. return;
  12525. }
  12526. const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
  12527. bool FoundWrongKind;
  12528. TypeTagData TypeInfo;
  12529. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  12530. TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
  12531. TypeInfo, isConstantEvaluated())) {
  12532. if (FoundWrongKind)
  12533. Diag(TypeTagExpr->getExprLoc(),
  12534. diag::warn_type_tag_for_datatype_wrong_kind)
  12535. << TypeTagExpr->getSourceRange();
  12536. return;
  12537. }
  12538. // Retrieve the argument representing the 'arg_idx'.
  12539. unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
  12540. if (ArgumentIdxAST >= ExprArgs.size()) {
  12541. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12542. << 1 << Attr->getArgumentIdx().getSourceIndex();
  12543. return;
  12544. }
  12545. const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
  12546. if (IsPointerAttr) {
  12547. // Skip implicit cast of pointer to `void *' (as a function argument).
  12548. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  12549. if (ICE->getType()->isVoidPointerType() &&
  12550. ICE->getCastKind() == CK_BitCast)
  12551. ArgumentExpr = ICE->getSubExpr();
  12552. }
  12553. QualType ArgumentType = ArgumentExpr->getType();
  12554. // Passing a `void*' pointer shouldn't trigger a warning.
  12555. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  12556. return;
  12557. if (TypeInfo.MustBeNull) {
  12558. // Type tag with matching void type requires a null pointer.
  12559. if (!ArgumentExpr->isNullPointerConstant(Context,
  12560. Expr::NPC_ValueDependentIsNotNull)) {
  12561. Diag(ArgumentExpr->getExprLoc(),
  12562. diag::warn_type_safety_null_pointer_required)
  12563. << ArgumentKind->getName()
  12564. << ArgumentExpr->getSourceRange()
  12565. << TypeTagExpr->getSourceRange();
  12566. }
  12567. return;
  12568. }
  12569. QualType RequiredType = TypeInfo.Type;
  12570. if (IsPointerAttr)
  12571. RequiredType = Context.getPointerType(RequiredType);
  12572. bool mismatch = false;
  12573. if (!TypeInfo.LayoutCompatible) {
  12574. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  12575. // C++11 [basic.fundamental] p1:
  12576. // Plain char, signed char, and unsigned char are three distinct types.
  12577. //
  12578. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  12579. // char' depending on the current char signedness mode.
  12580. if (mismatch)
  12581. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  12582. RequiredType->getPointeeType())) ||
  12583. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  12584. mismatch = false;
  12585. } else
  12586. if (IsPointerAttr)
  12587. mismatch = !isLayoutCompatible(Context,
  12588. ArgumentType->getPointeeType(),
  12589. RequiredType->getPointeeType());
  12590. else
  12591. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  12592. if (mismatch)
  12593. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  12594. << ArgumentType << ArgumentKind
  12595. << TypeInfo.LayoutCompatible << RequiredType
  12596. << ArgumentExpr->getSourceRange()
  12597. << TypeTagExpr->getSourceRange();
  12598. }
  12599. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  12600. CharUnits Alignment) {
  12601. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  12602. }
  12603. void Sema::DiagnoseMisalignedMembers() {
  12604. for (MisalignedMember &m : MisalignedMembers) {
  12605. const NamedDecl *ND = m.RD;
  12606. if (ND->getName().empty()) {
  12607. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  12608. ND = TD;
  12609. }
  12610. Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
  12611. << m.MD << ND << m.E->getSourceRange();
  12612. }
  12613. MisalignedMembers.clear();
  12614. }
  12615. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  12616. E = E->IgnoreParens();
  12617. if (!T->isPointerType() && !T->isIntegerType())
  12618. return;
  12619. if (isa<UnaryOperator>(E) &&
  12620. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  12621. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  12622. if (isa<MemberExpr>(Op)) {
  12623. auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
  12624. if (MA != MisalignedMembers.end() &&
  12625. (T->isIntegerType() ||
  12626. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  12627. Context.getTypeAlignInChars(
  12628. T->getPointeeType()) <= MA->Alignment))))
  12629. MisalignedMembers.erase(MA);
  12630. }
  12631. }
  12632. }
  12633. void Sema::RefersToMemberWithReducedAlignment(
  12634. Expr *E,
  12635. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  12636. Action) {
  12637. const auto *ME = dyn_cast<MemberExpr>(E);
  12638. if (!ME)
  12639. return;
  12640. // No need to check expressions with an __unaligned-qualified type.
  12641. if (E->getType().getQualifiers().hasUnaligned())
  12642. return;
  12643. // For a chain of MemberExpr like "a.b.c.d" this list
  12644. // will keep FieldDecl's like [d, c, b].
  12645. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  12646. const MemberExpr *TopME = nullptr;
  12647. bool AnyIsPacked = false;
  12648. do {
  12649. QualType BaseType = ME->getBase()->getType();
  12650. if (ME->isArrow())
  12651. BaseType = BaseType->getPointeeType();
  12652. RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
  12653. if (RD->isInvalidDecl())
  12654. return;
  12655. ValueDecl *MD = ME->getMemberDecl();
  12656. auto *FD = dyn_cast<FieldDecl>(MD);
  12657. // We do not care about non-data members.
  12658. if (!FD || FD->isInvalidDecl())
  12659. return;
  12660. AnyIsPacked =
  12661. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  12662. ReverseMemberChain.push_back(FD);
  12663. TopME = ME;
  12664. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  12665. } while (ME);
  12666. assert(TopME && "We did not compute a topmost MemberExpr!");
  12667. // Not the scope of this diagnostic.
  12668. if (!AnyIsPacked)
  12669. return;
  12670. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  12671. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  12672. // TODO: The innermost base of the member expression may be too complicated.
  12673. // For now, just disregard these cases. This is left for future
  12674. // improvement.
  12675. if (!DRE && !isa<CXXThisExpr>(TopBase))
  12676. return;
  12677. // Alignment expected by the whole expression.
  12678. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  12679. // No need to do anything else with this case.
  12680. if (ExpectedAlignment.isOne())
  12681. return;
  12682. // Synthesize offset of the whole access.
  12683. CharUnits Offset;
  12684. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  12685. I++) {
  12686. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  12687. }
  12688. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  12689. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  12690. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  12691. // The base expression of the innermost MemberExpr may give
  12692. // stronger guarantees than the class containing the member.
  12693. if (DRE && !TopME->isArrow()) {
  12694. const ValueDecl *VD = DRE->getDecl();
  12695. if (!VD->getType()->isReferenceType())
  12696. CompleteObjectAlignment =
  12697. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  12698. }
  12699. // Check if the synthesized offset fulfills the alignment.
  12700. if (Offset % ExpectedAlignment != 0 ||
  12701. // It may fulfill the offset it but the effective alignment may still be
  12702. // lower than the expected expression alignment.
  12703. CompleteObjectAlignment < ExpectedAlignment) {
  12704. // If this happens, we want to determine a sensible culprit of this.
  12705. // Intuitively, watching the chain of member expressions from right to
  12706. // left, we start with the required alignment (as required by the field
  12707. // type) but some packed attribute in that chain has reduced the alignment.
  12708. // It may happen that another packed structure increases it again. But if
  12709. // we are here such increase has not been enough. So pointing the first
  12710. // FieldDecl that either is packed or else its RecordDecl is,
  12711. // seems reasonable.
  12712. FieldDecl *FD = nullptr;
  12713. CharUnits Alignment;
  12714. for (FieldDecl *FDI : ReverseMemberChain) {
  12715. if (FDI->hasAttr<PackedAttr>() ||
  12716. FDI->getParent()->hasAttr<PackedAttr>()) {
  12717. FD = FDI;
  12718. Alignment = std::min(
  12719. Context.getTypeAlignInChars(FD->getType()),
  12720. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  12721. break;
  12722. }
  12723. }
  12724. assert(FD && "We did not find a packed FieldDecl!");
  12725. Action(E, FD->getParent(), FD, Alignment);
  12726. }
  12727. }
  12728. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  12729. using namespace std::placeholders;
  12730. RefersToMemberWithReducedAlignment(
  12731. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  12732. _2, _3, _4));
  12733. }