SemaChecking.cpp 533 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637
  1. //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements extra semantic analysis beyond what is enforced
  11. // by the C type system.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/AST/APValue.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/Attr.h"
  17. #include "clang/AST/AttrIterator.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclBase.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/DeclarationName.h"
  24. #include "clang/AST/EvaluatedExprVisitor.h"
  25. #include "clang/AST/Expr.h"
  26. #include "clang/AST/ExprCXX.h"
  27. #include "clang/AST/ExprObjC.h"
  28. #include "clang/AST/ExprOpenMP.h"
  29. #include "clang/AST/NSAPI.h"
  30. #include "clang/AST/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/Analysis/Analyses/FormatString.h"
  38. #include "clang/Basic/AddressSpaces.h"
  39. #include "clang/Basic/CharInfo.h"
  40. #include "clang/Basic/Diagnostic.h"
  41. #include "clang/Basic/IdentifierTable.h"
  42. #include "clang/Basic/LLVM.h"
  43. #include "clang/Basic/LangOptions.h"
  44. #include "clang/Basic/OpenCLOptions.h"
  45. #include "clang/Basic/OperatorKinds.h"
  46. #include "clang/Basic/PartialDiagnostic.h"
  47. #include "clang/Basic/SourceLocation.h"
  48. #include "clang/Basic/SourceManager.h"
  49. #include "clang/Basic/Specifiers.h"
  50. #include "clang/Basic/SyncScope.h"
  51. #include "clang/Basic/TargetBuiltins.h"
  52. #include "clang/Basic/TargetCXXABI.h"
  53. #include "clang/Basic/TargetInfo.h"
  54. #include "clang/Basic/TypeTraits.h"
  55. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  56. #include "clang/Sema/Initialization.h"
  57. #include "clang/Sema/Lookup.h"
  58. #include "clang/Sema/Ownership.h"
  59. #include "clang/Sema/Scope.h"
  60. #include "clang/Sema/ScopeInfo.h"
  61. #include "clang/Sema/Sema.h"
  62. #include "clang/Sema/SemaInternal.h"
  63. #include "llvm/ADT/APFloat.h"
  64. #include "llvm/ADT/APInt.h"
  65. #include "llvm/ADT/APSInt.h"
  66. #include "llvm/ADT/ArrayRef.h"
  67. #include "llvm/ADT/DenseMap.h"
  68. #include "llvm/ADT/FoldingSet.h"
  69. #include "llvm/ADT/None.h"
  70. #include "llvm/ADT/Optional.h"
  71. #include "llvm/ADT/STLExtras.h"
  72. #include "llvm/ADT/SmallBitVector.h"
  73. #include "llvm/ADT/SmallPtrSet.h"
  74. #include "llvm/ADT/SmallString.h"
  75. #include "llvm/ADT/SmallVector.h"
  76. #include "llvm/ADT/StringRef.h"
  77. #include "llvm/ADT/StringSwitch.h"
  78. #include "llvm/ADT/Triple.h"
  79. #include "llvm/Support/AtomicOrdering.h"
  80. #include "llvm/Support/Casting.h"
  81. #include "llvm/Support/Compiler.h"
  82. #include "llvm/Support/ConvertUTF.h"
  83. #include "llvm/Support/ErrorHandling.h"
  84. #include "llvm/Support/Format.h"
  85. #include "llvm/Support/Locale.h"
  86. #include "llvm/Support/MathExtras.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->getLocEnd(), 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)->getLocStart(),
  115. call->getArg(argCount - 1)->getLocEnd());
  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->getLocStart(), 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->getLocStart(), 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->getLocEnd(), 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->getLocStart(), 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->getLocStart());
  170. if (ResultType.isNull())
  171. return true;
  172. TheCall->setArg(0, Arg.get());
  173. TheCall->setType(ResultType);
  174. return false;
  175. }
  176. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
  177. if (checkArgCount(S, TheCall, 3))
  178. return true;
  179. // First two arguments should be integers.
  180. for (unsigned I = 0; I < 2; ++I) {
  181. ExprResult Arg = TheCall->getArg(I);
  182. QualType Ty = Arg.get()->getType();
  183. if (!Ty->isIntegerType()) {
  184. S.Diag(Arg.get()->getLocStart(), diag::err_overflow_builtin_must_be_int)
  185. << Ty << Arg.get()->getSourceRange();
  186. return true;
  187. }
  188. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  189. S.getASTContext(), Ty, /*consume*/ false);
  190. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  191. if (Arg.isInvalid())
  192. return true;
  193. TheCall->setArg(I, Arg.get());
  194. }
  195. // Third argument should be a pointer to a non-const integer.
  196. // IRGen correctly handles volatile, restrict, and address spaces, and
  197. // the other qualifiers aren't possible.
  198. {
  199. ExprResult Arg = TheCall->getArg(2);
  200. QualType Ty = Arg.get()->getType();
  201. const auto *PtrTy = Ty->getAs<PointerType>();
  202. if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
  203. !PtrTy->getPointeeType().isConstQualified())) {
  204. S.Diag(Arg.get()->getLocStart(),
  205. diag::err_overflow_builtin_must_be_ptr_int)
  206. << Ty << Arg.get()->getSourceRange();
  207. return true;
  208. }
  209. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  210. S.getASTContext(), Ty, /*consume*/ false);
  211. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  212. if (Arg.isInvalid())
  213. return true;
  214. TheCall->setArg(2, Arg.get());
  215. }
  216. return false;
  217. }
  218. static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
  219. CallExpr *TheCall, unsigned SizeIdx,
  220. unsigned DstSizeIdx) {
  221. if (TheCall->getNumArgs() <= SizeIdx ||
  222. TheCall->getNumArgs() <= DstSizeIdx)
  223. return;
  224. const Expr *SizeArg = TheCall->getArg(SizeIdx);
  225. const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
  226. llvm::APSInt Size, DstSize;
  227. // find out if both sizes are known at compile time
  228. if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
  229. !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
  230. return;
  231. if (Size.ule(DstSize))
  232. return;
  233. // confirmed overflow so generate the diagnostic.
  234. IdentifierInfo *FnName = FDecl->getIdentifier();
  235. SourceLocation SL = TheCall->getLocStart();
  236. SourceRange SR = TheCall->getSourceRange();
  237. S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
  238. }
  239. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  240. if (checkArgCount(S, BuiltinCall, 2))
  241. return true;
  242. SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
  243. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  244. Expr *Call = BuiltinCall->getArg(0);
  245. Expr *Chain = BuiltinCall->getArg(1);
  246. if (Call->getStmtClass() != Stmt::CallExprClass) {
  247. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  248. << Call->getSourceRange();
  249. return true;
  250. }
  251. auto CE = cast<CallExpr>(Call);
  252. if (CE->getCallee()->getType()->isBlockPointerType()) {
  253. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  254. << Call->getSourceRange();
  255. return true;
  256. }
  257. const Decl *TargetDecl = CE->getCalleeDecl();
  258. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  259. if (FD->getBuiltinID()) {
  260. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  261. << Call->getSourceRange();
  262. return true;
  263. }
  264. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  265. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  266. << Call->getSourceRange();
  267. return true;
  268. }
  269. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  270. if (ChainResult.isInvalid())
  271. return true;
  272. if (!ChainResult.get()->getType()->isPointerType()) {
  273. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  274. << Chain->getSourceRange();
  275. return true;
  276. }
  277. QualType ReturnTy = CE->getCallReturnType(S.Context);
  278. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  279. QualType BuiltinTy = S.Context.getFunctionType(
  280. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  281. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  282. Builtin =
  283. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  284. BuiltinCall->setType(CE->getType());
  285. BuiltinCall->setValueKind(CE->getValueKind());
  286. BuiltinCall->setObjectKind(CE->getObjectKind());
  287. BuiltinCall->setCallee(Builtin);
  288. BuiltinCall->setArg(1, ChainResult.get());
  289. return false;
  290. }
  291. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  292. Scope::ScopeFlags NeededScopeFlags,
  293. unsigned DiagID) {
  294. // Scopes aren't available during instantiation. Fortunately, builtin
  295. // functions cannot be template args so they cannot be formed through template
  296. // instantiation. Therefore checking once during the parse is sufficient.
  297. if (SemaRef.inTemplateInstantiation())
  298. return false;
  299. Scope *S = SemaRef.getCurScope();
  300. while (S && !S->isSEHExceptScope())
  301. S = S->getParent();
  302. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  303. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  304. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  305. << DRE->getDecl()->getIdentifier();
  306. return true;
  307. }
  308. return false;
  309. }
  310. static inline bool isBlockPointer(Expr *Arg) {
  311. return Arg->getType()->isBlockPointerType();
  312. }
  313. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  314. /// void*, which is a requirement of device side enqueue.
  315. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  316. const BlockPointerType *BPT =
  317. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  318. ArrayRef<QualType> Params =
  319. BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
  320. unsigned ArgCounter = 0;
  321. bool IllegalParams = false;
  322. // Iterate through the block parameters until either one is found that is not
  323. // a local void*, or the block is valid.
  324. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  325. I != E; ++I, ++ArgCounter) {
  326. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  327. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  328. LangAS::opencl_local) {
  329. // Get the location of the error. If a block literal has been passed
  330. // (BlockExpr) then we can point straight to the offending argument,
  331. // else we just point to the variable reference.
  332. SourceLocation ErrorLoc;
  333. if (isa<BlockExpr>(BlockArg)) {
  334. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  335. ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
  336. } else if (isa<DeclRefExpr>(BlockArg)) {
  337. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
  338. }
  339. S.Diag(ErrorLoc,
  340. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  341. IllegalParams = true;
  342. }
  343. }
  344. return IllegalParams;
  345. }
  346. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  347. if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
  348. S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
  349. << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
  350. return true;
  351. }
  352. return false;
  353. }
  354. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  355. if (checkArgCount(S, TheCall, 2))
  356. return true;
  357. if (checkOpenCLSubgroupExt(S, TheCall))
  358. return true;
  359. // First argument is an ndrange_t type.
  360. Expr *NDRangeArg = TheCall->getArg(0);
  361. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  362. S.Diag(NDRangeArg->getLocStart(),
  363. diag::err_opencl_builtin_expected_type)
  364. << TheCall->getDirectCallee() << "'ndrange_t'";
  365. return true;
  366. }
  367. Expr *BlockArg = TheCall->getArg(1);
  368. if (!isBlockPointer(BlockArg)) {
  369. S.Diag(BlockArg->getLocStart(),
  370. diag::err_opencl_builtin_expected_type)
  371. << TheCall->getDirectCallee() << "block";
  372. return true;
  373. }
  374. return checkOpenCLBlockArgs(S, BlockArg);
  375. }
  376. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  377. /// get_kernel_work_group_size
  378. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  379. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  380. if (checkArgCount(S, TheCall, 1))
  381. return true;
  382. Expr *BlockArg = TheCall->getArg(0);
  383. if (!isBlockPointer(BlockArg)) {
  384. S.Diag(BlockArg->getLocStart(),
  385. diag::err_opencl_builtin_expected_type)
  386. << TheCall->getDirectCallee() << "block";
  387. return true;
  388. }
  389. return checkOpenCLBlockArgs(S, BlockArg);
  390. }
  391. /// Diagnose integer type and any valid implicit conversion to it.
  392. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  393. const QualType &IntType);
  394. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  395. unsigned Start, unsigned End) {
  396. bool IllegalParams = false;
  397. for (unsigned I = Start; I <= End; ++I)
  398. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  399. S.Context.getSizeType());
  400. return IllegalParams;
  401. }
  402. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  403. /// 'local void*' parameter of passed block.
  404. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  405. Expr *BlockArg,
  406. unsigned NumNonVarArgs) {
  407. const BlockPointerType *BPT =
  408. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  409. unsigned NumBlockParams =
  410. BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
  411. unsigned TotalNumArgs = TheCall->getNumArgs();
  412. // For each argument passed to the block, a corresponding uint needs to
  413. // be passed to describe the size of the local memory.
  414. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  415. S.Diag(TheCall->getLocStart(),
  416. diag::err_opencl_enqueue_kernel_local_size_args);
  417. return true;
  418. }
  419. // Check that the sizes of the local memory are specified by integers.
  420. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  421. TotalNumArgs - 1);
  422. }
  423. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  424. /// overload formats specified in Table 6.13.17.1.
  425. /// int enqueue_kernel(queue_t queue,
  426. /// kernel_enqueue_flags_t flags,
  427. /// const ndrange_t ndrange,
  428. /// void (^block)(void))
  429. /// int enqueue_kernel(queue_t queue,
  430. /// kernel_enqueue_flags_t flags,
  431. /// const ndrange_t ndrange,
  432. /// uint num_events_in_wait_list,
  433. /// clk_event_t *event_wait_list,
  434. /// clk_event_t *event_ret,
  435. /// void (^block)(void))
  436. /// int enqueue_kernel(queue_t queue,
  437. /// kernel_enqueue_flags_t flags,
  438. /// const ndrange_t ndrange,
  439. /// void (^block)(local void*, ...),
  440. /// uint size0, ...)
  441. /// int enqueue_kernel(queue_t queue,
  442. /// kernel_enqueue_flags_t flags,
  443. /// const ndrange_t ndrange,
  444. /// uint num_events_in_wait_list,
  445. /// clk_event_t *event_wait_list,
  446. /// clk_event_t *event_ret,
  447. /// void (^block)(local void*, ...),
  448. /// uint size0, ...)
  449. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  450. unsigned NumArgs = TheCall->getNumArgs();
  451. if (NumArgs < 4) {
  452. S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
  453. return true;
  454. }
  455. Expr *Arg0 = TheCall->getArg(0);
  456. Expr *Arg1 = TheCall->getArg(1);
  457. Expr *Arg2 = TheCall->getArg(2);
  458. Expr *Arg3 = TheCall->getArg(3);
  459. // First argument always needs to be a queue_t type.
  460. if (!Arg0->getType()->isQueueT()) {
  461. S.Diag(TheCall->getArg(0)->getLocStart(),
  462. diag::err_opencl_builtin_expected_type)
  463. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  464. return true;
  465. }
  466. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  467. if (!Arg1->getType()->isIntegerType()) {
  468. S.Diag(TheCall->getArg(1)->getLocStart(),
  469. diag::err_opencl_builtin_expected_type)
  470. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  471. return true;
  472. }
  473. // Third argument is always an ndrange_t type.
  474. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  475. S.Diag(TheCall->getArg(2)->getLocStart(),
  476. diag::err_opencl_builtin_expected_type)
  477. << TheCall->getDirectCallee() << "'ndrange_t'";
  478. return true;
  479. }
  480. // With four arguments, there is only one form that the function could be
  481. // called in: no events and no variable arguments.
  482. if (NumArgs == 4) {
  483. // check that the last argument is the right block type.
  484. if (!isBlockPointer(Arg3)) {
  485. S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
  486. << TheCall->getDirectCallee() << "block";
  487. return true;
  488. }
  489. // we have a block type, check the prototype
  490. const BlockPointerType *BPT =
  491. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  492. if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
  493. S.Diag(Arg3->getLocStart(),
  494. diag::err_opencl_enqueue_kernel_blocks_no_args);
  495. return true;
  496. }
  497. return false;
  498. }
  499. // we can have block + varargs.
  500. if (isBlockPointer(Arg3))
  501. return (checkOpenCLBlockArgs(S, Arg3) ||
  502. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  503. // last two cases with either exactly 7 args or 7 args and varargs.
  504. if (NumArgs >= 7) {
  505. // check common block argument.
  506. Expr *Arg6 = TheCall->getArg(6);
  507. if (!isBlockPointer(Arg6)) {
  508. S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
  509. << TheCall->getDirectCallee() << "block";
  510. return true;
  511. }
  512. if (checkOpenCLBlockArgs(S, Arg6))
  513. return true;
  514. // Forth argument has to be any integer type.
  515. if (!Arg3->getType()->isIntegerType()) {
  516. S.Diag(TheCall->getArg(3)->getLocStart(),
  517. diag::err_opencl_builtin_expected_type)
  518. << TheCall->getDirectCallee() << "integer";
  519. return true;
  520. }
  521. // check remaining common arguments.
  522. Expr *Arg4 = TheCall->getArg(4);
  523. Expr *Arg5 = TheCall->getArg(5);
  524. // Fifth argument is always passed as a pointer to clk_event_t.
  525. if (!Arg4->isNullPointerConstant(S.Context,
  526. Expr::NPC_ValueDependentIsNotNull) &&
  527. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  528. S.Diag(TheCall->getArg(4)->getLocStart(),
  529. diag::err_opencl_builtin_expected_type)
  530. << TheCall->getDirectCallee()
  531. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  532. return true;
  533. }
  534. // Sixth argument is always passed as a pointer to clk_event_t.
  535. if (!Arg5->isNullPointerConstant(S.Context,
  536. Expr::NPC_ValueDependentIsNotNull) &&
  537. !(Arg5->getType()->isPointerType() &&
  538. Arg5->getType()->getPointeeType()->isClkEventT())) {
  539. S.Diag(TheCall->getArg(5)->getLocStart(),
  540. diag::err_opencl_builtin_expected_type)
  541. << TheCall->getDirectCallee()
  542. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  543. return true;
  544. }
  545. if (NumArgs == 7)
  546. return false;
  547. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  548. }
  549. // None of the specific case has been detected, give generic error
  550. S.Diag(TheCall->getLocStart(),
  551. diag::err_opencl_enqueue_kernel_incorrect_args);
  552. return true;
  553. }
  554. /// Returns OpenCL access qual.
  555. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  556. return D->getAttr<OpenCLAccessAttr>();
  557. }
  558. /// Returns true if pipe element type is different from the pointer.
  559. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  560. const Expr *Arg0 = Call->getArg(0);
  561. // First argument type should always be pipe.
  562. if (!Arg0->getType()->isPipeType()) {
  563. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
  564. << Call->getDirectCallee() << Arg0->getSourceRange();
  565. return true;
  566. }
  567. OpenCLAccessAttr *AccessQual =
  568. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  569. // Validates the access qualifier is compatible with the call.
  570. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  571. // read_only and write_only, and assumed to be read_only if no qualifier is
  572. // specified.
  573. switch (Call->getDirectCallee()->getBuiltinID()) {
  574. case Builtin::BIread_pipe:
  575. case Builtin::BIreserve_read_pipe:
  576. case Builtin::BIcommit_read_pipe:
  577. case Builtin::BIwork_group_reserve_read_pipe:
  578. case Builtin::BIsub_group_reserve_read_pipe:
  579. case Builtin::BIwork_group_commit_read_pipe:
  580. case Builtin::BIsub_group_commit_read_pipe:
  581. if (!(!AccessQual || AccessQual->isReadOnly())) {
  582. S.Diag(Arg0->getLocStart(),
  583. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  584. << "read_only" << Arg0->getSourceRange();
  585. return true;
  586. }
  587. break;
  588. case Builtin::BIwrite_pipe:
  589. case Builtin::BIreserve_write_pipe:
  590. case Builtin::BIcommit_write_pipe:
  591. case Builtin::BIwork_group_reserve_write_pipe:
  592. case Builtin::BIsub_group_reserve_write_pipe:
  593. case Builtin::BIwork_group_commit_write_pipe:
  594. case Builtin::BIsub_group_commit_write_pipe:
  595. if (!(AccessQual && AccessQual->isWriteOnly())) {
  596. S.Diag(Arg0->getLocStart(),
  597. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  598. << "write_only" << Arg0->getSourceRange();
  599. return true;
  600. }
  601. break;
  602. default:
  603. break;
  604. }
  605. return false;
  606. }
  607. /// Returns true if pipe element type is different from the pointer.
  608. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  609. const Expr *Arg0 = Call->getArg(0);
  610. const Expr *ArgIdx = Call->getArg(Idx);
  611. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  612. const QualType EltTy = PipeTy->getElementType();
  613. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  614. // The Idx argument should be a pointer and the type of the pointer and
  615. // the type of pipe element should also be the same.
  616. if (!ArgTy ||
  617. !S.Context.hasSameType(
  618. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  619. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  620. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  621. << ArgIdx->getType() << ArgIdx->getSourceRange();
  622. return true;
  623. }
  624. return false;
  625. }
  626. // Performs semantic analysis for the read/write_pipe call.
  627. // \param S Reference to the semantic analyzer.
  628. // \param Call A pointer to the builtin call.
  629. // \return True if a semantic error has been found, false otherwise.
  630. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  631. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  632. // functions have two forms.
  633. switch (Call->getNumArgs()) {
  634. case 2:
  635. if (checkOpenCLPipeArg(S, Call))
  636. return true;
  637. // The call with 2 arguments should be
  638. // read/write_pipe(pipe T, T*).
  639. // Check packet type T.
  640. if (checkOpenCLPipePacketType(S, Call, 1))
  641. return true;
  642. break;
  643. case 4: {
  644. if (checkOpenCLPipeArg(S, Call))
  645. return true;
  646. // The call with 4 arguments should be
  647. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  648. // Check reserve_id_t.
  649. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  650. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  651. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  652. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  653. return true;
  654. }
  655. // Check the index.
  656. const Expr *Arg2 = Call->getArg(2);
  657. if (!Arg2->getType()->isIntegerType() &&
  658. !Arg2->getType()->isUnsignedIntegerType()) {
  659. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  660. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  661. << Arg2->getType() << Arg2->getSourceRange();
  662. return true;
  663. }
  664. // Check packet type T.
  665. if (checkOpenCLPipePacketType(S, Call, 3))
  666. return true;
  667. } break;
  668. default:
  669. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
  670. << Call->getDirectCallee() << Call->getSourceRange();
  671. return true;
  672. }
  673. return false;
  674. }
  675. // Performs a semantic analysis on the {work_group_/sub_group_
  676. // /_}reserve_{read/write}_pipe
  677. // \param S Reference to the semantic analyzer.
  678. // \param Call The call to the builtin function to be analyzed.
  679. // \return True if a semantic error was found, false otherwise.
  680. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  681. if (checkArgCount(S, Call, 2))
  682. return true;
  683. if (checkOpenCLPipeArg(S, Call))
  684. return true;
  685. // Check the reserve size.
  686. if (!Call->getArg(1)->getType()->isIntegerType() &&
  687. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  688. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  689. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  690. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  691. return true;
  692. }
  693. // Since return type of reserve_read/write_pipe built-in function is
  694. // reserve_id_t, which is not defined in the builtin def file , we used int
  695. // as return type and need to override the return type of these functions.
  696. Call->setType(S.Context.OCLReserveIDTy);
  697. return false;
  698. }
  699. // Performs a semantic analysis on {work_group_/sub_group_
  700. // /_}commit_{read/write}_pipe
  701. // \param S Reference to the semantic analyzer.
  702. // \param Call The call to the builtin function to be analyzed.
  703. // \return True if a semantic error was found, false otherwise.
  704. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  705. if (checkArgCount(S, Call, 2))
  706. return true;
  707. if (checkOpenCLPipeArg(S, Call))
  708. return true;
  709. // Check reserve_id_t.
  710. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  711. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  712. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  713. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  714. return true;
  715. }
  716. return false;
  717. }
  718. // Performs a semantic analysis on the call to built-in Pipe
  719. // Query Functions.
  720. // \param S Reference to the semantic analyzer.
  721. // \param Call The call to the builtin function to be analyzed.
  722. // \return True if a semantic error was found, false otherwise.
  723. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  724. if (checkArgCount(S, Call, 1))
  725. return true;
  726. if (!Call->getArg(0)->getType()->isPipeType()) {
  727. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
  728. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  729. return true;
  730. }
  731. return false;
  732. }
  733. // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  734. // Performs semantic analysis for the to_global/local/private call.
  735. // \param S Reference to the semantic analyzer.
  736. // \param BuiltinID ID of the builtin function.
  737. // \param Call A pointer to the builtin call.
  738. // \return True if a semantic error has been found, false otherwise.
  739. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  740. CallExpr *Call) {
  741. if (Call->getNumArgs() != 1) {
  742. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
  743. << Call->getDirectCallee() << Call->getSourceRange();
  744. return true;
  745. }
  746. auto RT = Call->getArg(0)->getType();
  747. if (!RT->isPointerType() || RT->getPointeeType()
  748. .getAddressSpace() == LangAS::opencl_constant) {
  749. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
  750. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  751. return true;
  752. }
  753. RT = RT->getPointeeType();
  754. auto Qual = RT.getQualifiers();
  755. switch (BuiltinID) {
  756. case Builtin::BIto_global:
  757. Qual.setAddressSpace(LangAS::opencl_global);
  758. break;
  759. case Builtin::BIto_local:
  760. Qual.setAddressSpace(LangAS::opencl_local);
  761. break;
  762. case Builtin::BIto_private:
  763. Qual.setAddressSpace(LangAS::opencl_private);
  764. break;
  765. default:
  766. llvm_unreachable("Invalid builtin function");
  767. }
  768. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  769. RT.getUnqualifiedType(), Qual)));
  770. return false;
  771. }
  772. // Emit an error and return true if the current architecture is not in the list
  773. // of supported architectures.
  774. static bool
  775. CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
  776. ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
  777. llvm::Triple::ArchType CurArch =
  778. S.getASTContext().getTargetInfo().getTriple().getArch();
  779. if (llvm::is_contained(SupportedArchs, CurArch))
  780. return false;
  781. S.Diag(TheCall->getLocStart(), diag::err_builtin_target_unsupported)
  782. << TheCall->getSourceRange();
  783. return true;
  784. }
  785. ExprResult
  786. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  787. CallExpr *TheCall) {
  788. ExprResult TheCallResult(TheCall);
  789. // Find out if any arguments are required to be integer constant expressions.
  790. unsigned ICEArguments = 0;
  791. ASTContext::GetBuiltinTypeError Error;
  792. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  793. if (Error != ASTContext::GE_None)
  794. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  795. // If any arguments are required to be ICE's, check and diagnose.
  796. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  797. // Skip arguments not required to be ICE's.
  798. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  799. llvm::APSInt Result;
  800. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  801. return true;
  802. ICEArguments &= ~(1 << ArgNo);
  803. }
  804. switch (BuiltinID) {
  805. case Builtin::BI__builtin___CFStringMakeConstantString:
  806. assert(TheCall->getNumArgs() == 1 &&
  807. "Wrong # arguments to builtin CFStringMakeConstantString");
  808. if (CheckObjCString(TheCall->getArg(0)))
  809. return ExprError();
  810. break;
  811. case Builtin::BI__builtin_ms_va_start:
  812. case Builtin::BI__builtin_stdarg_start:
  813. case Builtin::BI__builtin_va_start:
  814. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  815. return ExprError();
  816. break;
  817. case Builtin::BI__va_start: {
  818. switch (Context.getTargetInfo().getTriple().getArch()) {
  819. case llvm::Triple::arm:
  820. case llvm::Triple::thumb:
  821. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  822. return ExprError();
  823. break;
  824. default:
  825. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  826. return ExprError();
  827. break;
  828. }
  829. break;
  830. }
  831. // The acquire, release, and no fence variants are ARM and AArch64 only.
  832. case Builtin::BI_interlockedbittestandset_acq:
  833. case Builtin::BI_interlockedbittestandset_rel:
  834. case Builtin::BI_interlockedbittestandset_nf:
  835. case Builtin::BI_interlockedbittestandreset_acq:
  836. case Builtin::BI_interlockedbittestandreset_rel:
  837. case Builtin::BI_interlockedbittestandreset_nf:
  838. if (CheckBuiltinTargetSupport(
  839. *this, BuiltinID, TheCall,
  840. {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
  841. return ExprError();
  842. break;
  843. // The 64-bit bittest variants are x64, ARM, and AArch64 only.
  844. case Builtin::BI_bittest64:
  845. case Builtin::BI_bittestandcomplement64:
  846. case Builtin::BI_bittestandreset64:
  847. case Builtin::BI_bittestandset64:
  848. case Builtin::BI_interlockedbittestandreset64:
  849. case Builtin::BI_interlockedbittestandset64:
  850. if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
  851. {llvm::Triple::x86_64, llvm::Triple::arm,
  852. llvm::Triple::thumb, llvm::Triple::aarch64}))
  853. return ExprError();
  854. break;
  855. case Builtin::BI__builtin_isgreater:
  856. case Builtin::BI__builtin_isgreaterequal:
  857. case Builtin::BI__builtin_isless:
  858. case Builtin::BI__builtin_islessequal:
  859. case Builtin::BI__builtin_islessgreater:
  860. case Builtin::BI__builtin_isunordered:
  861. if (SemaBuiltinUnorderedCompare(TheCall))
  862. return ExprError();
  863. break;
  864. case Builtin::BI__builtin_fpclassify:
  865. if (SemaBuiltinFPClassification(TheCall, 6))
  866. return ExprError();
  867. break;
  868. case Builtin::BI__builtin_isfinite:
  869. case Builtin::BI__builtin_isinf:
  870. case Builtin::BI__builtin_isinf_sign:
  871. case Builtin::BI__builtin_isnan:
  872. case Builtin::BI__builtin_isnormal:
  873. case Builtin::BI__builtin_signbit:
  874. case Builtin::BI__builtin_signbitf:
  875. case Builtin::BI__builtin_signbitl:
  876. if (SemaBuiltinFPClassification(TheCall, 1))
  877. return ExprError();
  878. break;
  879. case Builtin::BI__builtin_shufflevector:
  880. return SemaBuiltinShuffleVector(TheCall);
  881. // TheCall will be freed by the smart pointer here, but that's fine, since
  882. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  883. case Builtin::BI__builtin_prefetch:
  884. if (SemaBuiltinPrefetch(TheCall))
  885. return ExprError();
  886. break;
  887. case Builtin::BI__builtin_alloca_with_align:
  888. if (SemaBuiltinAllocaWithAlign(TheCall))
  889. return ExprError();
  890. break;
  891. case Builtin::BI__assume:
  892. case Builtin::BI__builtin_assume:
  893. if (SemaBuiltinAssume(TheCall))
  894. return ExprError();
  895. break;
  896. case Builtin::BI__builtin_assume_aligned:
  897. if (SemaBuiltinAssumeAligned(TheCall))
  898. return ExprError();
  899. break;
  900. case Builtin::BI__builtin_object_size:
  901. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  902. return ExprError();
  903. break;
  904. case Builtin::BI__builtin_longjmp:
  905. if (SemaBuiltinLongjmp(TheCall))
  906. return ExprError();
  907. break;
  908. case Builtin::BI__builtin_setjmp:
  909. if (SemaBuiltinSetjmp(TheCall))
  910. return ExprError();
  911. break;
  912. case Builtin::BI_setjmp:
  913. case Builtin::BI_setjmpex:
  914. if (checkArgCount(*this, TheCall, 1))
  915. return true;
  916. break;
  917. case Builtin::BI__builtin_classify_type:
  918. if (checkArgCount(*this, TheCall, 1)) return true;
  919. TheCall->setType(Context.IntTy);
  920. break;
  921. case Builtin::BI__builtin_constant_p:
  922. if (checkArgCount(*this, TheCall, 1)) return true;
  923. TheCall->setType(Context.IntTy);
  924. break;
  925. case Builtin::BI__sync_fetch_and_add:
  926. case Builtin::BI__sync_fetch_and_add_1:
  927. case Builtin::BI__sync_fetch_and_add_2:
  928. case Builtin::BI__sync_fetch_and_add_4:
  929. case Builtin::BI__sync_fetch_and_add_8:
  930. case Builtin::BI__sync_fetch_and_add_16:
  931. case Builtin::BI__sync_fetch_and_sub:
  932. case Builtin::BI__sync_fetch_and_sub_1:
  933. case Builtin::BI__sync_fetch_and_sub_2:
  934. case Builtin::BI__sync_fetch_and_sub_4:
  935. case Builtin::BI__sync_fetch_and_sub_8:
  936. case Builtin::BI__sync_fetch_and_sub_16:
  937. case Builtin::BI__sync_fetch_and_or:
  938. case Builtin::BI__sync_fetch_and_or_1:
  939. case Builtin::BI__sync_fetch_and_or_2:
  940. case Builtin::BI__sync_fetch_and_or_4:
  941. case Builtin::BI__sync_fetch_and_or_8:
  942. case Builtin::BI__sync_fetch_and_or_16:
  943. case Builtin::BI__sync_fetch_and_and:
  944. case Builtin::BI__sync_fetch_and_and_1:
  945. case Builtin::BI__sync_fetch_and_and_2:
  946. case Builtin::BI__sync_fetch_and_and_4:
  947. case Builtin::BI__sync_fetch_and_and_8:
  948. case Builtin::BI__sync_fetch_and_and_16:
  949. case Builtin::BI__sync_fetch_and_xor:
  950. case Builtin::BI__sync_fetch_and_xor_1:
  951. case Builtin::BI__sync_fetch_and_xor_2:
  952. case Builtin::BI__sync_fetch_and_xor_4:
  953. case Builtin::BI__sync_fetch_and_xor_8:
  954. case Builtin::BI__sync_fetch_and_xor_16:
  955. case Builtin::BI__sync_fetch_and_nand:
  956. case Builtin::BI__sync_fetch_and_nand_1:
  957. case Builtin::BI__sync_fetch_and_nand_2:
  958. case Builtin::BI__sync_fetch_and_nand_4:
  959. case Builtin::BI__sync_fetch_and_nand_8:
  960. case Builtin::BI__sync_fetch_and_nand_16:
  961. case Builtin::BI__sync_add_and_fetch:
  962. case Builtin::BI__sync_add_and_fetch_1:
  963. case Builtin::BI__sync_add_and_fetch_2:
  964. case Builtin::BI__sync_add_and_fetch_4:
  965. case Builtin::BI__sync_add_and_fetch_8:
  966. case Builtin::BI__sync_add_and_fetch_16:
  967. case Builtin::BI__sync_sub_and_fetch:
  968. case Builtin::BI__sync_sub_and_fetch_1:
  969. case Builtin::BI__sync_sub_and_fetch_2:
  970. case Builtin::BI__sync_sub_and_fetch_4:
  971. case Builtin::BI__sync_sub_and_fetch_8:
  972. case Builtin::BI__sync_sub_and_fetch_16:
  973. case Builtin::BI__sync_and_and_fetch:
  974. case Builtin::BI__sync_and_and_fetch_1:
  975. case Builtin::BI__sync_and_and_fetch_2:
  976. case Builtin::BI__sync_and_and_fetch_4:
  977. case Builtin::BI__sync_and_and_fetch_8:
  978. case Builtin::BI__sync_and_and_fetch_16:
  979. case Builtin::BI__sync_or_and_fetch:
  980. case Builtin::BI__sync_or_and_fetch_1:
  981. case Builtin::BI__sync_or_and_fetch_2:
  982. case Builtin::BI__sync_or_and_fetch_4:
  983. case Builtin::BI__sync_or_and_fetch_8:
  984. case Builtin::BI__sync_or_and_fetch_16:
  985. case Builtin::BI__sync_xor_and_fetch:
  986. case Builtin::BI__sync_xor_and_fetch_1:
  987. case Builtin::BI__sync_xor_and_fetch_2:
  988. case Builtin::BI__sync_xor_and_fetch_4:
  989. case Builtin::BI__sync_xor_and_fetch_8:
  990. case Builtin::BI__sync_xor_and_fetch_16:
  991. case Builtin::BI__sync_nand_and_fetch:
  992. case Builtin::BI__sync_nand_and_fetch_1:
  993. case Builtin::BI__sync_nand_and_fetch_2:
  994. case Builtin::BI__sync_nand_and_fetch_4:
  995. case Builtin::BI__sync_nand_and_fetch_8:
  996. case Builtin::BI__sync_nand_and_fetch_16:
  997. case Builtin::BI__sync_val_compare_and_swap:
  998. case Builtin::BI__sync_val_compare_and_swap_1:
  999. case Builtin::BI__sync_val_compare_and_swap_2:
  1000. case Builtin::BI__sync_val_compare_and_swap_4:
  1001. case Builtin::BI__sync_val_compare_and_swap_8:
  1002. case Builtin::BI__sync_val_compare_and_swap_16:
  1003. case Builtin::BI__sync_bool_compare_and_swap:
  1004. case Builtin::BI__sync_bool_compare_and_swap_1:
  1005. case Builtin::BI__sync_bool_compare_and_swap_2:
  1006. case Builtin::BI__sync_bool_compare_and_swap_4:
  1007. case Builtin::BI__sync_bool_compare_and_swap_8:
  1008. case Builtin::BI__sync_bool_compare_and_swap_16:
  1009. case Builtin::BI__sync_lock_test_and_set:
  1010. case Builtin::BI__sync_lock_test_and_set_1:
  1011. case Builtin::BI__sync_lock_test_and_set_2:
  1012. case Builtin::BI__sync_lock_test_and_set_4:
  1013. case Builtin::BI__sync_lock_test_and_set_8:
  1014. case Builtin::BI__sync_lock_test_and_set_16:
  1015. case Builtin::BI__sync_lock_release:
  1016. case Builtin::BI__sync_lock_release_1:
  1017. case Builtin::BI__sync_lock_release_2:
  1018. case Builtin::BI__sync_lock_release_4:
  1019. case Builtin::BI__sync_lock_release_8:
  1020. case Builtin::BI__sync_lock_release_16:
  1021. case Builtin::BI__sync_swap:
  1022. case Builtin::BI__sync_swap_1:
  1023. case Builtin::BI__sync_swap_2:
  1024. case Builtin::BI__sync_swap_4:
  1025. case Builtin::BI__sync_swap_8:
  1026. case Builtin::BI__sync_swap_16:
  1027. return SemaBuiltinAtomicOverloaded(TheCallResult);
  1028. case Builtin::BI__builtin_nontemporal_load:
  1029. case Builtin::BI__builtin_nontemporal_store:
  1030. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  1031. #define BUILTIN(ID, TYPE, ATTRS)
  1032. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  1033. case Builtin::BI##ID: \
  1034. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  1035. #include "clang/Basic/Builtins.def"
  1036. case Builtin::BI__annotation:
  1037. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  1038. return ExprError();
  1039. break;
  1040. case Builtin::BI__builtin_annotation:
  1041. if (SemaBuiltinAnnotation(*this, TheCall))
  1042. return ExprError();
  1043. break;
  1044. case Builtin::BI__builtin_addressof:
  1045. if (SemaBuiltinAddressof(*this, TheCall))
  1046. return ExprError();
  1047. break;
  1048. case Builtin::BI__builtin_add_overflow:
  1049. case Builtin::BI__builtin_sub_overflow:
  1050. case Builtin::BI__builtin_mul_overflow:
  1051. if (SemaBuiltinOverflow(*this, TheCall))
  1052. return ExprError();
  1053. break;
  1054. case Builtin::BI__builtin_operator_new:
  1055. case Builtin::BI__builtin_operator_delete: {
  1056. bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
  1057. ExprResult Res =
  1058. SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
  1059. if (Res.isInvalid())
  1060. CorrectDelayedTyposInExpr(TheCallResult.get());
  1061. return Res;
  1062. }
  1063. case Builtin::BI__builtin_dump_struct: {
  1064. // We first want to ensure we are called with 2 arguments
  1065. if (checkArgCount(*this, TheCall, 2))
  1066. return ExprError();
  1067. // Ensure that the first argument is of type 'struct XX *'
  1068. const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
  1069. const QualType PtrArgType = PtrArg->getType();
  1070. if (!PtrArgType->isPointerType() ||
  1071. !PtrArgType->getPointeeType()->isRecordType()) {
  1072. Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
  1073. << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
  1074. << "structure pointer";
  1075. return ExprError();
  1076. }
  1077. // Ensure that the second argument is of type 'FunctionType'
  1078. const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
  1079. const QualType FnPtrArgType = FnPtrArg->getType();
  1080. if (!FnPtrArgType->isPointerType()) {
  1081. Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
  1082. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1083. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1084. return ExprError();
  1085. }
  1086. const auto *FuncType =
  1087. FnPtrArgType->getPointeeType()->getAs<FunctionType>();
  1088. if (!FuncType) {
  1089. Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
  1090. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1091. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1092. return ExprError();
  1093. }
  1094. if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
  1095. if (!FT->getNumParams()) {
  1096. Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
  1097. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1098. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1099. return ExprError();
  1100. }
  1101. QualType PT = FT->getParamType(0);
  1102. if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
  1103. !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
  1104. !PT->getPointeeType().isConstQualified()) {
  1105. Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
  1106. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1107. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1108. return ExprError();
  1109. }
  1110. }
  1111. TheCall->setType(Context.IntTy);
  1112. break;
  1113. }
  1114. // check secure string manipulation functions where overflows
  1115. // are detectable at compile time
  1116. case Builtin::BI__builtin___memcpy_chk:
  1117. case Builtin::BI__builtin___memmove_chk:
  1118. case Builtin::BI__builtin___memset_chk:
  1119. case Builtin::BI__builtin___strlcat_chk:
  1120. case Builtin::BI__builtin___strlcpy_chk:
  1121. case Builtin::BI__builtin___strncat_chk:
  1122. case Builtin::BI__builtin___strncpy_chk:
  1123. case Builtin::BI__builtin___stpncpy_chk:
  1124. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
  1125. break;
  1126. case Builtin::BI__builtin___memccpy_chk:
  1127. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
  1128. break;
  1129. case Builtin::BI__builtin___snprintf_chk:
  1130. case Builtin::BI__builtin___vsnprintf_chk:
  1131. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
  1132. break;
  1133. case Builtin::BI__builtin_call_with_static_chain:
  1134. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  1135. return ExprError();
  1136. break;
  1137. case Builtin::BI__exception_code:
  1138. case Builtin::BI_exception_code:
  1139. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  1140. diag::err_seh___except_block))
  1141. return ExprError();
  1142. break;
  1143. case Builtin::BI__exception_info:
  1144. case Builtin::BI_exception_info:
  1145. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  1146. diag::err_seh___except_filter))
  1147. return ExprError();
  1148. break;
  1149. case Builtin::BI__GetExceptionInfo:
  1150. if (checkArgCount(*this, TheCall, 1))
  1151. return ExprError();
  1152. if (CheckCXXThrowOperand(
  1153. TheCall->getLocStart(),
  1154. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1155. TheCall))
  1156. return ExprError();
  1157. TheCall->setType(Context.VoidPtrTy);
  1158. break;
  1159. // OpenCL v2.0, s6.13.16 - Pipe functions
  1160. case Builtin::BIread_pipe:
  1161. case Builtin::BIwrite_pipe:
  1162. // Since those two functions are declared with var args, we need a semantic
  1163. // check for the argument.
  1164. if (SemaBuiltinRWPipe(*this, TheCall))
  1165. return ExprError();
  1166. TheCall->setType(Context.IntTy);
  1167. break;
  1168. case Builtin::BIreserve_read_pipe:
  1169. case Builtin::BIreserve_write_pipe:
  1170. case Builtin::BIwork_group_reserve_read_pipe:
  1171. case Builtin::BIwork_group_reserve_write_pipe:
  1172. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1173. return ExprError();
  1174. break;
  1175. case Builtin::BIsub_group_reserve_read_pipe:
  1176. case Builtin::BIsub_group_reserve_write_pipe:
  1177. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1178. SemaBuiltinReserveRWPipe(*this, TheCall))
  1179. return ExprError();
  1180. break;
  1181. case Builtin::BIcommit_read_pipe:
  1182. case Builtin::BIcommit_write_pipe:
  1183. case Builtin::BIwork_group_commit_read_pipe:
  1184. case Builtin::BIwork_group_commit_write_pipe:
  1185. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1186. return ExprError();
  1187. break;
  1188. case Builtin::BIsub_group_commit_read_pipe:
  1189. case Builtin::BIsub_group_commit_write_pipe:
  1190. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1191. SemaBuiltinCommitRWPipe(*this, TheCall))
  1192. return ExprError();
  1193. break;
  1194. case Builtin::BIget_pipe_num_packets:
  1195. case Builtin::BIget_pipe_max_packets:
  1196. if (SemaBuiltinPipePackets(*this, TheCall))
  1197. return ExprError();
  1198. TheCall->setType(Context.UnsignedIntTy);
  1199. break;
  1200. case Builtin::BIto_global:
  1201. case Builtin::BIto_local:
  1202. case Builtin::BIto_private:
  1203. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1204. return ExprError();
  1205. break;
  1206. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1207. case Builtin::BIenqueue_kernel:
  1208. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1209. return ExprError();
  1210. break;
  1211. case Builtin::BIget_kernel_work_group_size:
  1212. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1213. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1214. return ExprError();
  1215. break;
  1216. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1217. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1218. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1219. return ExprError();
  1220. break;
  1221. case Builtin::BI__builtin_os_log_format:
  1222. case Builtin::BI__builtin_os_log_format_buffer_size:
  1223. if (SemaBuiltinOSLogFormat(TheCall))
  1224. return ExprError();
  1225. break;
  1226. }
  1227. // Since the target specific builtins for each arch overlap, only check those
  1228. // of the arch we are compiling for.
  1229. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  1230. switch (Context.getTargetInfo().getTriple().getArch()) {
  1231. case llvm::Triple::arm:
  1232. case llvm::Triple::armeb:
  1233. case llvm::Triple::thumb:
  1234. case llvm::Triple::thumbeb:
  1235. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  1236. return ExprError();
  1237. break;
  1238. case llvm::Triple::aarch64:
  1239. case llvm::Triple::aarch64_be:
  1240. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  1241. return ExprError();
  1242. break;
  1243. case llvm::Triple::hexagon:
  1244. if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
  1245. return ExprError();
  1246. break;
  1247. case llvm::Triple::mips:
  1248. case llvm::Triple::mipsel:
  1249. case llvm::Triple::mips64:
  1250. case llvm::Triple::mips64el:
  1251. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  1252. return ExprError();
  1253. break;
  1254. case llvm::Triple::systemz:
  1255. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  1256. return ExprError();
  1257. break;
  1258. case llvm::Triple::x86:
  1259. case llvm::Triple::x86_64:
  1260. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  1261. return ExprError();
  1262. break;
  1263. case llvm::Triple::ppc:
  1264. case llvm::Triple::ppc64:
  1265. case llvm::Triple::ppc64le:
  1266. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  1267. return ExprError();
  1268. break;
  1269. default:
  1270. break;
  1271. }
  1272. }
  1273. return TheCallResult;
  1274. }
  1275. // Get the valid immediate range for the specified NEON type code.
  1276. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  1277. NeonTypeFlags Type(t);
  1278. int IsQuad = ForceQuad ? true : Type.isQuad();
  1279. switch (Type.getEltType()) {
  1280. case NeonTypeFlags::Int8:
  1281. case NeonTypeFlags::Poly8:
  1282. return shift ? 7 : (8 << IsQuad) - 1;
  1283. case NeonTypeFlags::Int16:
  1284. case NeonTypeFlags::Poly16:
  1285. return shift ? 15 : (4 << IsQuad) - 1;
  1286. case NeonTypeFlags::Int32:
  1287. return shift ? 31 : (2 << IsQuad) - 1;
  1288. case NeonTypeFlags::Int64:
  1289. case NeonTypeFlags::Poly64:
  1290. return shift ? 63 : (1 << IsQuad) - 1;
  1291. case NeonTypeFlags::Poly128:
  1292. return shift ? 127 : (1 << IsQuad) - 1;
  1293. case NeonTypeFlags::Float16:
  1294. assert(!shift && "cannot shift float types!");
  1295. return (4 << IsQuad) - 1;
  1296. case NeonTypeFlags::Float32:
  1297. assert(!shift && "cannot shift float types!");
  1298. return (2 << IsQuad) - 1;
  1299. case NeonTypeFlags::Float64:
  1300. assert(!shift && "cannot shift float types!");
  1301. return (1 << IsQuad) - 1;
  1302. }
  1303. llvm_unreachable("Invalid NeonTypeFlag!");
  1304. }
  1305. /// getNeonEltType - Return the QualType corresponding to the elements of
  1306. /// the vector type specified by the NeonTypeFlags. This is used to check
  1307. /// the pointer arguments for Neon load/store intrinsics.
  1308. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  1309. bool IsPolyUnsigned, bool IsInt64Long) {
  1310. switch (Flags.getEltType()) {
  1311. case NeonTypeFlags::Int8:
  1312. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  1313. case NeonTypeFlags::Int16:
  1314. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  1315. case NeonTypeFlags::Int32:
  1316. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  1317. case NeonTypeFlags::Int64:
  1318. if (IsInt64Long)
  1319. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  1320. else
  1321. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  1322. : Context.LongLongTy;
  1323. case NeonTypeFlags::Poly8:
  1324. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  1325. case NeonTypeFlags::Poly16:
  1326. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  1327. case NeonTypeFlags::Poly64:
  1328. if (IsInt64Long)
  1329. return Context.UnsignedLongTy;
  1330. else
  1331. return Context.UnsignedLongLongTy;
  1332. case NeonTypeFlags::Poly128:
  1333. break;
  1334. case NeonTypeFlags::Float16:
  1335. return Context.HalfTy;
  1336. case NeonTypeFlags::Float32:
  1337. return Context.FloatTy;
  1338. case NeonTypeFlags::Float64:
  1339. return Context.DoubleTy;
  1340. }
  1341. llvm_unreachable("Invalid NeonTypeFlag!");
  1342. }
  1343. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1344. llvm::APSInt Result;
  1345. uint64_t mask = 0;
  1346. unsigned TV = 0;
  1347. int PtrArgNum = -1;
  1348. bool HasConstPtr = false;
  1349. switch (BuiltinID) {
  1350. #define GET_NEON_OVERLOAD_CHECK
  1351. #include "clang/Basic/arm_neon.inc"
  1352. #include "clang/Basic/arm_fp16.inc"
  1353. #undef GET_NEON_OVERLOAD_CHECK
  1354. }
  1355. // For NEON intrinsics which are overloaded on vector element type, validate
  1356. // the immediate which specifies which variant to emit.
  1357. unsigned ImmArg = TheCall->getNumArgs()-1;
  1358. if (mask) {
  1359. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  1360. return true;
  1361. TV = Result.getLimitedValue(64);
  1362. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  1363. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  1364. << TheCall->getArg(ImmArg)->getSourceRange();
  1365. }
  1366. if (PtrArgNum >= 0) {
  1367. // Check that pointer arguments have the specified type.
  1368. Expr *Arg = TheCall->getArg(PtrArgNum);
  1369. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  1370. Arg = ICE->getSubExpr();
  1371. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  1372. QualType RHSTy = RHS.get()->getType();
  1373. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  1374. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  1375. Arch == llvm::Triple::aarch64_be;
  1376. bool IsInt64Long =
  1377. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  1378. QualType EltTy =
  1379. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  1380. if (HasConstPtr)
  1381. EltTy = EltTy.withConst();
  1382. QualType LHSTy = Context.getPointerType(EltTy);
  1383. AssignConvertType ConvTy;
  1384. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  1385. if (RHS.isInvalid())
  1386. return true;
  1387. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  1388. RHS.get(), AA_Assigning))
  1389. return true;
  1390. }
  1391. // For NEON intrinsics which take an immediate value as part of the
  1392. // instruction, range check them here.
  1393. unsigned i = 0, l = 0, u = 0;
  1394. switch (BuiltinID) {
  1395. default:
  1396. return false;
  1397. #define GET_NEON_IMMEDIATE_CHECK
  1398. #include "clang/Basic/arm_neon.inc"
  1399. #include "clang/Basic/arm_fp16.inc"
  1400. #undef GET_NEON_IMMEDIATE_CHECK
  1401. }
  1402. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1403. }
  1404. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  1405. unsigned MaxWidth) {
  1406. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1407. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1408. BuiltinID == ARM::BI__builtin_arm_strex ||
  1409. BuiltinID == ARM::BI__builtin_arm_stlex ||
  1410. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1411. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1412. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1413. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  1414. "unexpected ARM builtin");
  1415. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1416. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1417. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1418. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  1419. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1420. // Ensure that we have the proper number of arguments.
  1421. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  1422. return true;
  1423. // Inspect the pointer argument of the atomic builtin. This should always be
  1424. // a pointer type, whose element is an integral scalar or pointer type.
  1425. // Because it is a pointer type, we don't have to worry about any implicit
  1426. // casts here.
  1427. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  1428. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  1429. if (PointerArgRes.isInvalid())
  1430. return true;
  1431. PointerArg = PointerArgRes.get();
  1432. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  1433. if (!pointerType) {
  1434. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  1435. << PointerArg->getType() << PointerArg->getSourceRange();
  1436. return true;
  1437. }
  1438. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  1439. // task is to insert the appropriate casts into the AST. First work out just
  1440. // what the appropriate type is.
  1441. QualType ValType = pointerType->getPointeeType();
  1442. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  1443. if (IsLdrex)
  1444. AddrType.addConst();
  1445. // Issue a warning if the cast is dodgy.
  1446. CastKind CastNeeded = CK_NoOp;
  1447. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  1448. CastNeeded = CK_BitCast;
  1449. Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
  1450. << PointerArg->getType()
  1451. << Context.getPointerType(AddrType)
  1452. << AA_Passing << PointerArg->getSourceRange();
  1453. }
  1454. // Finally, do the cast and replace the argument with the corrected version.
  1455. AddrType = Context.getPointerType(AddrType);
  1456. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  1457. if (PointerArgRes.isInvalid())
  1458. return true;
  1459. PointerArg = PointerArgRes.get();
  1460. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  1461. // In general, we allow ints, floats and pointers to be loaded and stored.
  1462. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1463. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  1464. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  1465. << PointerArg->getType() << PointerArg->getSourceRange();
  1466. return true;
  1467. }
  1468. // But ARM doesn't have instructions to deal with 128-bit versions.
  1469. if (Context.getTypeSize(ValType) > MaxWidth) {
  1470. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  1471. Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
  1472. << PointerArg->getType() << PointerArg->getSourceRange();
  1473. return true;
  1474. }
  1475. switch (ValType.getObjCLifetime()) {
  1476. case Qualifiers::OCL_None:
  1477. case Qualifiers::OCL_ExplicitNone:
  1478. // okay
  1479. break;
  1480. case Qualifiers::OCL_Weak:
  1481. case Qualifiers::OCL_Strong:
  1482. case Qualifiers::OCL_Autoreleasing:
  1483. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  1484. << ValType << PointerArg->getSourceRange();
  1485. return true;
  1486. }
  1487. if (IsLdrex) {
  1488. TheCall->setType(ValType);
  1489. return false;
  1490. }
  1491. // Initialize the argument to be stored.
  1492. ExprResult ValArg = TheCall->getArg(0);
  1493. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  1494. Context, ValType, /*consume*/ false);
  1495. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  1496. if (ValArg.isInvalid())
  1497. return true;
  1498. TheCall->setArg(0, ValArg.get());
  1499. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  1500. // but the custom checker bypasses all default analysis.
  1501. TheCall->setType(Context.IntTy);
  1502. return false;
  1503. }
  1504. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1505. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1506. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1507. BuiltinID == ARM::BI__builtin_arm_strex ||
  1508. BuiltinID == ARM::BI__builtin_arm_stlex) {
  1509. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  1510. }
  1511. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  1512. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1513. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  1514. }
  1515. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  1516. BuiltinID == ARM::BI__builtin_arm_wsr64)
  1517. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  1518. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  1519. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  1520. BuiltinID == ARM::BI__builtin_arm_wsr ||
  1521. BuiltinID == ARM::BI__builtin_arm_wsrp)
  1522. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1523. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1524. return true;
  1525. // For intrinsics which take an immediate value as part of the instruction,
  1526. // range check them here.
  1527. // FIXME: VFP Intrinsics should error if VFP not present.
  1528. switch (BuiltinID) {
  1529. default: return false;
  1530. case ARM::BI__builtin_arm_ssat:
  1531. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  1532. case ARM::BI__builtin_arm_usat:
  1533. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  1534. case ARM::BI__builtin_arm_ssat16:
  1535. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  1536. case ARM::BI__builtin_arm_usat16:
  1537. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  1538. case ARM::BI__builtin_arm_vcvtr_f:
  1539. case ARM::BI__builtin_arm_vcvtr_d:
  1540. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  1541. case ARM::BI__builtin_arm_dmb:
  1542. case ARM::BI__builtin_arm_dsb:
  1543. case ARM::BI__builtin_arm_isb:
  1544. case ARM::BI__builtin_arm_dbg:
  1545. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  1546. }
  1547. }
  1548. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  1549. CallExpr *TheCall) {
  1550. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1551. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1552. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1553. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  1554. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  1555. }
  1556. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  1557. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1558. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  1559. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  1560. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  1561. }
  1562. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  1563. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  1564. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1565. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  1566. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  1567. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  1568. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  1569. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1570. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1571. return true;
  1572. // For intrinsics which take an immediate value as part of the instruction,
  1573. // range check them here.
  1574. unsigned i = 0, l = 0, u = 0;
  1575. switch (BuiltinID) {
  1576. default: return false;
  1577. case AArch64::BI__builtin_arm_dmb:
  1578. case AArch64::BI__builtin_arm_dsb:
  1579. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  1580. }
  1581. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1582. }
  1583. bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
  1584. static const std::map<unsigned, std::vector<StringRef>> ValidCPU = {
  1585. { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, {"v65"} },
  1586. { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, {"v62", "v65"} },
  1587. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, {"v62", "v65"} },
  1588. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, {"v62", "v65"} },
  1589. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {"v60", "v62", "v65"} },
  1590. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {"v60", "v62", "v65"} },
  1591. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {"v60", "v62", "v65"} },
  1592. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {"v60", "v62", "v65"} },
  1593. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {"v60", "v62", "v65"} },
  1594. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {"v60", "v62", "v65"} },
  1595. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {"v60", "v62", "v65"} },
  1596. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {"v60", "v62", "v65"} },
  1597. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {"v60", "v62", "v65"} },
  1598. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {"v60", "v62", "v65"} },
  1599. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {"v60", "v62", "v65"} },
  1600. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {"v60", "v62", "v65"} },
  1601. { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, {"v62", "v65"} },
  1602. { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, {"v62", "v65"} },
  1603. { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, {"v62", "v65"} },
  1604. };
  1605. static const std::map<unsigned, std::vector<StringRef>> ValidHVX = {
  1606. { Hexagon::BI__builtin_HEXAGON_V6_extractw, {"v60", "v62", "v65"} },
  1607. { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, {"v60", "v62", "v65"} },
  1608. { Hexagon::BI__builtin_HEXAGON_V6_hi, {"v60", "v62", "v65"} },
  1609. { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, {"v60", "v62", "v65"} },
  1610. { Hexagon::BI__builtin_HEXAGON_V6_lo, {"v60", "v62", "v65"} },
  1611. { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, {"v60", "v62", "v65"} },
  1612. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, {"v62", "v65"} },
  1613. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, {"v62", "v65"} },
  1614. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, {"v62", "v65"} },
  1615. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, {"v62", "v65"} },
  1616. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, {"v60", "v62", "v65"} },
  1617. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, {"v60", "v62", "v65"} },
  1618. { Hexagon::BI__builtin_HEXAGON_V6_pred_and, {"v60", "v62", "v65"} },
  1619. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, {"v60", "v62", "v65"} },
  1620. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, {"v60", "v62", "v65"} },
  1621. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, {"v60", "v62", "v65"} },
  1622. { Hexagon::BI__builtin_HEXAGON_V6_pred_not, {"v60", "v62", "v65"} },
  1623. { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, {"v60", "v62", "v65"} },
  1624. { Hexagon::BI__builtin_HEXAGON_V6_pred_or, {"v60", "v62", "v65"} },
  1625. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, {"v60", "v62", "v65"} },
  1626. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, {"v60", "v62", "v65"} },
  1627. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, {"v60", "v62", "v65"} },
  1628. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, {"v60", "v62", "v65"} },
  1629. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, {"v60", "v62", "v65"} },
  1630. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, {"v62", "v65"} },
  1631. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, {"v62", "v65"} },
  1632. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, {"v60", "v62", "v65"} },
  1633. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, {"v60", "v62", "v65"} },
  1634. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, {"v62", "v65"} },
  1635. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, {"v62", "v65"} },
  1636. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, {"v62", "v65"} },
  1637. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, {"v62", "v65"} },
  1638. { Hexagon::BI__builtin_HEXAGON_V6_vabsb, {"v65"} },
  1639. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, {"v65"} },
  1640. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, {"v65"} },
  1641. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, {"v65"} },
  1642. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, {"v60", "v62", "v65"} },
  1643. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, {"v60", "v62", "v65"} },
  1644. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, {"v60", "v62", "v65"} },
  1645. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, {"v60", "v62", "v65"} },
  1646. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, {"v60", "v62", "v65"} },
  1647. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, {"v60", "v62", "v65"} },
  1648. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, {"v60", "v62", "v65"} },
  1649. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, {"v60", "v62", "v65"} },
  1650. { Hexagon::BI__builtin_HEXAGON_V6_vabsh, {"v60", "v62", "v65"} },
  1651. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, {"v60", "v62", "v65"} },
  1652. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, {"v60", "v62", "v65"} },
  1653. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, {"v60", "v62", "v65"} },
  1654. { Hexagon::BI__builtin_HEXAGON_V6_vabsw, {"v60", "v62", "v65"} },
  1655. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, {"v60", "v62", "v65"} },
  1656. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, {"v60", "v62", "v65"} },
  1657. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, {"v60", "v62", "v65"} },
  1658. { Hexagon::BI__builtin_HEXAGON_V6_vaddb, {"v60", "v62", "v65"} },
  1659. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, {"v60", "v62", "v65"} },
  1660. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, {"v60", "v62", "v65"} },
  1661. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, {"v60", "v62", "v65"} },
  1662. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, {"v62", "v65"} },
  1663. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, {"v62", "v65"} },
  1664. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, {"v62", "v65"} },
  1665. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, {"v62", "v65"} },
  1666. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, {"v62", "v65"} },
  1667. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, {"v62", "v65"} },
  1668. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, {"v62", "v65"} },
  1669. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, {"v62", "v65"} },
  1670. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, {"v62", "v65"} },
  1671. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, {"v62", "v65"} },
  1672. { Hexagon::BI__builtin_HEXAGON_V6_vaddh, {"v60", "v62", "v65"} },
  1673. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, {"v60", "v62", "v65"} },
  1674. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, {"v60", "v62", "v65"} },
  1675. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, {"v60", "v62", "v65"} },
  1676. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, {"v60", "v62", "v65"} },
  1677. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, {"v60", "v62", "v65"} },
  1678. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, {"v60", "v62", "v65"} },
  1679. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, {"v60", "v62", "v65"} },
  1680. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, {"v60", "v62", "v65"} },
  1681. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, {"v60", "v62", "v65"} },
  1682. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, {"v62", "v65"} },
  1683. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, {"v62", "v65"} },
  1684. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, {"v60", "v62", "v65"} },
  1685. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, {"v60", "v62", "v65"} },
  1686. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, {"v62", "v65"} },
  1687. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, {"v62", "v65"} },
  1688. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, {"v60", "v62", "v65"} },
  1689. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, {"v60", "v62", "v65"} },
  1690. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, {"v60", "v62", "v65"} },
  1691. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, {"v60", "v62", "v65"} },
  1692. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, {"v62", "v65"} },
  1693. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, {"v62", "v65"} },
  1694. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, {"v60", "v62", "v65"} },
  1695. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, {"v60", "v62", "v65"} },
  1696. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, {"v60", "v62", "v65"} },
  1697. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, {"v60", "v62", "v65"} },
  1698. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, {"v60", "v62", "v65"} },
  1699. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, {"v60", "v62", "v65"} },
  1700. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, {"v62", "v65"} },
  1701. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, {"v62", "v65"} },
  1702. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, {"v62", "v65"} },
  1703. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, {"v62", "v65"} },
  1704. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, {"v62", "v65"} },
  1705. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, {"v62", "v65"} },
  1706. { Hexagon::BI__builtin_HEXAGON_V6_vaddw, {"v60", "v62", "v65"} },
  1707. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, {"v60", "v62", "v65"} },
  1708. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, {"v60", "v62", "v65"} },
  1709. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, {"v60", "v62", "v65"} },
  1710. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, {"v60", "v62", "v65"} },
  1711. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, {"v60", "v62", "v65"} },
  1712. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, {"v60", "v62", "v65"} },
  1713. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, {"v60", "v62", "v65"} },
  1714. { Hexagon::BI__builtin_HEXAGON_V6_valignb, {"v60", "v62", "v65"} },
  1715. { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, {"v60", "v62", "v65"} },
  1716. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {"v60", "v62", "v65"} },
  1717. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {"v60", "v62", "v65"} },
  1718. { Hexagon::BI__builtin_HEXAGON_V6_vand, {"v60", "v62", "v65"} },
  1719. { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, {"v60", "v62", "v65"} },
  1720. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, {"v62", "v65"} },
  1721. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, {"v62", "v65"} },
  1722. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, {"v62", "v65"} },
  1723. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, {"v62", "v65"} },
  1724. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, {"v60", "v62", "v65"} },
  1725. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, {"v60", "v62", "v65"} },
  1726. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, {"v60", "v62", "v65"} },
  1727. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, {"v60", "v62", "v65"} },
  1728. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, {"v62", "v65"} },
  1729. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, {"v62", "v65"} },
  1730. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, {"v62", "v65"} },
  1731. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, {"v62", "v65"} },
  1732. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, {"v60", "v62", "v65"} },
  1733. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, {"v60", "v62", "v65"} },
  1734. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, {"v60", "v62", "v65"} },
  1735. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, {"v60", "v62", "v65"} },
  1736. { Hexagon::BI__builtin_HEXAGON_V6_vaslh, {"v60", "v62", "v65"} },
  1737. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, {"v60", "v62", "v65"} },
  1738. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, {"v65"} },
  1739. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, {"v65"} },
  1740. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, {"v60", "v62", "v65"} },
  1741. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, {"v60", "v62", "v65"} },
  1742. { Hexagon::BI__builtin_HEXAGON_V6_vaslw, {"v60", "v62", "v65"} },
  1743. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, {"v60", "v62", "v65"} },
  1744. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, {"v60", "v62", "v65"} },
  1745. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, {"v60", "v62", "v65"} },
  1746. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, {"v60", "v62", "v65"} },
  1747. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, {"v60", "v62", "v65"} },
  1748. { Hexagon::BI__builtin_HEXAGON_V6_vasrh, {"v60", "v62", "v65"} },
  1749. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, {"v60", "v62", "v65"} },
  1750. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, {"v65"} },
  1751. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, {"v65"} },
  1752. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, {"v60", "v62", "v65"} },
  1753. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, {"v60", "v62", "v65"} },
  1754. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, {"v62", "v65"} },
  1755. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, {"v62", "v65"} },
  1756. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, {"v60", "v62", "v65"} },
  1757. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, {"v60", "v62", "v65"} },
  1758. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, {"v60", "v62", "v65"} },
  1759. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, {"v60", "v62", "v65"} },
  1760. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, {"v60", "v62", "v65"} },
  1761. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, {"v60", "v62", "v65"} },
  1762. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, {"v65"} },
  1763. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, {"v65"} },
  1764. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, {"v65"} },
  1765. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, {"v65"} },
  1766. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, {"v62", "v65"} },
  1767. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, {"v62", "v65"} },
  1768. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, {"v65"} },
  1769. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, {"v65"} },
  1770. { Hexagon::BI__builtin_HEXAGON_V6_vasrw, {"v60", "v62", "v65"} },
  1771. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, {"v60", "v62", "v65"} },
  1772. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, {"v60", "v62", "v65"} },
  1773. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, {"v60", "v62", "v65"} },
  1774. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, {"v60", "v62", "v65"} },
  1775. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, {"v60", "v62", "v65"} },
  1776. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, {"v60", "v62", "v65"} },
  1777. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, {"v60", "v62", "v65"} },
  1778. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, {"v60", "v62", "v65"} },
  1779. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, {"v60", "v62", "v65"} },
  1780. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, {"v62", "v65"} },
  1781. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, {"v62", "v65"} },
  1782. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, {"v60", "v62", "v65"} },
  1783. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, {"v60", "v62", "v65"} },
  1784. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, {"v60", "v62", "v65"} },
  1785. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, {"v60", "v62", "v65"} },
  1786. { Hexagon::BI__builtin_HEXAGON_V6_vassign, {"v60", "v62", "v65"} },
  1787. { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, {"v60", "v62", "v65"} },
  1788. { Hexagon::BI__builtin_HEXAGON_V6_vassignp, {"v60", "v62", "v65"} },
  1789. { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, {"v60", "v62", "v65"} },
  1790. { Hexagon::BI__builtin_HEXAGON_V6_vavgb, {"v65"} },
  1791. { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, {"v65"} },
  1792. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, {"v65"} },
  1793. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, {"v65"} },
  1794. { Hexagon::BI__builtin_HEXAGON_V6_vavgh, {"v60", "v62", "v65"} },
  1795. { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, {"v60", "v62", "v65"} },
  1796. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, {"v60", "v62", "v65"} },
  1797. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, {"v60", "v62", "v65"} },
  1798. { Hexagon::BI__builtin_HEXAGON_V6_vavgub, {"v60", "v62", "v65"} },
  1799. { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, {"v60", "v62", "v65"} },
  1800. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, {"v60", "v62", "v65"} },
  1801. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, {"v60", "v62", "v65"} },
  1802. { Hexagon::BI__builtin_HEXAGON_V6_vavguh, {"v60", "v62", "v65"} },
  1803. { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, {"v60", "v62", "v65"} },
  1804. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, {"v60", "v62", "v65"} },
  1805. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, {"v60", "v62", "v65"} },
  1806. { Hexagon::BI__builtin_HEXAGON_V6_vavguw, {"v65"} },
  1807. { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, {"v65"} },
  1808. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, {"v65"} },
  1809. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, {"v65"} },
  1810. { Hexagon::BI__builtin_HEXAGON_V6_vavgw, {"v60", "v62", "v65"} },
  1811. { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, {"v60", "v62", "v65"} },
  1812. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, {"v60", "v62", "v65"} },
  1813. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, {"v60", "v62", "v65"} },
  1814. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, {"v60", "v62", "v65"} },
  1815. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, {"v60", "v62", "v65"} },
  1816. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, {"v60", "v62", "v65"} },
  1817. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, {"v60", "v62", "v65"} },
  1818. { Hexagon::BI__builtin_HEXAGON_V6_vcombine, {"v60", "v62", "v65"} },
  1819. { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, {"v60", "v62", "v65"} },
  1820. { Hexagon::BI__builtin_HEXAGON_V6_vd0, {"v60", "v62", "v65"} },
  1821. { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, {"v60", "v62", "v65"} },
  1822. { Hexagon::BI__builtin_HEXAGON_V6_vdd0, {"v65"} },
  1823. { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, {"v65"} },
  1824. { Hexagon::BI__builtin_HEXAGON_V6_vdealb, {"v60", "v62", "v65"} },
  1825. { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, {"v60", "v62", "v65"} },
  1826. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, {"v60", "v62", "v65"} },
  1827. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, {"v60", "v62", "v65"} },
  1828. { Hexagon::BI__builtin_HEXAGON_V6_vdealh, {"v60", "v62", "v65"} },
  1829. { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, {"v60", "v62", "v65"} },
  1830. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, {"v60", "v62", "v65"} },
  1831. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, {"v60", "v62", "v65"} },
  1832. { Hexagon::BI__builtin_HEXAGON_V6_vdelta, {"v60", "v62", "v65"} },
  1833. { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, {"v60", "v62", "v65"} },
  1834. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, {"v60", "v62", "v65"} },
  1835. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, {"v60", "v62", "v65"} },
  1836. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, {"v60", "v62", "v65"} },
  1837. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, {"v60", "v62", "v65"} },
  1838. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, {"v60", "v62", "v65"} },
  1839. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, {"v60", "v62", "v65"} },
  1840. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, {"v60", "v62", "v65"} },
  1841. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, {"v60", "v62", "v65"} },
  1842. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, {"v60", "v62", "v65"} },
  1843. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, {"v60", "v62", "v65"} },
  1844. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, {"v60", "v62", "v65"} },
  1845. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, {"v60", "v62", "v65"} },
  1846. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, {"v60", "v62", "v65"} },
  1847. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, {"v60", "v62", "v65"} },
  1848. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, {"v60", "v62", "v65"} },
  1849. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, {"v60", "v62", "v65"} },
  1850. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, {"v60", "v62", "v65"} },
  1851. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, {"v60", "v62", "v65"} },
  1852. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, {"v60", "v62", "v65"} },
  1853. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, {"v60", "v62", "v65"} },
  1854. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, {"v60", "v62", "v65"} },
  1855. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, {"v60", "v62", "v65"} },
  1856. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, {"v60", "v62", "v65"} },
  1857. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, {"v60", "v62", "v65"} },
  1858. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, {"v60", "v62", "v65"} },
  1859. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, {"v60", "v62", "v65"} },
  1860. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, {"v60", "v62", "v65"} },
  1861. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, {"v60", "v62", "v65"} },
  1862. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, {"v60", "v62", "v65"} },
  1863. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, {"v60", "v62", "v65"} },
  1864. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, {"v60", "v62", "v65"} },
  1865. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, {"v60", "v62", "v65"} },
  1866. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, {"v60", "v62", "v65"} },
  1867. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, {"v60", "v62", "v65"} },
  1868. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, {"v60", "v62", "v65"} },
  1869. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, {"v60", "v62", "v65"} },
  1870. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, {"v60", "v62", "v65"} },
  1871. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, {"v60", "v62", "v65"} },
  1872. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, {"v60", "v62", "v65"} },
  1873. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, {"v60", "v62", "v65"} },
  1874. { Hexagon::BI__builtin_HEXAGON_V6_veqb, {"v60", "v62", "v65"} },
  1875. { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, {"v60", "v62", "v65"} },
  1876. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, {"v60", "v62", "v65"} },
  1877. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, {"v60", "v62", "v65"} },
  1878. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, {"v60", "v62", "v65"} },
  1879. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, {"v60", "v62", "v65"} },
  1880. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, {"v60", "v62", "v65"} },
  1881. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, {"v60", "v62", "v65"} },
  1882. { Hexagon::BI__builtin_HEXAGON_V6_veqh, {"v60", "v62", "v65"} },
  1883. { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, {"v60", "v62", "v65"} },
  1884. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, {"v60", "v62", "v65"} },
  1885. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, {"v60", "v62", "v65"} },
  1886. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, {"v60", "v62", "v65"} },
  1887. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, {"v60", "v62", "v65"} },
  1888. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, {"v60", "v62", "v65"} },
  1889. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, {"v60", "v62", "v65"} },
  1890. { Hexagon::BI__builtin_HEXAGON_V6_veqw, {"v60", "v62", "v65"} },
  1891. { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, {"v60", "v62", "v65"} },
  1892. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, {"v60", "v62", "v65"} },
  1893. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, {"v60", "v62", "v65"} },
  1894. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, {"v60", "v62", "v65"} },
  1895. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, {"v60", "v62", "v65"} },
  1896. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, {"v60", "v62", "v65"} },
  1897. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, {"v60", "v62", "v65"} },
  1898. { Hexagon::BI__builtin_HEXAGON_V6_vgtb, {"v60", "v62", "v65"} },
  1899. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, {"v60", "v62", "v65"} },
  1900. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, {"v60", "v62", "v65"} },
  1901. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, {"v60", "v62", "v65"} },
  1902. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, {"v60", "v62", "v65"} },
  1903. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, {"v60", "v62", "v65"} },
  1904. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, {"v60", "v62", "v65"} },
  1905. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, {"v60", "v62", "v65"} },
  1906. { Hexagon::BI__builtin_HEXAGON_V6_vgth, {"v60", "v62", "v65"} },
  1907. { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, {"v60", "v62", "v65"} },
  1908. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, {"v60", "v62", "v65"} },
  1909. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, {"v60", "v62", "v65"} },
  1910. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, {"v60", "v62", "v65"} },
  1911. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, {"v60", "v62", "v65"} },
  1912. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, {"v60", "v62", "v65"} },
  1913. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, {"v60", "v62", "v65"} },
  1914. { Hexagon::BI__builtin_HEXAGON_V6_vgtub, {"v60", "v62", "v65"} },
  1915. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, {"v60", "v62", "v65"} },
  1916. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, {"v60", "v62", "v65"} },
  1917. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, {"v60", "v62", "v65"} },
  1918. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, {"v60", "v62", "v65"} },
  1919. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, {"v60", "v62", "v65"} },
  1920. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, {"v60", "v62", "v65"} },
  1921. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, {"v60", "v62", "v65"} },
  1922. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, {"v60", "v62", "v65"} },
  1923. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, {"v60", "v62", "v65"} },
  1924. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, {"v60", "v62", "v65"} },
  1925. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, {"v60", "v62", "v65"} },
  1926. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, {"v60", "v62", "v65"} },
  1927. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, {"v60", "v62", "v65"} },
  1928. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, {"v60", "v62", "v65"} },
  1929. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, {"v60", "v62", "v65"} },
  1930. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, {"v60", "v62", "v65"} },
  1931. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, {"v60", "v62", "v65"} },
  1932. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, {"v60", "v62", "v65"} },
  1933. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, {"v60", "v62", "v65"} },
  1934. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, {"v60", "v62", "v65"} },
  1935. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, {"v60", "v62", "v65"} },
  1936. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, {"v60", "v62", "v65"} },
  1937. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, {"v60", "v62", "v65"} },
  1938. { Hexagon::BI__builtin_HEXAGON_V6_vgtw, {"v60", "v62", "v65"} },
  1939. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, {"v60", "v62", "v65"} },
  1940. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, {"v60", "v62", "v65"} },
  1941. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, {"v60", "v62", "v65"} },
  1942. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, {"v60", "v62", "v65"} },
  1943. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, {"v60", "v62", "v65"} },
  1944. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, {"v60", "v62", "v65"} },
  1945. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, {"v60", "v62", "v65"} },
  1946. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, {"v60", "v62", "v65"} },
  1947. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, {"v60", "v62", "v65"} },
  1948. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, {"v60", "v62", "v65"} },
  1949. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, {"v60", "v62", "v65"} },
  1950. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {"v60", "v62", "v65"} },
  1951. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {"v60", "v62", "v65"} },
  1952. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, {"v62", "v65"} },
  1953. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, {"v62", "v65"} },
  1954. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, {"v60", "v62", "v65"} },
  1955. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, {"v60", "v62", "v65"} },
  1956. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, {"v60", "v62", "v65"} },
  1957. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, {"v60", "v62", "v65"} },
  1958. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, {"v60", "v62", "v65"} },
  1959. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, {"v60", "v62", "v65"} },
  1960. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, {"v60", "v62", "v65"} },
  1961. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, {"v60", "v62", "v65"} },
  1962. { Hexagon::BI__builtin_HEXAGON_V6_vlut4, {"v65"} },
  1963. { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, {"v65"} },
  1964. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, {"v60", "v62", "v65"} },
  1965. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, {"v60", "v62", "v65"} },
  1966. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, {"v62", "v65"} },
  1967. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, {"v62", "v65"} },
  1968. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, {"v62", "v65"} },
  1969. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, {"v62", "v65"} },
  1970. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, {"v60", "v62", "v65"} },
  1971. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, {"v60", "v62", "v65"} },
  1972. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, {"v62", "v65"} },
  1973. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, {"v62", "v65"} },
  1974. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, {"v60", "v62", "v65"} },
  1975. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, {"v60", "v62", "v65"} },
  1976. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, {"v62", "v65"} },
  1977. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, {"v62", "v65"} },
  1978. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, {"v62", "v65"} },
  1979. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, {"v62", "v65"} },
  1980. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, {"v60", "v62", "v65"} },
  1981. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, {"v60", "v62", "v65"} },
  1982. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, {"v62", "v65"} },
  1983. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, {"v62", "v65"} },
  1984. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, {"v62", "v65"} },
  1985. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, {"v62", "v65"} },
  1986. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, {"v60", "v62", "v65"} },
  1987. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, {"v60", "v62", "v65"} },
  1988. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, {"v60", "v62", "v65"} },
  1989. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, {"v60", "v62", "v65"} },
  1990. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, {"v60", "v62", "v65"} },
  1991. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, {"v60", "v62", "v65"} },
  1992. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, {"v60", "v62", "v65"} },
  1993. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, {"v60", "v62", "v65"} },
  1994. { Hexagon::BI__builtin_HEXAGON_V6_vminb, {"v62", "v65"} },
  1995. { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, {"v62", "v65"} },
  1996. { Hexagon::BI__builtin_HEXAGON_V6_vminh, {"v60", "v62", "v65"} },
  1997. { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, {"v60", "v62", "v65"} },
  1998. { Hexagon::BI__builtin_HEXAGON_V6_vminub, {"v60", "v62", "v65"} },
  1999. { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, {"v60", "v62", "v65"} },
  2000. { Hexagon::BI__builtin_HEXAGON_V6_vminuh, {"v60", "v62", "v65"} },
  2001. { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, {"v60", "v62", "v65"} },
  2002. { Hexagon::BI__builtin_HEXAGON_V6_vminw, {"v60", "v62", "v65"} },
  2003. { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, {"v60", "v62", "v65"} },
  2004. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, {"v60", "v62", "v65"} },
  2005. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, {"v60", "v62", "v65"} },
  2006. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, {"v60", "v62", "v65"} },
  2007. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, {"v60", "v62", "v65"} },
  2008. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, {"v60", "v62", "v65"} },
  2009. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, {"v60", "v62", "v65"} },
  2010. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, {"v65"} },
  2011. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, {"v65"} },
  2012. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, {"v65"} },
  2013. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, {"v65"} },
  2014. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, {"v60", "v62", "v65"} },
  2015. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, {"v60", "v62", "v65"} },
  2016. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, {"v60", "v62", "v65"} },
  2017. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, {"v60", "v62", "v65"} },
  2018. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, {"v60", "v62", "v65"} },
  2019. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, {"v60", "v62", "v65"} },
  2020. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, {"v65"} },
  2021. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, {"v65"} },
  2022. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, {"v62", "v65"} },
  2023. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, {"v62", "v65"} },
  2024. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, {"v62", "v65"} },
  2025. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, {"v62", "v65"} },
  2026. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, {"v65"} },
  2027. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, {"v65"} },
  2028. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, {"v65"} },
  2029. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, {"v65"} },
  2030. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, {"v60", "v62", "v65"} },
  2031. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, {"v60", "v62", "v65"} },
  2032. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, {"v60", "v62", "v65"} },
  2033. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, {"v60", "v62", "v65"} },
  2034. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, {"v60", "v62", "v65"} },
  2035. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, {"v60", "v62", "v65"} },
  2036. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, {"v60", "v62", "v65"} },
  2037. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, {"v60", "v62", "v65"} },
  2038. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, {"v60", "v62", "v65"} },
  2039. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, {"v60", "v62", "v65"} },
  2040. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, {"v60", "v62", "v65"} },
  2041. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, {"v60", "v62", "v65"} },
  2042. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, {"v60", "v62", "v65"} },
  2043. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, {"v60", "v62", "v65"} },
  2044. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, {"v62", "v65"} },
  2045. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, {"v62", "v65"} },
  2046. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, {"v60", "v62", "v65"} },
  2047. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, {"v60", "v62", "v65"} },
  2048. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, {"v65"} },
  2049. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, {"v65"} },
  2050. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, {"v60", "v62", "v65"} },
  2051. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, {"v60", "v62", "v65"} },
  2052. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, {"v60", "v62", "v65"} },
  2053. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, {"v60", "v62", "v65"} },
  2054. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, {"v60", "v62", "v65"} },
  2055. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, {"v60", "v62", "v65"} },
  2056. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, {"v60", "v62", "v65"} },
  2057. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, {"v60", "v62", "v65"} },
  2058. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, {"v60", "v62", "v65"} },
  2059. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, {"v60", "v62", "v65"} },
  2060. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, {"v60", "v62", "v65"} },
  2061. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, {"v60", "v62", "v65"} },
  2062. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, {"v60", "v62", "v65"} },
  2063. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, {"v60", "v62", "v65"} },
  2064. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, {"v60", "v62", "v65"} },
  2065. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, {"v60", "v62", "v65"} },
  2066. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, {"v60", "v62", "v65"} },
  2067. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, {"v60", "v62", "v65"} },
  2068. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, {"v60", "v62", "v65"} },
  2069. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, {"v60", "v62", "v65"} },
  2070. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, {"v60", "v62", "v65"} },
  2071. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, {"v60", "v62", "v65"} },
  2072. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, {"v60", "v62", "v65"} },
  2073. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, {"v60", "v62", "v65"} },
  2074. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, {"v60", "v62", "v65"} },
  2075. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, {"v60", "v62", "v65"} },
  2076. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, {"v60", "v62", "v65"} },
  2077. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, {"v60", "v62", "v65"} },
  2078. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, {"v60", "v62", "v65"} },
  2079. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, {"v60", "v62", "v65"} },
  2080. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, {"v60", "v62", "v65"} },
  2081. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, {"v60", "v62", "v65"} },
  2082. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, {"v60", "v62", "v65"} },
  2083. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, {"v60", "v62", "v65"} },
  2084. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, {"v60", "v62", "v65"} },
  2085. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, {"v60", "v62", "v65"} },
  2086. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, {"v60", "v62", "v65"} },
  2087. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, {"v60", "v62", "v65"} },
  2088. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, {"v60", "v62", "v65"} },
  2089. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, {"v60", "v62", "v65"} },
  2090. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, {"v60", "v62", "v65"} },
  2091. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, {"v60", "v62", "v65"} },
  2092. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, {"v62", "v65"} },
  2093. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, {"v62", "v65"} },
  2094. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, {"v62", "v65"} },
  2095. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, {"v62", "v65"} },
  2096. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, {"v60", "v62", "v65"} },
  2097. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, {"v60", "v62", "v65"} },
  2098. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, {"v62", "v65"} },
  2099. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, {"v62", "v65"} },
  2100. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, {"v60", "v62", "v65"} },
  2101. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, {"v60", "v62", "v65"} },
  2102. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, {"v60", "v62", "v65"} },
  2103. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, {"v60", "v62", "v65"} },
  2104. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, {"v60", "v62", "v65"} },
  2105. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, {"v60", "v62", "v65"} },
  2106. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, {"v60", "v62", "v65"} },
  2107. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, {"v60", "v62", "v65"} },
  2108. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, {"v60", "v62", "v65"} },
  2109. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, {"v60", "v62", "v65"} },
  2110. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, {"v60", "v62", "v65"} },
  2111. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, {"v60", "v62", "v65"} },
  2112. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, {"v60", "v62", "v65"} },
  2113. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, {"v60", "v62", "v65"} },
  2114. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, {"v60", "v62", "v65"} },
  2115. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, {"v60", "v62", "v65"} },
  2116. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, {"v60", "v62", "v65"} },
  2117. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, {"v60", "v62", "v65"} },
  2118. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, {"v65"} },
  2119. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, {"v65"} },
  2120. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, {"v65"} },
  2121. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, {"v65"} },
  2122. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, {"v60", "v62", "v65"} },
  2123. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, {"v60", "v62", "v65"} },
  2124. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, {"v60", "v62", "v65"} },
  2125. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, {"v60", "v62", "v65"} },
  2126. { Hexagon::BI__builtin_HEXAGON_V6_vmux, {"v60", "v62", "v65"} },
  2127. { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, {"v60", "v62", "v65"} },
  2128. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, {"v65"} },
  2129. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, {"v65"} },
  2130. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, {"v60", "v62", "v65"} },
  2131. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, {"v60", "v62", "v65"} },
  2132. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, {"v60", "v62", "v65"} },
  2133. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, {"v60", "v62", "v65"} },
  2134. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, {"v60", "v62", "v65"} },
  2135. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, {"v60", "v62", "v65"} },
  2136. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, {"v60", "v62", "v65"} },
  2137. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, {"v60", "v62", "v65"} },
  2138. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, {"v60", "v62", "v65"} },
  2139. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, {"v60", "v62", "v65"} },
  2140. { Hexagon::BI__builtin_HEXAGON_V6_vnot, {"v60", "v62", "v65"} },
  2141. { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, {"v60", "v62", "v65"} },
  2142. { Hexagon::BI__builtin_HEXAGON_V6_vor, {"v60", "v62", "v65"} },
  2143. { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, {"v60", "v62", "v65"} },
  2144. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, {"v60", "v62", "v65"} },
  2145. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, {"v60", "v62", "v65"} },
  2146. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, {"v60", "v62", "v65"} },
  2147. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, {"v60", "v62", "v65"} },
  2148. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, {"v60", "v62", "v65"} },
  2149. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, {"v60", "v62", "v65"} },
  2150. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, {"v60", "v62", "v65"} },
  2151. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, {"v60", "v62", "v65"} },
  2152. { Hexagon::BI__builtin_HEXAGON_V6_vpackob, {"v60", "v62", "v65"} },
  2153. { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, {"v60", "v62", "v65"} },
  2154. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, {"v60", "v62", "v65"} },
  2155. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, {"v60", "v62", "v65"} },
  2156. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, {"v60", "v62", "v65"} },
  2157. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, {"v60", "v62", "v65"} },
  2158. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, {"v60", "v62", "v65"} },
  2159. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, {"v60", "v62", "v65"} },
  2160. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, {"v60", "v62", "v65"} },
  2161. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, {"v60", "v62", "v65"} },
  2162. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, {"v65"} },
  2163. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, {"v65"} },
  2164. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, {"v65"} },
  2165. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, {"v65"} },
  2166. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, {"v65"} },
  2167. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, {"v65"} },
  2168. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, {"v60", "v62", "v65"} },
  2169. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, {"v60", "v62", "v65"} },
  2170. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, {"v65"} },
  2171. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, {"v65"} },
  2172. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, {"v65"} },
  2173. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, {"v65"} },
  2174. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, {"v60", "v62", "v65"} },
  2175. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, {"v60", "v62", "v65"} },
  2176. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, {"v60", "v62", "v65"} },
  2177. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, {"v60", "v62", "v65"} },
  2178. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {"v60", "v62", "v65"} },
  2179. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {"v60", "v62", "v65"} },
  2180. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {"v60", "v62", "v65"} },
  2181. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, {"v60", "v62", "v65"} },
  2182. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, {"v60", "v62", "v65"} },
  2183. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, {"v60", "v62", "v65"} },
  2184. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, {"v60", "v62", "v65"} },
  2185. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, {"v60", "v62", "v65"} },
  2186. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, {"v60", "v62", "v65"} },
  2187. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, {"v60", "v62", "v65"} },
  2188. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, {"v60", "v62", "v65"} },
  2189. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, {"v60", "v62", "v65"} },
  2190. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, {"v60", "v62", "v65"} },
  2191. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, {"v60", "v62", "v65"} },
  2192. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, {"v60", "v62", "v65"} },
  2193. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, {"v60", "v62", "v65"} },
  2194. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {"v60", "v62", "v65"} },
  2195. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {"v60", "v62", "v65"} },
  2196. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {"v60", "v62", "v65"} },
  2197. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, {"v60", "v62", "v65"} },
  2198. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, {"v65"} },
  2199. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, {"v65"} },
  2200. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, {"v65"} },
  2201. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, {"v65"} },
  2202. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, {"v60", "v62", "v65"} },
  2203. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, {"v60", "v62", "v65"} },
  2204. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, {"v60", "v62", "v65"} },
  2205. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, {"v60", "v62", "v65"} },
  2206. { Hexagon::BI__builtin_HEXAGON_V6_vror, {"v60", "v62", "v65"} },
  2207. { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, {"v60", "v62", "v65"} },
  2208. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, {"v60", "v62", "v65"} },
  2209. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, {"v60", "v62", "v65"} },
  2210. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, {"v60", "v62", "v65"} },
  2211. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, {"v60", "v62", "v65"} },
  2212. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, {"v62", "v65"} },
  2213. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, {"v62", "v65"} },
  2214. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, {"v62", "v65"} },
  2215. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, {"v62", "v65"} },
  2216. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, {"v60", "v62", "v65"} },
  2217. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, {"v60", "v62", "v65"} },
  2218. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, {"v60", "v62", "v65"} },
  2219. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, {"v60", "v62", "v65"} },
  2220. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {"v60", "v62", "v65"} },
  2221. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {"v60", "v62", "v65"} },
  2222. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {"v60", "v62", "v65"} },
  2223. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, {"v60", "v62", "v65"} },
  2224. { Hexagon::BI__builtin_HEXAGON_V6_vsathub, {"v60", "v62", "v65"} },
  2225. { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, {"v60", "v62", "v65"} },
  2226. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, {"v62", "v65"} },
  2227. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, {"v62", "v65"} },
  2228. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, {"v60", "v62", "v65"} },
  2229. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, {"v60", "v62", "v65"} },
  2230. { Hexagon::BI__builtin_HEXAGON_V6_vsb, {"v60", "v62", "v65"} },
  2231. { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, {"v60", "v62", "v65"} },
  2232. { Hexagon::BI__builtin_HEXAGON_V6_vsh, {"v60", "v62", "v65"} },
  2233. { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, {"v60", "v62", "v65"} },
  2234. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, {"v60", "v62", "v65"} },
  2235. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, {"v60", "v62", "v65"} },
  2236. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, {"v60", "v62", "v65"} },
  2237. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, {"v60", "v62", "v65"} },
  2238. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, {"v60", "v62", "v65"} },
  2239. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, {"v60", "v62", "v65"} },
  2240. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, {"v60", "v62", "v65"} },
  2241. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, {"v60", "v62", "v65"} },
  2242. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, {"v60", "v62", "v65"} },
  2243. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, {"v60", "v62", "v65"} },
  2244. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, {"v60", "v62", "v65"} },
  2245. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, {"v60", "v62", "v65"} },
  2246. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, {"v60", "v62", "v65"} },
  2247. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, {"v60", "v62", "v65"} },
  2248. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, {"v60", "v62", "v65"} },
  2249. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, {"v60", "v62", "v65"} },
  2250. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, {"v60", "v62", "v65"} },
  2251. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, {"v60", "v62", "v65"} },
  2252. { Hexagon::BI__builtin_HEXAGON_V6_vsubb, {"v60", "v62", "v65"} },
  2253. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, {"v60", "v62", "v65"} },
  2254. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, {"v60", "v62", "v65"} },
  2255. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, {"v60", "v62", "v65"} },
  2256. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, {"v62", "v65"} },
  2257. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, {"v62", "v65"} },
  2258. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, {"v62", "v65"} },
  2259. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, {"v62", "v65"} },
  2260. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, {"v62", "v65"} },
  2261. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, {"v62", "v65"} },
  2262. { Hexagon::BI__builtin_HEXAGON_V6_vsubh, {"v60", "v62", "v65"} },
  2263. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, {"v60", "v62", "v65"} },
  2264. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, {"v60", "v62", "v65"} },
  2265. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, {"v60", "v62", "v65"} },
  2266. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, {"v60", "v62", "v65"} },
  2267. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, {"v60", "v62", "v65"} },
  2268. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, {"v60", "v62", "v65"} },
  2269. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, {"v60", "v62", "v65"} },
  2270. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, {"v60", "v62", "v65"} },
  2271. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, {"v60", "v62", "v65"} },
  2272. { Hexagon::BI__builtin_HEXAGON_V6_vsububh, {"v60", "v62", "v65"} },
  2273. { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, {"v60", "v62", "v65"} },
  2274. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, {"v60", "v62", "v65"} },
  2275. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, {"v60", "v62", "v65"} },
  2276. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, {"v60", "v62", "v65"} },
  2277. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, {"v60", "v62", "v65"} },
  2278. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, {"v62", "v65"} },
  2279. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, {"v62", "v65"} },
  2280. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, {"v60", "v62", "v65"} },
  2281. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, {"v60", "v62", "v65"} },
  2282. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, {"v60", "v62", "v65"} },
  2283. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, {"v60", "v62", "v65"} },
  2284. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, {"v60", "v62", "v65"} },
  2285. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, {"v60", "v62", "v65"} },
  2286. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, {"v62", "v65"} },
  2287. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, {"v62", "v65"} },
  2288. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, {"v62", "v65"} },
  2289. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, {"v62", "v65"} },
  2290. { Hexagon::BI__builtin_HEXAGON_V6_vsubw, {"v60", "v62", "v65"} },
  2291. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, {"v60", "v62", "v65"} },
  2292. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, {"v60", "v62", "v65"} },
  2293. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, {"v60", "v62", "v65"} },
  2294. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, {"v60", "v62", "v65"} },
  2295. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, {"v60", "v62", "v65"} },
  2296. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, {"v60", "v62", "v65"} },
  2297. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, {"v60", "v62", "v65"} },
  2298. { Hexagon::BI__builtin_HEXAGON_V6_vswap, {"v60", "v62", "v65"} },
  2299. { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, {"v60", "v62", "v65"} },
  2300. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, {"v60", "v62", "v65"} },
  2301. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, {"v60", "v62", "v65"} },
  2302. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, {"v60", "v62", "v65"} },
  2303. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, {"v60", "v62", "v65"} },
  2304. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, {"v60", "v62", "v65"} },
  2305. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, {"v60", "v62", "v65"} },
  2306. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, {"v60", "v62", "v65"} },
  2307. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, {"v60", "v62", "v65"} },
  2308. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, {"v60", "v62", "v65"} },
  2309. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, {"v60", "v62", "v65"} },
  2310. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, {"v60", "v62", "v65"} },
  2311. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, {"v60", "v62", "v65"} },
  2312. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, {"v60", "v62", "v65"} },
  2313. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, {"v60", "v62", "v65"} },
  2314. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, {"v60", "v62", "v65"} },
  2315. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, {"v60", "v62", "v65"} },
  2316. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, {"v60", "v62", "v65"} },
  2317. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, {"v60", "v62", "v65"} },
  2318. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, {"v60", "v62", "v65"} },
  2319. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, {"v60", "v62", "v65"} },
  2320. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, {"v60", "v62", "v65"} },
  2321. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, {"v60", "v62", "v65"} },
  2322. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, {"v60", "v62", "v65"} },
  2323. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, {"v60", "v62", "v65"} },
  2324. { Hexagon::BI__builtin_HEXAGON_V6_vxor, {"v60", "v62", "v65"} },
  2325. { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, {"v60", "v62", "v65"} },
  2326. { Hexagon::BI__builtin_HEXAGON_V6_vzb, {"v60", "v62", "v65"} },
  2327. { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, {"v60", "v62", "v65"} },
  2328. { Hexagon::BI__builtin_HEXAGON_V6_vzh, {"v60", "v62", "v65"} },
  2329. { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, {"v60", "v62", "v65"} },
  2330. };
  2331. const TargetInfo &TI = Context.getTargetInfo();
  2332. auto FC = ValidCPU.find(BuiltinID);
  2333. if (FC != ValidCPU.end()) {
  2334. const TargetOptions &Opts = TI.getTargetOpts();
  2335. StringRef CPU = Opts.CPU;
  2336. if (!CPU.empty()) {
  2337. assert(CPU.startswith("hexagon") && "Unexpected CPU name");
  2338. CPU.consume_front("hexagon");
  2339. if (llvm::none_of(FC->second, [CPU](StringRef S) { return S == CPU; }))
  2340. return Diag(TheCall->getLocStart(),
  2341. diag::err_hexagon_builtin_unsupported_cpu);
  2342. }
  2343. }
  2344. auto FH = ValidHVX.find(BuiltinID);
  2345. if (FH != ValidHVX.end()) {
  2346. if (!TI.hasFeature("hvx"))
  2347. return Diag(TheCall->getLocStart(),
  2348. diag::err_hexagon_builtin_requires_hvx);
  2349. bool IsValid = llvm::any_of(FH->second,
  2350. [&TI] (StringRef V) {
  2351. std::string F = "hvx" + V.str();
  2352. return TI.hasFeature(F);
  2353. });
  2354. if (!IsValid)
  2355. return Diag(TheCall->getLocStart(),
  2356. diag::err_hexagon_builtin_unsupported_hvx);
  2357. }
  2358. return false;
  2359. }
  2360. bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
  2361. struct ArgInfo {
  2362. ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
  2363. : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
  2364. unsigned OpNum = 0;
  2365. bool IsSigned = false;
  2366. unsigned BitWidth = 0;
  2367. unsigned Align = 0;
  2368. };
  2369. static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
  2370. { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
  2371. { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
  2372. { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
  2373. { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
  2374. { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
  2375. { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
  2376. { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
  2377. { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
  2378. { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
  2379. { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
  2380. { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
  2381. { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
  2382. { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
  2383. { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
  2384. { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
  2385. { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
  2386. { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
  2387. { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
  2388. { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
  2389. { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
  2390. { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
  2391. { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
  2392. { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
  2393. { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
  2394. { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
  2395. { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
  2396. { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
  2397. { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
  2398. { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
  2399. { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
  2400. { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
  2401. { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
  2402. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
  2403. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
  2404. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
  2405. { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
  2406. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
  2407. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
  2408. { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
  2409. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
  2410. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
  2411. { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
  2412. { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
  2413. { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
  2414. { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
  2415. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
  2416. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
  2417. { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
  2418. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
  2419. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
  2420. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
  2421. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
  2422. { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
  2423. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
  2424. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
  2425. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
  2426. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
  2427. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
  2428. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
  2429. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
  2430. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
  2431. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
  2432. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
  2433. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
  2434. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
  2435. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
  2436. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
  2437. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
  2438. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
  2439. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
  2440. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
  2441. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
  2442. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
  2443. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
  2444. {{ 1, false, 6, 0 }} },
  2445. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
  2446. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
  2447. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
  2448. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
  2449. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
  2450. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
  2451. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
  2452. {{ 1, false, 5, 0 }} },
  2453. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
  2454. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
  2455. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
  2456. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
  2457. { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
  2458. { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
  2459. { 2, false, 5, 0 }} },
  2460. { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
  2461. { 2, false, 6, 0 }} },
  2462. { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
  2463. { 3, false, 5, 0 }} },
  2464. { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
  2465. { 3, false, 6, 0 }} },
  2466. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
  2467. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
  2468. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
  2469. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
  2470. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
  2471. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
  2472. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
  2473. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
  2474. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
  2475. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
  2476. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
  2477. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
  2478. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
  2479. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
  2480. { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
  2481. { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
  2482. {{ 2, false, 4, 0 },
  2483. { 3, false, 5, 0 }} },
  2484. { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
  2485. {{ 2, false, 4, 0 },
  2486. { 3, false, 5, 0 }} },
  2487. { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
  2488. {{ 2, false, 4, 0 },
  2489. { 3, false, 5, 0 }} },
  2490. { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
  2491. {{ 2, false, 4, 0 },
  2492. { 3, false, 5, 0 }} },
  2493. { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
  2494. { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
  2495. { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
  2496. { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
  2497. { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
  2498. { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
  2499. { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
  2500. { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
  2501. { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
  2502. { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
  2503. { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
  2504. { 2, false, 5, 0 }} },
  2505. { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
  2506. { 2, false, 6, 0 }} },
  2507. { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
  2508. { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
  2509. { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
  2510. { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
  2511. { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
  2512. { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
  2513. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
  2514. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
  2515. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
  2516. {{ 1, false, 4, 0 }} },
  2517. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
  2518. { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
  2519. {{ 1, false, 4, 0 }} },
  2520. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
  2521. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
  2522. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
  2523. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
  2524. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
  2525. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
  2526. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
  2527. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
  2528. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
  2529. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
  2530. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
  2531. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
  2532. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
  2533. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
  2534. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
  2535. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
  2536. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
  2537. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
  2538. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
  2539. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
  2540. {{ 3, false, 1, 0 }} },
  2541. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
  2542. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
  2543. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
  2544. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
  2545. {{ 3, false, 1, 0 }} },
  2546. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
  2547. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
  2548. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
  2549. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
  2550. {{ 3, false, 1, 0 }} },
  2551. };
  2552. auto F = Infos.find(BuiltinID);
  2553. if (F == Infos.end())
  2554. return false;
  2555. bool Error = false;
  2556. for (const ArgInfo &A : F->second) {
  2557. int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
  2558. int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
  2559. if (!A.Align) {
  2560. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
  2561. } else {
  2562. unsigned M = 1 << A.Align;
  2563. Min *= M;
  2564. Max *= M;
  2565. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
  2566. SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
  2567. }
  2568. }
  2569. return Error;
  2570. }
  2571. bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
  2572. CallExpr *TheCall) {
  2573. return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
  2574. CheckHexagonBuiltinArgument(BuiltinID, TheCall);
  2575. }
  2576. // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
  2577. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  2578. // ordering for DSP is unspecified. MSA is ordered by the data format used
  2579. // by the underlying instruction i.e., df/m, df/n and then by size.
  2580. //
  2581. // FIXME: The size tests here should instead be tablegen'd along with the
  2582. // definitions from include/clang/Basic/BuiltinsMips.def.
  2583. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  2584. // be too.
  2585. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2586. unsigned i = 0, l = 0, u = 0, m = 0;
  2587. switch (BuiltinID) {
  2588. default: return false;
  2589. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  2590. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  2591. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  2592. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  2593. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  2594. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  2595. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  2596. // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
  2597. // df/m field.
  2598. // These intrinsics take an unsigned 3 bit immediate.
  2599. case Mips::BI__builtin_msa_bclri_b:
  2600. case Mips::BI__builtin_msa_bnegi_b:
  2601. case Mips::BI__builtin_msa_bseti_b:
  2602. case Mips::BI__builtin_msa_sat_s_b:
  2603. case Mips::BI__builtin_msa_sat_u_b:
  2604. case Mips::BI__builtin_msa_slli_b:
  2605. case Mips::BI__builtin_msa_srai_b:
  2606. case Mips::BI__builtin_msa_srari_b:
  2607. case Mips::BI__builtin_msa_srli_b:
  2608. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  2609. case Mips::BI__builtin_msa_binsli_b:
  2610. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  2611. // These intrinsics take an unsigned 4 bit immediate.
  2612. case Mips::BI__builtin_msa_bclri_h:
  2613. case Mips::BI__builtin_msa_bnegi_h:
  2614. case Mips::BI__builtin_msa_bseti_h:
  2615. case Mips::BI__builtin_msa_sat_s_h:
  2616. case Mips::BI__builtin_msa_sat_u_h:
  2617. case Mips::BI__builtin_msa_slli_h:
  2618. case Mips::BI__builtin_msa_srai_h:
  2619. case Mips::BI__builtin_msa_srari_h:
  2620. case Mips::BI__builtin_msa_srli_h:
  2621. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  2622. case Mips::BI__builtin_msa_binsli_h:
  2623. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  2624. // These intrinsics take an unsigned 5 bit immediate.
  2625. // The first block of intrinsics actually have an unsigned 5 bit field,
  2626. // not a df/n field.
  2627. case Mips::BI__builtin_msa_clei_u_b:
  2628. case Mips::BI__builtin_msa_clei_u_h:
  2629. case Mips::BI__builtin_msa_clei_u_w:
  2630. case Mips::BI__builtin_msa_clei_u_d:
  2631. case Mips::BI__builtin_msa_clti_u_b:
  2632. case Mips::BI__builtin_msa_clti_u_h:
  2633. case Mips::BI__builtin_msa_clti_u_w:
  2634. case Mips::BI__builtin_msa_clti_u_d:
  2635. case Mips::BI__builtin_msa_maxi_u_b:
  2636. case Mips::BI__builtin_msa_maxi_u_h:
  2637. case Mips::BI__builtin_msa_maxi_u_w:
  2638. case Mips::BI__builtin_msa_maxi_u_d:
  2639. case Mips::BI__builtin_msa_mini_u_b:
  2640. case Mips::BI__builtin_msa_mini_u_h:
  2641. case Mips::BI__builtin_msa_mini_u_w:
  2642. case Mips::BI__builtin_msa_mini_u_d:
  2643. case Mips::BI__builtin_msa_addvi_b:
  2644. case Mips::BI__builtin_msa_addvi_h:
  2645. case Mips::BI__builtin_msa_addvi_w:
  2646. case Mips::BI__builtin_msa_addvi_d:
  2647. case Mips::BI__builtin_msa_bclri_w:
  2648. case Mips::BI__builtin_msa_bnegi_w:
  2649. case Mips::BI__builtin_msa_bseti_w:
  2650. case Mips::BI__builtin_msa_sat_s_w:
  2651. case Mips::BI__builtin_msa_sat_u_w:
  2652. case Mips::BI__builtin_msa_slli_w:
  2653. case Mips::BI__builtin_msa_srai_w:
  2654. case Mips::BI__builtin_msa_srari_w:
  2655. case Mips::BI__builtin_msa_srli_w:
  2656. case Mips::BI__builtin_msa_srlri_w:
  2657. case Mips::BI__builtin_msa_subvi_b:
  2658. case Mips::BI__builtin_msa_subvi_h:
  2659. case Mips::BI__builtin_msa_subvi_w:
  2660. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  2661. case Mips::BI__builtin_msa_binsli_w:
  2662. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  2663. // These intrinsics take an unsigned 6 bit immediate.
  2664. case Mips::BI__builtin_msa_bclri_d:
  2665. case Mips::BI__builtin_msa_bnegi_d:
  2666. case Mips::BI__builtin_msa_bseti_d:
  2667. case Mips::BI__builtin_msa_sat_s_d:
  2668. case Mips::BI__builtin_msa_sat_u_d:
  2669. case Mips::BI__builtin_msa_slli_d:
  2670. case Mips::BI__builtin_msa_srai_d:
  2671. case Mips::BI__builtin_msa_srari_d:
  2672. case Mips::BI__builtin_msa_srli_d:
  2673. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  2674. case Mips::BI__builtin_msa_binsli_d:
  2675. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  2676. // These intrinsics take a signed 5 bit immediate.
  2677. case Mips::BI__builtin_msa_ceqi_b:
  2678. case Mips::BI__builtin_msa_ceqi_h:
  2679. case Mips::BI__builtin_msa_ceqi_w:
  2680. case Mips::BI__builtin_msa_ceqi_d:
  2681. case Mips::BI__builtin_msa_clti_s_b:
  2682. case Mips::BI__builtin_msa_clti_s_h:
  2683. case Mips::BI__builtin_msa_clti_s_w:
  2684. case Mips::BI__builtin_msa_clti_s_d:
  2685. case Mips::BI__builtin_msa_clei_s_b:
  2686. case Mips::BI__builtin_msa_clei_s_h:
  2687. case Mips::BI__builtin_msa_clei_s_w:
  2688. case Mips::BI__builtin_msa_clei_s_d:
  2689. case Mips::BI__builtin_msa_maxi_s_b:
  2690. case Mips::BI__builtin_msa_maxi_s_h:
  2691. case Mips::BI__builtin_msa_maxi_s_w:
  2692. case Mips::BI__builtin_msa_maxi_s_d:
  2693. case Mips::BI__builtin_msa_mini_s_b:
  2694. case Mips::BI__builtin_msa_mini_s_h:
  2695. case Mips::BI__builtin_msa_mini_s_w:
  2696. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  2697. // These intrinsics take an unsigned 8 bit immediate.
  2698. case Mips::BI__builtin_msa_andi_b:
  2699. case Mips::BI__builtin_msa_nori_b:
  2700. case Mips::BI__builtin_msa_ori_b:
  2701. case Mips::BI__builtin_msa_shf_b:
  2702. case Mips::BI__builtin_msa_shf_h:
  2703. case Mips::BI__builtin_msa_shf_w:
  2704. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  2705. case Mips::BI__builtin_msa_bseli_b:
  2706. case Mips::BI__builtin_msa_bmnzi_b:
  2707. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  2708. // df/n format
  2709. // These intrinsics take an unsigned 4 bit immediate.
  2710. case Mips::BI__builtin_msa_copy_s_b:
  2711. case Mips::BI__builtin_msa_copy_u_b:
  2712. case Mips::BI__builtin_msa_insve_b:
  2713. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  2714. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  2715. // These intrinsics take an unsigned 3 bit immediate.
  2716. case Mips::BI__builtin_msa_copy_s_h:
  2717. case Mips::BI__builtin_msa_copy_u_h:
  2718. case Mips::BI__builtin_msa_insve_h:
  2719. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  2720. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  2721. // These intrinsics take an unsigned 2 bit immediate.
  2722. case Mips::BI__builtin_msa_copy_s_w:
  2723. case Mips::BI__builtin_msa_copy_u_w:
  2724. case Mips::BI__builtin_msa_insve_w:
  2725. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  2726. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  2727. // These intrinsics take an unsigned 1 bit immediate.
  2728. case Mips::BI__builtin_msa_copy_s_d:
  2729. case Mips::BI__builtin_msa_copy_u_d:
  2730. case Mips::BI__builtin_msa_insve_d:
  2731. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  2732. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  2733. // Memory offsets and immediate loads.
  2734. // These intrinsics take a signed 10 bit immediate.
  2735. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  2736. case Mips::BI__builtin_msa_ldi_h:
  2737. case Mips::BI__builtin_msa_ldi_w:
  2738. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  2739. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
  2740. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
  2741. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
  2742. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
  2743. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
  2744. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
  2745. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
  2746. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
  2747. }
  2748. if (!m)
  2749. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2750. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  2751. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  2752. }
  2753. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2754. unsigned i = 0, l = 0, u = 0;
  2755. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  2756. BuiltinID == PPC::BI__builtin_divdeu ||
  2757. BuiltinID == PPC::BI__builtin_bpermd;
  2758. bool IsTarget64Bit = Context.getTargetInfo()
  2759. .getTypeWidth(Context
  2760. .getTargetInfo()
  2761. .getIntPtrType()) == 64;
  2762. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  2763. BuiltinID == PPC::BI__builtin_divweu ||
  2764. BuiltinID == PPC::BI__builtin_divde ||
  2765. BuiltinID == PPC::BI__builtin_divdeu;
  2766. if (Is64BitBltin && !IsTarget64Bit)
  2767. return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
  2768. << TheCall->getSourceRange();
  2769. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  2770. (BuiltinID == PPC::BI__builtin_bpermd &&
  2771. !Context.getTargetInfo().hasFeature("bpermd")))
  2772. return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
  2773. << TheCall->getSourceRange();
  2774. switch (BuiltinID) {
  2775. default: return false;
  2776. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  2777. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  2778. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  2779. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  2780. case PPC::BI__builtin_tbegin:
  2781. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  2782. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  2783. case PPC::BI__builtin_tabortwc:
  2784. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  2785. case PPC::BI__builtin_tabortwci:
  2786. case PPC::BI__builtin_tabortdci:
  2787. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  2788. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  2789. case PPC::BI__builtin_vsx_xxpermdi:
  2790. case PPC::BI__builtin_vsx_xxsldwi:
  2791. return SemaBuiltinVSX(TheCall);
  2792. }
  2793. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2794. }
  2795. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  2796. CallExpr *TheCall) {
  2797. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  2798. Expr *Arg = TheCall->getArg(0);
  2799. llvm::APSInt AbortCode(32);
  2800. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  2801. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  2802. return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
  2803. << Arg->getSourceRange();
  2804. }
  2805. // For intrinsics which take an immediate value as part of the instruction,
  2806. // range check them here.
  2807. unsigned i = 0, l = 0, u = 0;
  2808. switch (BuiltinID) {
  2809. default: return false;
  2810. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  2811. case SystemZ::BI__builtin_s390_verimb:
  2812. case SystemZ::BI__builtin_s390_verimh:
  2813. case SystemZ::BI__builtin_s390_verimf:
  2814. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  2815. case SystemZ::BI__builtin_s390_vfaeb:
  2816. case SystemZ::BI__builtin_s390_vfaeh:
  2817. case SystemZ::BI__builtin_s390_vfaef:
  2818. case SystemZ::BI__builtin_s390_vfaebs:
  2819. case SystemZ::BI__builtin_s390_vfaehs:
  2820. case SystemZ::BI__builtin_s390_vfaefs:
  2821. case SystemZ::BI__builtin_s390_vfaezb:
  2822. case SystemZ::BI__builtin_s390_vfaezh:
  2823. case SystemZ::BI__builtin_s390_vfaezf:
  2824. case SystemZ::BI__builtin_s390_vfaezbs:
  2825. case SystemZ::BI__builtin_s390_vfaezhs:
  2826. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  2827. case SystemZ::BI__builtin_s390_vfisb:
  2828. case SystemZ::BI__builtin_s390_vfidb:
  2829. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  2830. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  2831. case SystemZ::BI__builtin_s390_vftcisb:
  2832. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  2833. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  2834. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  2835. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  2836. case SystemZ::BI__builtin_s390_vstrcb:
  2837. case SystemZ::BI__builtin_s390_vstrch:
  2838. case SystemZ::BI__builtin_s390_vstrcf:
  2839. case SystemZ::BI__builtin_s390_vstrczb:
  2840. case SystemZ::BI__builtin_s390_vstrczh:
  2841. case SystemZ::BI__builtin_s390_vstrczf:
  2842. case SystemZ::BI__builtin_s390_vstrcbs:
  2843. case SystemZ::BI__builtin_s390_vstrchs:
  2844. case SystemZ::BI__builtin_s390_vstrcfs:
  2845. case SystemZ::BI__builtin_s390_vstrczbs:
  2846. case SystemZ::BI__builtin_s390_vstrczhs:
  2847. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  2848. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  2849. case SystemZ::BI__builtin_s390_vfminsb:
  2850. case SystemZ::BI__builtin_s390_vfmaxsb:
  2851. case SystemZ::BI__builtin_s390_vfmindb:
  2852. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  2853. }
  2854. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2855. }
  2856. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  2857. /// This checks that the target supports __builtin_cpu_supports and
  2858. /// that the string argument is constant and valid.
  2859. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  2860. Expr *Arg = TheCall->getArg(0);
  2861. // Check if the argument is a string literal.
  2862. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  2863. return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  2864. << Arg->getSourceRange();
  2865. // Check the contents of the string.
  2866. StringRef Feature =
  2867. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  2868. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  2869. return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
  2870. << Arg->getSourceRange();
  2871. return false;
  2872. }
  2873. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  2874. /// This checks that the target supports __builtin_cpu_is and
  2875. /// that the string argument is constant and valid.
  2876. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  2877. Expr *Arg = TheCall->getArg(0);
  2878. // Check if the argument is a string literal.
  2879. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  2880. return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  2881. << Arg->getSourceRange();
  2882. // Check the contents of the string.
  2883. StringRef Feature =
  2884. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  2885. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  2886. return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
  2887. << Arg->getSourceRange();
  2888. return false;
  2889. }
  2890. // Check if the rounding mode is legal.
  2891. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  2892. // Indicates if this instruction has rounding control or just SAE.
  2893. bool HasRC = false;
  2894. unsigned ArgNum = 0;
  2895. switch (BuiltinID) {
  2896. default:
  2897. return false;
  2898. case X86::BI__builtin_ia32_vcvttsd2si32:
  2899. case X86::BI__builtin_ia32_vcvttsd2si64:
  2900. case X86::BI__builtin_ia32_vcvttsd2usi32:
  2901. case X86::BI__builtin_ia32_vcvttsd2usi64:
  2902. case X86::BI__builtin_ia32_vcvttss2si32:
  2903. case X86::BI__builtin_ia32_vcvttss2si64:
  2904. case X86::BI__builtin_ia32_vcvttss2usi32:
  2905. case X86::BI__builtin_ia32_vcvttss2usi64:
  2906. ArgNum = 1;
  2907. break;
  2908. case X86::BI__builtin_ia32_maxpd512:
  2909. case X86::BI__builtin_ia32_maxps512:
  2910. case X86::BI__builtin_ia32_minpd512:
  2911. case X86::BI__builtin_ia32_minps512:
  2912. ArgNum = 2;
  2913. break;
  2914. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  2915. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  2916. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  2917. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  2918. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  2919. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  2920. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  2921. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  2922. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  2923. case X86::BI__builtin_ia32_exp2pd_mask:
  2924. case X86::BI__builtin_ia32_exp2ps_mask:
  2925. case X86::BI__builtin_ia32_getexppd512_mask:
  2926. case X86::BI__builtin_ia32_getexpps512_mask:
  2927. case X86::BI__builtin_ia32_rcp28pd_mask:
  2928. case X86::BI__builtin_ia32_rcp28ps_mask:
  2929. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  2930. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  2931. case X86::BI__builtin_ia32_vcomisd:
  2932. case X86::BI__builtin_ia32_vcomiss:
  2933. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  2934. ArgNum = 3;
  2935. break;
  2936. case X86::BI__builtin_ia32_cmppd512_mask:
  2937. case X86::BI__builtin_ia32_cmpps512_mask:
  2938. case X86::BI__builtin_ia32_cmpsd_mask:
  2939. case X86::BI__builtin_ia32_cmpss_mask:
  2940. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  2941. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  2942. case X86::BI__builtin_ia32_getexpss128_round_mask:
  2943. case X86::BI__builtin_ia32_maxsd_round_mask:
  2944. case X86::BI__builtin_ia32_maxss_round_mask:
  2945. case X86::BI__builtin_ia32_minsd_round_mask:
  2946. case X86::BI__builtin_ia32_minss_round_mask:
  2947. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  2948. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  2949. case X86::BI__builtin_ia32_reducepd512_mask:
  2950. case X86::BI__builtin_ia32_reduceps512_mask:
  2951. case X86::BI__builtin_ia32_rndscalepd_mask:
  2952. case X86::BI__builtin_ia32_rndscaleps_mask:
  2953. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  2954. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  2955. ArgNum = 4;
  2956. break;
  2957. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  2958. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  2959. case X86::BI__builtin_ia32_fixupimmps512_mask:
  2960. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  2961. case X86::BI__builtin_ia32_fixupimmsd_mask:
  2962. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  2963. case X86::BI__builtin_ia32_fixupimmss_mask:
  2964. case X86::BI__builtin_ia32_fixupimmss_maskz:
  2965. case X86::BI__builtin_ia32_rangepd512_mask:
  2966. case X86::BI__builtin_ia32_rangeps512_mask:
  2967. case X86::BI__builtin_ia32_rangesd128_round_mask:
  2968. case X86::BI__builtin_ia32_rangess128_round_mask:
  2969. case X86::BI__builtin_ia32_reducesd_mask:
  2970. case X86::BI__builtin_ia32_reducess_mask:
  2971. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  2972. case X86::BI__builtin_ia32_rndscaless_round_mask:
  2973. ArgNum = 5;
  2974. break;
  2975. case X86::BI__builtin_ia32_vcvtsd2si64:
  2976. case X86::BI__builtin_ia32_vcvtsd2si32:
  2977. case X86::BI__builtin_ia32_vcvtsd2usi32:
  2978. case X86::BI__builtin_ia32_vcvtsd2usi64:
  2979. case X86::BI__builtin_ia32_vcvtss2si32:
  2980. case X86::BI__builtin_ia32_vcvtss2si64:
  2981. case X86::BI__builtin_ia32_vcvtss2usi32:
  2982. case X86::BI__builtin_ia32_vcvtss2usi64:
  2983. case X86::BI__builtin_ia32_sqrtpd512:
  2984. case X86::BI__builtin_ia32_sqrtps512:
  2985. ArgNum = 1;
  2986. HasRC = true;
  2987. break;
  2988. case X86::BI__builtin_ia32_addpd512:
  2989. case X86::BI__builtin_ia32_addps512:
  2990. case X86::BI__builtin_ia32_divpd512:
  2991. case X86::BI__builtin_ia32_divps512:
  2992. case X86::BI__builtin_ia32_mulpd512:
  2993. case X86::BI__builtin_ia32_mulps512:
  2994. case X86::BI__builtin_ia32_subpd512:
  2995. case X86::BI__builtin_ia32_subps512:
  2996. case X86::BI__builtin_ia32_cvtsi2sd64:
  2997. case X86::BI__builtin_ia32_cvtsi2ss32:
  2998. case X86::BI__builtin_ia32_cvtsi2ss64:
  2999. case X86::BI__builtin_ia32_cvtusi2sd64:
  3000. case X86::BI__builtin_ia32_cvtusi2ss32:
  3001. case X86::BI__builtin_ia32_cvtusi2ss64:
  3002. ArgNum = 2;
  3003. HasRC = true;
  3004. break;
  3005. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  3006. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  3007. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  3008. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  3009. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  3010. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  3011. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  3012. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  3013. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  3014. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  3015. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  3016. ArgNum = 3;
  3017. HasRC = true;
  3018. break;
  3019. case X86::BI__builtin_ia32_addss_round_mask:
  3020. case X86::BI__builtin_ia32_addsd_round_mask:
  3021. case X86::BI__builtin_ia32_divss_round_mask:
  3022. case X86::BI__builtin_ia32_divsd_round_mask:
  3023. case X86::BI__builtin_ia32_mulss_round_mask:
  3024. case X86::BI__builtin_ia32_mulsd_round_mask:
  3025. case X86::BI__builtin_ia32_subss_round_mask:
  3026. case X86::BI__builtin_ia32_subsd_round_mask:
  3027. case X86::BI__builtin_ia32_scalefpd512_mask:
  3028. case X86::BI__builtin_ia32_scalefps512_mask:
  3029. case X86::BI__builtin_ia32_scalefsd_round_mask:
  3030. case X86::BI__builtin_ia32_scalefss_round_mask:
  3031. case X86::BI__builtin_ia32_getmantpd512_mask:
  3032. case X86::BI__builtin_ia32_getmantps512_mask:
  3033. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  3034. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  3035. case X86::BI__builtin_ia32_sqrtss_round_mask:
  3036. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  3037. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  3038. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  3039. case X86::BI__builtin_ia32_vfmaddss3_mask:
  3040. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  3041. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  3042. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  3043. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  3044. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  3045. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  3046. case X86::BI__builtin_ia32_vfmaddps512_mask:
  3047. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  3048. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  3049. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  3050. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  3051. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  3052. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  3053. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  3054. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  3055. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  3056. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  3057. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  3058. ArgNum = 4;
  3059. HasRC = true;
  3060. break;
  3061. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3062. case X86::BI__builtin_ia32_getmantss_round_mask:
  3063. ArgNum = 5;
  3064. HasRC = true;
  3065. break;
  3066. }
  3067. llvm::APSInt Result;
  3068. // We can't check the value of a dependent argument.
  3069. Expr *Arg = TheCall->getArg(ArgNum);
  3070. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3071. return false;
  3072. // Check constant-ness first.
  3073. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3074. return true;
  3075. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  3076. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  3077. // combined with ROUND_NO_EXC.
  3078. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  3079. Result == 8/*ROUND_NO_EXC*/ ||
  3080. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  3081. return false;
  3082. return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
  3083. << Arg->getSourceRange();
  3084. }
  3085. // Check if the gather/scatter scale is legal.
  3086. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  3087. CallExpr *TheCall) {
  3088. unsigned ArgNum = 0;
  3089. switch (BuiltinID) {
  3090. default:
  3091. return false;
  3092. case X86::BI__builtin_ia32_gatherpfdpd:
  3093. case X86::BI__builtin_ia32_gatherpfdps:
  3094. case X86::BI__builtin_ia32_gatherpfqpd:
  3095. case X86::BI__builtin_ia32_gatherpfqps:
  3096. case X86::BI__builtin_ia32_scatterpfdpd:
  3097. case X86::BI__builtin_ia32_scatterpfdps:
  3098. case X86::BI__builtin_ia32_scatterpfqpd:
  3099. case X86::BI__builtin_ia32_scatterpfqps:
  3100. ArgNum = 3;
  3101. break;
  3102. case X86::BI__builtin_ia32_gatherd_pd:
  3103. case X86::BI__builtin_ia32_gatherd_pd256:
  3104. case X86::BI__builtin_ia32_gatherq_pd:
  3105. case X86::BI__builtin_ia32_gatherq_pd256:
  3106. case X86::BI__builtin_ia32_gatherd_ps:
  3107. case X86::BI__builtin_ia32_gatherd_ps256:
  3108. case X86::BI__builtin_ia32_gatherq_ps:
  3109. case X86::BI__builtin_ia32_gatherq_ps256:
  3110. case X86::BI__builtin_ia32_gatherd_q:
  3111. case X86::BI__builtin_ia32_gatherd_q256:
  3112. case X86::BI__builtin_ia32_gatherq_q:
  3113. case X86::BI__builtin_ia32_gatherq_q256:
  3114. case X86::BI__builtin_ia32_gatherd_d:
  3115. case X86::BI__builtin_ia32_gatherd_d256:
  3116. case X86::BI__builtin_ia32_gatherq_d:
  3117. case X86::BI__builtin_ia32_gatherq_d256:
  3118. case X86::BI__builtin_ia32_gather3div2df:
  3119. case X86::BI__builtin_ia32_gather3div2di:
  3120. case X86::BI__builtin_ia32_gather3div4df:
  3121. case X86::BI__builtin_ia32_gather3div4di:
  3122. case X86::BI__builtin_ia32_gather3div4sf:
  3123. case X86::BI__builtin_ia32_gather3div4si:
  3124. case X86::BI__builtin_ia32_gather3div8sf:
  3125. case X86::BI__builtin_ia32_gather3div8si:
  3126. case X86::BI__builtin_ia32_gather3siv2df:
  3127. case X86::BI__builtin_ia32_gather3siv2di:
  3128. case X86::BI__builtin_ia32_gather3siv4df:
  3129. case X86::BI__builtin_ia32_gather3siv4di:
  3130. case X86::BI__builtin_ia32_gather3siv4sf:
  3131. case X86::BI__builtin_ia32_gather3siv4si:
  3132. case X86::BI__builtin_ia32_gather3siv8sf:
  3133. case X86::BI__builtin_ia32_gather3siv8si:
  3134. case X86::BI__builtin_ia32_gathersiv8df:
  3135. case X86::BI__builtin_ia32_gathersiv16sf:
  3136. case X86::BI__builtin_ia32_gatherdiv8df:
  3137. case X86::BI__builtin_ia32_gatherdiv16sf:
  3138. case X86::BI__builtin_ia32_gathersiv8di:
  3139. case X86::BI__builtin_ia32_gathersiv16si:
  3140. case X86::BI__builtin_ia32_gatherdiv8di:
  3141. case X86::BI__builtin_ia32_gatherdiv16si:
  3142. case X86::BI__builtin_ia32_scatterdiv2df:
  3143. case X86::BI__builtin_ia32_scatterdiv2di:
  3144. case X86::BI__builtin_ia32_scatterdiv4df:
  3145. case X86::BI__builtin_ia32_scatterdiv4di:
  3146. case X86::BI__builtin_ia32_scatterdiv4sf:
  3147. case X86::BI__builtin_ia32_scatterdiv4si:
  3148. case X86::BI__builtin_ia32_scatterdiv8sf:
  3149. case X86::BI__builtin_ia32_scatterdiv8si:
  3150. case X86::BI__builtin_ia32_scattersiv2df:
  3151. case X86::BI__builtin_ia32_scattersiv2di:
  3152. case X86::BI__builtin_ia32_scattersiv4df:
  3153. case X86::BI__builtin_ia32_scattersiv4di:
  3154. case X86::BI__builtin_ia32_scattersiv4sf:
  3155. case X86::BI__builtin_ia32_scattersiv4si:
  3156. case X86::BI__builtin_ia32_scattersiv8sf:
  3157. case X86::BI__builtin_ia32_scattersiv8si:
  3158. case X86::BI__builtin_ia32_scattersiv8df:
  3159. case X86::BI__builtin_ia32_scattersiv16sf:
  3160. case X86::BI__builtin_ia32_scatterdiv8df:
  3161. case X86::BI__builtin_ia32_scatterdiv16sf:
  3162. case X86::BI__builtin_ia32_scattersiv8di:
  3163. case X86::BI__builtin_ia32_scattersiv16si:
  3164. case X86::BI__builtin_ia32_scatterdiv8di:
  3165. case X86::BI__builtin_ia32_scatterdiv16si:
  3166. ArgNum = 4;
  3167. break;
  3168. }
  3169. llvm::APSInt Result;
  3170. // We can't check the value of a dependent argument.
  3171. Expr *Arg = TheCall->getArg(ArgNum);
  3172. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3173. return false;
  3174. // Check constant-ness first.
  3175. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3176. return true;
  3177. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  3178. return false;
  3179. return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
  3180. << Arg->getSourceRange();
  3181. }
  3182. static bool isX86_32Builtin(unsigned BuiltinID) {
  3183. // These builtins only work on x86-32 targets.
  3184. switch (BuiltinID) {
  3185. case X86::BI__builtin_ia32_readeflags_u32:
  3186. case X86::BI__builtin_ia32_writeeflags_u32:
  3187. return true;
  3188. }
  3189. return false;
  3190. }
  3191. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  3192. if (BuiltinID == X86::BI__builtin_cpu_supports)
  3193. return SemaBuiltinCpuSupports(*this, TheCall);
  3194. if (BuiltinID == X86::BI__builtin_cpu_is)
  3195. return SemaBuiltinCpuIs(*this, TheCall);
  3196. // Check for 32-bit only builtins on a 64-bit target.
  3197. const llvm::Triple &TT = Context.getTargetInfo().getTriple();
  3198. if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
  3199. return Diag(TheCall->getCallee()->getLocStart(),
  3200. diag::err_32_bit_builtin_64_bit_tgt);
  3201. // If the intrinsic has rounding or SAE make sure its valid.
  3202. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  3203. return true;
  3204. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  3205. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  3206. return true;
  3207. // For intrinsics which take an immediate value as part of the instruction,
  3208. // range check them here.
  3209. int i = 0, l = 0, u = 0;
  3210. switch (BuiltinID) {
  3211. default:
  3212. return false;
  3213. case X86::BI__builtin_ia32_vec_ext_v2si:
  3214. case X86::BI__builtin_ia32_vec_ext_v2di:
  3215. case X86::BI__builtin_ia32_vextractf128_pd256:
  3216. case X86::BI__builtin_ia32_vextractf128_ps256:
  3217. case X86::BI__builtin_ia32_vextractf128_si256:
  3218. case X86::BI__builtin_ia32_extract128i256:
  3219. case X86::BI__builtin_ia32_extractf64x4_mask:
  3220. case X86::BI__builtin_ia32_extracti64x4_mask:
  3221. case X86::BI__builtin_ia32_extractf32x8_mask:
  3222. case X86::BI__builtin_ia32_extracti32x8_mask:
  3223. case X86::BI__builtin_ia32_extractf64x2_256_mask:
  3224. case X86::BI__builtin_ia32_extracti64x2_256_mask:
  3225. case X86::BI__builtin_ia32_extractf32x4_256_mask:
  3226. case X86::BI__builtin_ia32_extracti32x4_256_mask:
  3227. i = 1; l = 0; u = 1;
  3228. break;
  3229. case X86::BI__builtin_ia32_vec_set_v2di:
  3230. case X86::BI__builtin_ia32_vinsertf128_pd256:
  3231. case X86::BI__builtin_ia32_vinsertf128_ps256:
  3232. case X86::BI__builtin_ia32_vinsertf128_si256:
  3233. case X86::BI__builtin_ia32_insert128i256:
  3234. case X86::BI__builtin_ia32_insertf32x8:
  3235. case X86::BI__builtin_ia32_inserti32x8:
  3236. case X86::BI__builtin_ia32_insertf64x4:
  3237. case X86::BI__builtin_ia32_inserti64x4:
  3238. case X86::BI__builtin_ia32_insertf64x2_256:
  3239. case X86::BI__builtin_ia32_inserti64x2_256:
  3240. case X86::BI__builtin_ia32_insertf32x4_256:
  3241. case X86::BI__builtin_ia32_inserti32x4_256:
  3242. i = 2; l = 0; u = 1;
  3243. break;
  3244. case X86::BI__builtin_ia32_vpermilpd:
  3245. case X86::BI__builtin_ia32_vec_ext_v4hi:
  3246. case X86::BI__builtin_ia32_vec_ext_v4si:
  3247. case X86::BI__builtin_ia32_vec_ext_v4sf:
  3248. case X86::BI__builtin_ia32_vec_ext_v4di:
  3249. case X86::BI__builtin_ia32_extractf32x4_mask:
  3250. case X86::BI__builtin_ia32_extracti32x4_mask:
  3251. case X86::BI__builtin_ia32_extractf64x2_512_mask:
  3252. case X86::BI__builtin_ia32_extracti64x2_512_mask:
  3253. i = 1; l = 0; u = 3;
  3254. break;
  3255. case X86::BI_mm_prefetch:
  3256. case X86::BI__builtin_ia32_vec_ext_v8hi:
  3257. case X86::BI__builtin_ia32_vec_ext_v8si:
  3258. i = 1; l = 0; u = 7;
  3259. break;
  3260. case X86::BI__builtin_ia32_sha1rnds4:
  3261. case X86::BI__builtin_ia32_blendpd:
  3262. case X86::BI__builtin_ia32_shufpd:
  3263. case X86::BI__builtin_ia32_vec_set_v4hi:
  3264. case X86::BI__builtin_ia32_vec_set_v4si:
  3265. case X86::BI__builtin_ia32_vec_set_v4di:
  3266. case X86::BI__builtin_ia32_shuf_f32x4_256:
  3267. case X86::BI__builtin_ia32_shuf_f64x2_256:
  3268. case X86::BI__builtin_ia32_shuf_i32x4_256:
  3269. case X86::BI__builtin_ia32_shuf_i64x2_256:
  3270. case X86::BI__builtin_ia32_insertf64x2_512:
  3271. case X86::BI__builtin_ia32_inserti64x2_512:
  3272. case X86::BI__builtin_ia32_insertf32x4:
  3273. case X86::BI__builtin_ia32_inserti32x4:
  3274. i = 2; l = 0; u = 3;
  3275. break;
  3276. case X86::BI__builtin_ia32_vpermil2pd:
  3277. case X86::BI__builtin_ia32_vpermil2pd256:
  3278. case X86::BI__builtin_ia32_vpermil2ps:
  3279. case X86::BI__builtin_ia32_vpermil2ps256:
  3280. i = 3; l = 0; u = 3;
  3281. break;
  3282. case X86::BI__builtin_ia32_cmpb128_mask:
  3283. case X86::BI__builtin_ia32_cmpw128_mask:
  3284. case X86::BI__builtin_ia32_cmpd128_mask:
  3285. case X86::BI__builtin_ia32_cmpq128_mask:
  3286. case X86::BI__builtin_ia32_cmpb256_mask:
  3287. case X86::BI__builtin_ia32_cmpw256_mask:
  3288. case X86::BI__builtin_ia32_cmpd256_mask:
  3289. case X86::BI__builtin_ia32_cmpq256_mask:
  3290. case X86::BI__builtin_ia32_cmpb512_mask:
  3291. case X86::BI__builtin_ia32_cmpw512_mask:
  3292. case X86::BI__builtin_ia32_cmpd512_mask:
  3293. case X86::BI__builtin_ia32_cmpq512_mask:
  3294. case X86::BI__builtin_ia32_ucmpb128_mask:
  3295. case X86::BI__builtin_ia32_ucmpw128_mask:
  3296. case X86::BI__builtin_ia32_ucmpd128_mask:
  3297. case X86::BI__builtin_ia32_ucmpq128_mask:
  3298. case X86::BI__builtin_ia32_ucmpb256_mask:
  3299. case X86::BI__builtin_ia32_ucmpw256_mask:
  3300. case X86::BI__builtin_ia32_ucmpd256_mask:
  3301. case X86::BI__builtin_ia32_ucmpq256_mask:
  3302. case X86::BI__builtin_ia32_ucmpb512_mask:
  3303. case X86::BI__builtin_ia32_ucmpw512_mask:
  3304. case X86::BI__builtin_ia32_ucmpd512_mask:
  3305. case X86::BI__builtin_ia32_ucmpq512_mask:
  3306. case X86::BI__builtin_ia32_vpcomub:
  3307. case X86::BI__builtin_ia32_vpcomuw:
  3308. case X86::BI__builtin_ia32_vpcomud:
  3309. case X86::BI__builtin_ia32_vpcomuq:
  3310. case X86::BI__builtin_ia32_vpcomb:
  3311. case X86::BI__builtin_ia32_vpcomw:
  3312. case X86::BI__builtin_ia32_vpcomd:
  3313. case X86::BI__builtin_ia32_vpcomq:
  3314. case X86::BI__builtin_ia32_vec_set_v8hi:
  3315. case X86::BI__builtin_ia32_vec_set_v8si:
  3316. i = 2; l = 0; u = 7;
  3317. break;
  3318. case X86::BI__builtin_ia32_vpermilpd256:
  3319. case X86::BI__builtin_ia32_roundps:
  3320. case X86::BI__builtin_ia32_roundpd:
  3321. case X86::BI__builtin_ia32_roundps256:
  3322. case X86::BI__builtin_ia32_roundpd256:
  3323. case X86::BI__builtin_ia32_getmantpd128_mask:
  3324. case X86::BI__builtin_ia32_getmantpd256_mask:
  3325. case X86::BI__builtin_ia32_getmantps128_mask:
  3326. case X86::BI__builtin_ia32_getmantps256_mask:
  3327. case X86::BI__builtin_ia32_getmantpd512_mask:
  3328. case X86::BI__builtin_ia32_getmantps512_mask:
  3329. case X86::BI__builtin_ia32_vec_ext_v16qi:
  3330. case X86::BI__builtin_ia32_vec_ext_v16hi:
  3331. i = 1; l = 0; u = 15;
  3332. break;
  3333. case X86::BI__builtin_ia32_pblendd128:
  3334. case X86::BI__builtin_ia32_blendps:
  3335. case X86::BI__builtin_ia32_blendpd256:
  3336. case X86::BI__builtin_ia32_shufpd256:
  3337. case X86::BI__builtin_ia32_roundss:
  3338. case X86::BI__builtin_ia32_roundsd:
  3339. case X86::BI__builtin_ia32_rangepd128_mask:
  3340. case X86::BI__builtin_ia32_rangepd256_mask:
  3341. case X86::BI__builtin_ia32_rangepd512_mask:
  3342. case X86::BI__builtin_ia32_rangeps128_mask:
  3343. case X86::BI__builtin_ia32_rangeps256_mask:
  3344. case X86::BI__builtin_ia32_rangeps512_mask:
  3345. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3346. case X86::BI__builtin_ia32_getmantss_round_mask:
  3347. case X86::BI__builtin_ia32_vec_set_v16qi:
  3348. case X86::BI__builtin_ia32_vec_set_v16hi:
  3349. i = 2; l = 0; u = 15;
  3350. break;
  3351. case X86::BI__builtin_ia32_vec_ext_v32qi:
  3352. i = 1; l = 0; u = 31;
  3353. break;
  3354. case X86::BI__builtin_ia32_cmpps:
  3355. case X86::BI__builtin_ia32_cmpss:
  3356. case X86::BI__builtin_ia32_cmppd:
  3357. case X86::BI__builtin_ia32_cmpsd:
  3358. case X86::BI__builtin_ia32_cmpps256:
  3359. case X86::BI__builtin_ia32_cmppd256:
  3360. case X86::BI__builtin_ia32_cmpps128_mask:
  3361. case X86::BI__builtin_ia32_cmppd128_mask:
  3362. case X86::BI__builtin_ia32_cmpps256_mask:
  3363. case X86::BI__builtin_ia32_cmppd256_mask:
  3364. case X86::BI__builtin_ia32_cmpps512_mask:
  3365. case X86::BI__builtin_ia32_cmppd512_mask:
  3366. case X86::BI__builtin_ia32_cmpsd_mask:
  3367. case X86::BI__builtin_ia32_cmpss_mask:
  3368. case X86::BI__builtin_ia32_vec_set_v32qi:
  3369. i = 2; l = 0; u = 31;
  3370. break;
  3371. case X86::BI__builtin_ia32_permdf256:
  3372. case X86::BI__builtin_ia32_permdi256:
  3373. case X86::BI__builtin_ia32_permdf512:
  3374. case X86::BI__builtin_ia32_permdi512:
  3375. case X86::BI__builtin_ia32_vpermilps:
  3376. case X86::BI__builtin_ia32_vpermilps256:
  3377. case X86::BI__builtin_ia32_vpermilpd512:
  3378. case X86::BI__builtin_ia32_vpermilps512:
  3379. case X86::BI__builtin_ia32_pshufd:
  3380. case X86::BI__builtin_ia32_pshufd256:
  3381. case X86::BI__builtin_ia32_pshufd512:
  3382. case X86::BI__builtin_ia32_pshufhw:
  3383. case X86::BI__builtin_ia32_pshufhw256:
  3384. case X86::BI__builtin_ia32_pshufhw512:
  3385. case X86::BI__builtin_ia32_pshuflw:
  3386. case X86::BI__builtin_ia32_pshuflw256:
  3387. case X86::BI__builtin_ia32_pshuflw512:
  3388. case X86::BI__builtin_ia32_vcvtps2ph:
  3389. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  3390. case X86::BI__builtin_ia32_vcvtps2ph256:
  3391. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  3392. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  3393. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  3394. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  3395. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  3396. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  3397. case X86::BI__builtin_ia32_rndscaleps_mask:
  3398. case X86::BI__builtin_ia32_rndscalepd_mask:
  3399. case X86::BI__builtin_ia32_reducepd128_mask:
  3400. case X86::BI__builtin_ia32_reducepd256_mask:
  3401. case X86::BI__builtin_ia32_reducepd512_mask:
  3402. case X86::BI__builtin_ia32_reduceps128_mask:
  3403. case X86::BI__builtin_ia32_reduceps256_mask:
  3404. case X86::BI__builtin_ia32_reduceps512_mask:
  3405. case X86::BI__builtin_ia32_prold512:
  3406. case X86::BI__builtin_ia32_prolq512:
  3407. case X86::BI__builtin_ia32_prold128:
  3408. case X86::BI__builtin_ia32_prold256:
  3409. case X86::BI__builtin_ia32_prolq128:
  3410. case X86::BI__builtin_ia32_prolq256:
  3411. case X86::BI__builtin_ia32_prord512:
  3412. case X86::BI__builtin_ia32_prorq512:
  3413. case X86::BI__builtin_ia32_prord128:
  3414. case X86::BI__builtin_ia32_prord256:
  3415. case X86::BI__builtin_ia32_prorq128:
  3416. case X86::BI__builtin_ia32_prorq256:
  3417. case X86::BI__builtin_ia32_fpclasspd128_mask:
  3418. case X86::BI__builtin_ia32_fpclasspd256_mask:
  3419. case X86::BI__builtin_ia32_fpclassps128_mask:
  3420. case X86::BI__builtin_ia32_fpclassps256_mask:
  3421. case X86::BI__builtin_ia32_fpclassps512_mask:
  3422. case X86::BI__builtin_ia32_fpclasspd512_mask:
  3423. case X86::BI__builtin_ia32_fpclasssd_mask:
  3424. case X86::BI__builtin_ia32_fpclassss_mask:
  3425. case X86::BI__builtin_ia32_pslldqi128_byteshift:
  3426. case X86::BI__builtin_ia32_pslldqi256_byteshift:
  3427. case X86::BI__builtin_ia32_pslldqi512_byteshift:
  3428. case X86::BI__builtin_ia32_psrldqi128_byteshift:
  3429. case X86::BI__builtin_ia32_psrldqi256_byteshift:
  3430. case X86::BI__builtin_ia32_psrldqi512_byteshift:
  3431. i = 1; l = 0; u = 255;
  3432. break;
  3433. case X86::BI__builtin_ia32_vperm2f128_pd256:
  3434. case X86::BI__builtin_ia32_vperm2f128_ps256:
  3435. case X86::BI__builtin_ia32_vperm2f128_si256:
  3436. case X86::BI__builtin_ia32_permti256:
  3437. case X86::BI__builtin_ia32_pblendw128:
  3438. case X86::BI__builtin_ia32_pblendw256:
  3439. case X86::BI__builtin_ia32_blendps256:
  3440. case X86::BI__builtin_ia32_pblendd256:
  3441. case X86::BI__builtin_ia32_palignr128:
  3442. case X86::BI__builtin_ia32_palignr256:
  3443. case X86::BI__builtin_ia32_palignr512:
  3444. case X86::BI__builtin_ia32_alignq512:
  3445. case X86::BI__builtin_ia32_alignd512:
  3446. case X86::BI__builtin_ia32_alignd128:
  3447. case X86::BI__builtin_ia32_alignd256:
  3448. case X86::BI__builtin_ia32_alignq128:
  3449. case X86::BI__builtin_ia32_alignq256:
  3450. case X86::BI__builtin_ia32_vcomisd:
  3451. case X86::BI__builtin_ia32_vcomiss:
  3452. case X86::BI__builtin_ia32_shuf_f32x4:
  3453. case X86::BI__builtin_ia32_shuf_f64x2:
  3454. case X86::BI__builtin_ia32_shuf_i32x4:
  3455. case X86::BI__builtin_ia32_shuf_i64x2:
  3456. case X86::BI__builtin_ia32_shufpd512:
  3457. case X86::BI__builtin_ia32_shufps:
  3458. case X86::BI__builtin_ia32_shufps256:
  3459. case X86::BI__builtin_ia32_shufps512:
  3460. case X86::BI__builtin_ia32_dbpsadbw128:
  3461. case X86::BI__builtin_ia32_dbpsadbw256:
  3462. case X86::BI__builtin_ia32_dbpsadbw512:
  3463. case X86::BI__builtin_ia32_vpshldd128:
  3464. case X86::BI__builtin_ia32_vpshldd256:
  3465. case X86::BI__builtin_ia32_vpshldd512:
  3466. case X86::BI__builtin_ia32_vpshldq128:
  3467. case X86::BI__builtin_ia32_vpshldq256:
  3468. case X86::BI__builtin_ia32_vpshldq512:
  3469. case X86::BI__builtin_ia32_vpshldw128:
  3470. case X86::BI__builtin_ia32_vpshldw256:
  3471. case X86::BI__builtin_ia32_vpshldw512:
  3472. case X86::BI__builtin_ia32_vpshrdd128:
  3473. case X86::BI__builtin_ia32_vpshrdd256:
  3474. case X86::BI__builtin_ia32_vpshrdd512:
  3475. case X86::BI__builtin_ia32_vpshrdq128:
  3476. case X86::BI__builtin_ia32_vpshrdq256:
  3477. case X86::BI__builtin_ia32_vpshrdq512:
  3478. case X86::BI__builtin_ia32_vpshrdw128:
  3479. case X86::BI__builtin_ia32_vpshrdw256:
  3480. case X86::BI__builtin_ia32_vpshrdw512:
  3481. i = 2; l = 0; u = 255;
  3482. break;
  3483. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3484. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3485. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3486. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3487. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3488. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3489. case X86::BI__builtin_ia32_fixupimmss_mask:
  3490. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3491. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  3492. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  3493. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  3494. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  3495. case X86::BI__builtin_ia32_fixupimmps128_mask:
  3496. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  3497. case X86::BI__builtin_ia32_fixupimmps256_mask:
  3498. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  3499. case X86::BI__builtin_ia32_pternlogd512_mask:
  3500. case X86::BI__builtin_ia32_pternlogd512_maskz:
  3501. case X86::BI__builtin_ia32_pternlogq512_mask:
  3502. case X86::BI__builtin_ia32_pternlogq512_maskz:
  3503. case X86::BI__builtin_ia32_pternlogd128_mask:
  3504. case X86::BI__builtin_ia32_pternlogd128_maskz:
  3505. case X86::BI__builtin_ia32_pternlogd256_mask:
  3506. case X86::BI__builtin_ia32_pternlogd256_maskz:
  3507. case X86::BI__builtin_ia32_pternlogq128_mask:
  3508. case X86::BI__builtin_ia32_pternlogq128_maskz:
  3509. case X86::BI__builtin_ia32_pternlogq256_mask:
  3510. case X86::BI__builtin_ia32_pternlogq256_maskz:
  3511. i = 3; l = 0; u = 255;
  3512. break;
  3513. case X86::BI__builtin_ia32_gatherpfdpd:
  3514. case X86::BI__builtin_ia32_gatherpfdps:
  3515. case X86::BI__builtin_ia32_gatherpfqpd:
  3516. case X86::BI__builtin_ia32_gatherpfqps:
  3517. case X86::BI__builtin_ia32_scatterpfdpd:
  3518. case X86::BI__builtin_ia32_scatterpfdps:
  3519. case X86::BI__builtin_ia32_scatterpfqpd:
  3520. case X86::BI__builtin_ia32_scatterpfqps:
  3521. i = 4; l = 2; u = 3;
  3522. break;
  3523. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3524. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3525. i = 4; l = 0; u = 255;
  3526. break;
  3527. }
  3528. // Note that we don't force a hard error on the range check here, allowing
  3529. // template-generated or macro-generated dead code to potentially have out-of-
  3530. // range values. These need to code generate, but don't need to necessarily
  3531. // make any sense. We use a warning that defaults to an error.
  3532. return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
  3533. }
  3534. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  3535. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  3536. /// Returns true when the format fits the function and the FormatStringInfo has
  3537. /// been populated.
  3538. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  3539. FormatStringInfo *FSI) {
  3540. FSI->HasVAListArg = Format->getFirstArg() == 0;
  3541. FSI->FormatIdx = Format->getFormatIdx() - 1;
  3542. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  3543. // The way the format attribute works in GCC, the implicit this argument
  3544. // of member functions is counted. However, it doesn't appear in our own
  3545. // lists, so decrement format_idx in that case.
  3546. if (IsCXXMember) {
  3547. if(FSI->FormatIdx == 0)
  3548. return false;
  3549. --FSI->FormatIdx;
  3550. if (FSI->FirstDataArg != 0)
  3551. --FSI->FirstDataArg;
  3552. }
  3553. return true;
  3554. }
  3555. /// Checks if a the given expression evaluates to null.
  3556. ///
  3557. /// Returns true if the value evaluates to null.
  3558. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  3559. // If the expression has non-null type, it doesn't evaluate to null.
  3560. if (auto nullability
  3561. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  3562. if (*nullability == NullabilityKind::NonNull)
  3563. return false;
  3564. }
  3565. // As a special case, transparent unions initialized with zero are
  3566. // considered null for the purposes of the nonnull attribute.
  3567. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  3568. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  3569. if (const CompoundLiteralExpr *CLE =
  3570. dyn_cast<CompoundLiteralExpr>(Expr))
  3571. if (const InitListExpr *ILE =
  3572. dyn_cast<InitListExpr>(CLE->getInitializer()))
  3573. Expr = ILE->getInit(0);
  3574. }
  3575. bool Result;
  3576. return (!Expr->isValueDependent() &&
  3577. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  3578. !Result);
  3579. }
  3580. static void CheckNonNullArgument(Sema &S,
  3581. const Expr *ArgExpr,
  3582. SourceLocation CallSiteLoc) {
  3583. if (CheckNonNullExpr(S, ArgExpr))
  3584. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  3585. S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
  3586. }
  3587. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  3588. FormatStringInfo FSI;
  3589. if ((GetFormatStringType(Format) == FST_NSString) &&
  3590. getFormatStringInfo(Format, false, &FSI)) {
  3591. Idx = FSI.FormatIdx;
  3592. return true;
  3593. }
  3594. return false;
  3595. }
  3596. /// Diagnose use of %s directive in an NSString which is being passed
  3597. /// as formatting string to formatting method.
  3598. static void
  3599. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  3600. const NamedDecl *FDecl,
  3601. Expr **Args,
  3602. unsigned NumArgs) {
  3603. unsigned Idx = 0;
  3604. bool Format = false;
  3605. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  3606. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  3607. Idx = 2;
  3608. Format = true;
  3609. }
  3610. else
  3611. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3612. if (S.GetFormatNSStringIdx(I, Idx)) {
  3613. Format = true;
  3614. break;
  3615. }
  3616. }
  3617. if (!Format || NumArgs <= Idx)
  3618. return;
  3619. const Expr *FormatExpr = Args[Idx];
  3620. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  3621. FormatExpr = CSCE->getSubExpr();
  3622. const StringLiteral *FormatString;
  3623. if (const ObjCStringLiteral *OSL =
  3624. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  3625. FormatString = OSL->getString();
  3626. else
  3627. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  3628. if (!FormatString)
  3629. return;
  3630. if (S.FormatStringHasSArg(FormatString)) {
  3631. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  3632. << "%s" << 1 << 1;
  3633. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  3634. << FDecl->getDeclName();
  3635. }
  3636. }
  3637. /// Determine whether the given type has a non-null nullability annotation.
  3638. static bool isNonNullType(ASTContext &ctx, QualType type) {
  3639. if (auto nullability = type->getNullability(ctx))
  3640. return *nullability == NullabilityKind::NonNull;
  3641. return false;
  3642. }
  3643. static void CheckNonNullArguments(Sema &S,
  3644. const NamedDecl *FDecl,
  3645. const FunctionProtoType *Proto,
  3646. ArrayRef<const Expr *> Args,
  3647. SourceLocation CallSiteLoc) {
  3648. assert((FDecl || Proto) && "Need a function declaration or prototype");
  3649. // Check the attributes attached to the method/function itself.
  3650. llvm::SmallBitVector NonNullArgs;
  3651. if (FDecl) {
  3652. // Handle the nonnull attribute on the function/method declaration itself.
  3653. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  3654. if (!NonNull->args_size()) {
  3655. // Easy case: all pointer arguments are nonnull.
  3656. for (const auto *Arg : Args)
  3657. if (S.isValidPointerAttrType(Arg->getType()))
  3658. CheckNonNullArgument(S, Arg, CallSiteLoc);
  3659. return;
  3660. }
  3661. for (const ParamIdx &Idx : NonNull->args()) {
  3662. unsigned IdxAST = Idx.getASTIndex();
  3663. if (IdxAST >= Args.size())
  3664. continue;
  3665. if (NonNullArgs.empty())
  3666. NonNullArgs.resize(Args.size());
  3667. NonNullArgs.set(IdxAST);
  3668. }
  3669. }
  3670. }
  3671. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  3672. // Handle the nonnull attribute on the parameters of the
  3673. // function/method.
  3674. ArrayRef<ParmVarDecl*> parms;
  3675. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  3676. parms = FD->parameters();
  3677. else
  3678. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  3679. unsigned ParamIndex = 0;
  3680. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  3681. I != E; ++I, ++ParamIndex) {
  3682. const ParmVarDecl *PVD = *I;
  3683. if (PVD->hasAttr<NonNullAttr>() ||
  3684. isNonNullType(S.Context, PVD->getType())) {
  3685. if (NonNullArgs.empty())
  3686. NonNullArgs.resize(Args.size());
  3687. NonNullArgs.set(ParamIndex);
  3688. }
  3689. }
  3690. } else {
  3691. // If we have a non-function, non-method declaration but no
  3692. // function prototype, try to dig out the function prototype.
  3693. if (!Proto) {
  3694. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  3695. QualType type = VD->getType().getNonReferenceType();
  3696. if (auto pointerType = type->getAs<PointerType>())
  3697. type = pointerType->getPointeeType();
  3698. else if (auto blockType = type->getAs<BlockPointerType>())
  3699. type = blockType->getPointeeType();
  3700. // FIXME: data member pointers?
  3701. // Dig out the function prototype, if there is one.
  3702. Proto = type->getAs<FunctionProtoType>();
  3703. }
  3704. }
  3705. // Fill in non-null argument information from the nullability
  3706. // information on the parameter types (if we have them).
  3707. if (Proto) {
  3708. unsigned Index = 0;
  3709. for (auto paramType : Proto->getParamTypes()) {
  3710. if (isNonNullType(S.Context, paramType)) {
  3711. if (NonNullArgs.empty())
  3712. NonNullArgs.resize(Args.size());
  3713. NonNullArgs.set(Index);
  3714. }
  3715. ++Index;
  3716. }
  3717. }
  3718. }
  3719. // Check for non-null arguments.
  3720. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  3721. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  3722. if (NonNullArgs[ArgIndex])
  3723. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  3724. }
  3725. }
  3726. /// Handles the checks for format strings, non-POD arguments to vararg
  3727. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  3728. /// attributes.
  3729. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  3730. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  3731. bool IsMemberFunction, SourceLocation Loc,
  3732. SourceRange Range, VariadicCallType CallType) {
  3733. // FIXME: We should check as much as we can in the template definition.
  3734. if (CurContext->isDependentContext())
  3735. return;
  3736. // Printf and scanf checking.
  3737. llvm::SmallBitVector CheckedVarArgs;
  3738. if (FDecl) {
  3739. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3740. // Only create vector if there are format attributes.
  3741. CheckedVarArgs.resize(Args.size());
  3742. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  3743. CheckedVarArgs);
  3744. }
  3745. }
  3746. // Refuse POD arguments that weren't caught by the format string
  3747. // checks above.
  3748. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  3749. if (CallType != VariadicDoesNotApply &&
  3750. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  3751. unsigned NumParams = Proto ? Proto->getNumParams()
  3752. : FDecl && isa<FunctionDecl>(FDecl)
  3753. ? cast<FunctionDecl>(FDecl)->getNumParams()
  3754. : FDecl && isa<ObjCMethodDecl>(FDecl)
  3755. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  3756. : 0;
  3757. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  3758. // Args[ArgIdx] can be null in malformed code.
  3759. if (const Expr *Arg = Args[ArgIdx]) {
  3760. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  3761. checkVariadicArgument(Arg, CallType);
  3762. }
  3763. }
  3764. }
  3765. if (FDecl || Proto) {
  3766. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  3767. // Type safety checking.
  3768. if (FDecl) {
  3769. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  3770. CheckArgumentWithTypeTag(I, Args, Loc);
  3771. }
  3772. }
  3773. if (FD)
  3774. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  3775. }
  3776. /// CheckConstructorCall - Check a constructor call for correctness and safety
  3777. /// properties not enforced by the C type system.
  3778. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  3779. ArrayRef<const Expr *> Args,
  3780. const FunctionProtoType *Proto,
  3781. SourceLocation Loc) {
  3782. VariadicCallType CallType =
  3783. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  3784. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  3785. Loc, SourceRange(), CallType);
  3786. }
  3787. /// CheckFunctionCall - Check a direct function call for various correctness
  3788. /// and safety properties not strictly enforced by the C type system.
  3789. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  3790. const FunctionProtoType *Proto) {
  3791. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  3792. isa<CXXMethodDecl>(FDecl);
  3793. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  3794. IsMemberOperatorCall;
  3795. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  3796. TheCall->getCallee());
  3797. Expr** Args = TheCall->getArgs();
  3798. unsigned NumArgs = TheCall->getNumArgs();
  3799. Expr *ImplicitThis = nullptr;
  3800. if (IsMemberOperatorCall) {
  3801. // If this is a call to a member operator, hide the first argument
  3802. // from checkCall.
  3803. // FIXME: Our choice of AST representation here is less than ideal.
  3804. ImplicitThis = Args[0];
  3805. ++Args;
  3806. --NumArgs;
  3807. } else if (IsMemberFunction)
  3808. ImplicitThis =
  3809. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  3810. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  3811. IsMemberFunction, TheCall->getRParenLoc(),
  3812. TheCall->getCallee()->getSourceRange(), CallType);
  3813. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  3814. // None of the checks below are needed for functions that don't have
  3815. // simple names (e.g., C++ conversion functions).
  3816. if (!FnInfo)
  3817. return false;
  3818. CheckAbsoluteValueFunction(TheCall, FDecl);
  3819. CheckMaxUnsignedZero(TheCall, FDecl);
  3820. if (getLangOpts().ObjC1)
  3821. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  3822. unsigned CMId = FDecl->getMemoryFunctionKind();
  3823. if (CMId == 0)
  3824. return false;
  3825. // Handle memory setting and copying functions.
  3826. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  3827. CheckStrlcpycatArguments(TheCall, FnInfo);
  3828. else if (CMId == Builtin::BIstrncat)
  3829. CheckStrncatArguments(TheCall, FnInfo);
  3830. else
  3831. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  3832. return false;
  3833. }
  3834. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  3835. ArrayRef<const Expr *> Args) {
  3836. VariadicCallType CallType =
  3837. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  3838. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  3839. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  3840. CallType);
  3841. return false;
  3842. }
  3843. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  3844. const FunctionProtoType *Proto) {
  3845. QualType Ty;
  3846. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  3847. Ty = V->getType().getNonReferenceType();
  3848. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  3849. Ty = F->getType().getNonReferenceType();
  3850. else
  3851. return false;
  3852. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  3853. !Ty->isFunctionProtoType())
  3854. return false;
  3855. VariadicCallType CallType;
  3856. if (!Proto || !Proto->isVariadic()) {
  3857. CallType = VariadicDoesNotApply;
  3858. } else if (Ty->isBlockPointerType()) {
  3859. CallType = VariadicBlock;
  3860. } else { // Ty->isFunctionPointerType()
  3861. CallType = VariadicFunction;
  3862. }
  3863. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  3864. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  3865. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  3866. TheCall->getCallee()->getSourceRange(), CallType);
  3867. return false;
  3868. }
  3869. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  3870. /// such as function pointers returned from functions.
  3871. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  3872. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  3873. TheCall->getCallee());
  3874. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  3875. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  3876. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  3877. TheCall->getCallee()->getSourceRange(), CallType);
  3878. return false;
  3879. }
  3880. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  3881. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  3882. return false;
  3883. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  3884. switch (Op) {
  3885. case AtomicExpr::AO__c11_atomic_init:
  3886. case AtomicExpr::AO__opencl_atomic_init:
  3887. llvm_unreachable("There is no ordering argument for an init");
  3888. case AtomicExpr::AO__c11_atomic_load:
  3889. case AtomicExpr::AO__opencl_atomic_load:
  3890. case AtomicExpr::AO__atomic_load_n:
  3891. case AtomicExpr::AO__atomic_load:
  3892. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  3893. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  3894. case AtomicExpr::AO__c11_atomic_store:
  3895. case AtomicExpr::AO__opencl_atomic_store:
  3896. case AtomicExpr::AO__atomic_store:
  3897. case AtomicExpr::AO__atomic_store_n:
  3898. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  3899. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  3900. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  3901. default:
  3902. return true;
  3903. }
  3904. }
  3905. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  3906. AtomicExpr::AtomicOp Op) {
  3907. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  3908. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  3909. // All the non-OpenCL operations take one of the following forms.
  3910. // The OpenCL operations take the __c11 forms with one extra argument for
  3911. // synchronization scope.
  3912. enum {
  3913. // C __c11_atomic_init(A *, C)
  3914. Init,
  3915. // C __c11_atomic_load(A *, int)
  3916. Load,
  3917. // void __atomic_load(A *, CP, int)
  3918. LoadCopy,
  3919. // void __atomic_store(A *, CP, int)
  3920. Copy,
  3921. // C __c11_atomic_add(A *, M, int)
  3922. Arithmetic,
  3923. // C __atomic_exchange_n(A *, CP, int)
  3924. Xchg,
  3925. // void __atomic_exchange(A *, C *, CP, int)
  3926. GNUXchg,
  3927. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  3928. C11CmpXchg,
  3929. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  3930. GNUCmpXchg
  3931. } Form = Init;
  3932. const unsigned NumForm = GNUCmpXchg + 1;
  3933. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  3934. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  3935. // where:
  3936. // C is an appropriate type,
  3937. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  3938. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  3939. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  3940. // the int parameters are for orderings.
  3941. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  3942. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  3943. "need to update code for modified forms");
  3944. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  3945. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  3946. AtomicExpr::AO__atomic_load,
  3947. "need to update code for modified C11 atomics");
  3948. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  3949. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  3950. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  3951. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  3952. IsOpenCL;
  3953. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  3954. Op == AtomicExpr::AO__atomic_store_n ||
  3955. Op == AtomicExpr::AO__atomic_exchange_n ||
  3956. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  3957. bool IsAddSub = false;
  3958. bool IsMinMax = false;
  3959. switch (Op) {
  3960. case AtomicExpr::AO__c11_atomic_init:
  3961. case AtomicExpr::AO__opencl_atomic_init:
  3962. Form = Init;
  3963. break;
  3964. case AtomicExpr::AO__c11_atomic_load:
  3965. case AtomicExpr::AO__opencl_atomic_load:
  3966. case AtomicExpr::AO__atomic_load_n:
  3967. Form = Load;
  3968. break;
  3969. case AtomicExpr::AO__atomic_load:
  3970. Form = LoadCopy;
  3971. break;
  3972. case AtomicExpr::AO__c11_atomic_store:
  3973. case AtomicExpr::AO__opencl_atomic_store:
  3974. case AtomicExpr::AO__atomic_store:
  3975. case AtomicExpr::AO__atomic_store_n:
  3976. Form = Copy;
  3977. break;
  3978. case AtomicExpr::AO__c11_atomic_fetch_add:
  3979. case AtomicExpr::AO__c11_atomic_fetch_sub:
  3980. case AtomicExpr::AO__opencl_atomic_fetch_add:
  3981. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  3982. case AtomicExpr::AO__opencl_atomic_fetch_min:
  3983. case AtomicExpr::AO__opencl_atomic_fetch_max:
  3984. case AtomicExpr::AO__atomic_fetch_add:
  3985. case AtomicExpr::AO__atomic_fetch_sub:
  3986. case AtomicExpr::AO__atomic_add_fetch:
  3987. case AtomicExpr::AO__atomic_sub_fetch:
  3988. IsAddSub = true;
  3989. LLVM_FALLTHROUGH;
  3990. case AtomicExpr::AO__c11_atomic_fetch_and:
  3991. case AtomicExpr::AO__c11_atomic_fetch_or:
  3992. case AtomicExpr::AO__c11_atomic_fetch_xor:
  3993. case AtomicExpr::AO__opencl_atomic_fetch_and:
  3994. case AtomicExpr::AO__opencl_atomic_fetch_or:
  3995. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  3996. case AtomicExpr::AO__atomic_fetch_and:
  3997. case AtomicExpr::AO__atomic_fetch_or:
  3998. case AtomicExpr::AO__atomic_fetch_xor:
  3999. case AtomicExpr::AO__atomic_fetch_nand:
  4000. case AtomicExpr::AO__atomic_and_fetch:
  4001. case AtomicExpr::AO__atomic_or_fetch:
  4002. case AtomicExpr::AO__atomic_xor_fetch:
  4003. case AtomicExpr::AO__atomic_nand_fetch:
  4004. Form = Arithmetic;
  4005. break;
  4006. case AtomicExpr::AO__atomic_fetch_min:
  4007. case AtomicExpr::AO__atomic_fetch_max:
  4008. IsMinMax = true;
  4009. Form = Arithmetic;
  4010. break;
  4011. case AtomicExpr::AO__c11_atomic_exchange:
  4012. case AtomicExpr::AO__opencl_atomic_exchange:
  4013. case AtomicExpr::AO__atomic_exchange_n:
  4014. Form = Xchg;
  4015. break;
  4016. case AtomicExpr::AO__atomic_exchange:
  4017. Form = GNUXchg;
  4018. break;
  4019. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  4020. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  4021. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  4022. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  4023. Form = C11CmpXchg;
  4024. break;
  4025. case AtomicExpr::AO__atomic_compare_exchange:
  4026. case AtomicExpr::AO__atomic_compare_exchange_n:
  4027. Form = GNUCmpXchg;
  4028. break;
  4029. }
  4030. unsigned AdjustedNumArgs = NumArgs[Form];
  4031. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  4032. ++AdjustedNumArgs;
  4033. // Check we have the right number of arguments.
  4034. if (TheCall->getNumArgs() < AdjustedNumArgs) {
  4035. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  4036. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4037. << TheCall->getCallee()->getSourceRange();
  4038. return ExprError();
  4039. } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
  4040. Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
  4041. diag::err_typecheck_call_too_many_args)
  4042. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4043. << TheCall->getCallee()->getSourceRange();
  4044. return ExprError();
  4045. }
  4046. // Inspect the first argument of the atomic operation.
  4047. Expr *Ptr = TheCall->getArg(0);
  4048. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  4049. if (ConvertedPtr.isInvalid())
  4050. return ExprError();
  4051. Ptr = ConvertedPtr.get();
  4052. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  4053. if (!pointerType) {
  4054. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  4055. << Ptr->getType() << Ptr->getSourceRange();
  4056. return ExprError();
  4057. }
  4058. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  4059. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  4060. QualType ValType = AtomTy; // 'C'
  4061. if (IsC11) {
  4062. if (!AtomTy->isAtomicType()) {
  4063. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  4064. << Ptr->getType() << Ptr->getSourceRange();
  4065. return ExprError();
  4066. }
  4067. if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
  4068. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  4069. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
  4070. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  4071. << Ptr->getSourceRange();
  4072. return ExprError();
  4073. }
  4074. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  4075. } else if (Form != Load && Form != LoadCopy) {
  4076. if (ValType.isConstQualified()) {
  4077. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
  4078. << Ptr->getType() << Ptr->getSourceRange();
  4079. return ExprError();
  4080. }
  4081. }
  4082. // For an arithmetic operation, the implied arithmetic must be well-formed.
  4083. if (Form == Arithmetic) {
  4084. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  4085. if (IsAddSub && !ValType->isIntegerType()
  4086. && !ValType->isPointerType()) {
  4087. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4088. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4089. return ExprError();
  4090. }
  4091. if (IsMinMax) {
  4092. const BuiltinType *BT = ValType->getAs<BuiltinType>();
  4093. if (!BT || (BT->getKind() != BuiltinType::Int &&
  4094. BT->getKind() != BuiltinType::UInt)) {
  4095. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
  4096. return ExprError();
  4097. }
  4098. }
  4099. if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
  4100. Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
  4101. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4102. return ExprError();
  4103. }
  4104. if (IsC11 && ValType->isPointerType() &&
  4105. RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
  4106. diag::err_incomplete_type)) {
  4107. return ExprError();
  4108. }
  4109. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  4110. // For __atomic_*_n operations, the value type must be a scalar integral or
  4111. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  4112. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4113. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4114. return ExprError();
  4115. }
  4116. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  4117. !AtomTy->isScalarType()) {
  4118. // For GNU atomics, require a trivially-copyable type. This is not part of
  4119. // the GNU atomics specification, but we enforce it for sanity.
  4120. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
  4121. << Ptr->getType() << Ptr->getSourceRange();
  4122. return ExprError();
  4123. }
  4124. switch (ValType.getObjCLifetime()) {
  4125. case Qualifiers::OCL_None:
  4126. case Qualifiers::OCL_ExplicitNone:
  4127. // okay
  4128. break;
  4129. case Qualifiers::OCL_Weak:
  4130. case Qualifiers::OCL_Strong:
  4131. case Qualifiers::OCL_Autoreleasing:
  4132. // FIXME: Can this happen? By this point, ValType should be known
  4133. // to be trivially copyable.
  4134. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  4135. << ValType << Ptr->getSourceRange();
  4136. return ExprError();
  4137. }
  4138. // All atomic operations have an overload which takes a pointer to a volatile
  4139. // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
  4140. // into the result or the other operands. Similarly atomic_load takes a
  4141. // pointer to a const 'A'.
  4142. ValType.removeLocalVolatile();
  4143. ValType.removeLocalConst();
  4144. QualType ResultType = ValType;
  4145. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  4146. Form == Init)
  4147. ResultType = Context.VoidTy;
  4148. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  4149. ResultType = Context.BoolTy;
  4150. // The type of a parameter passed 'by value'. In the GNU atomics, such
  4151. // arguments are actually passed as pointers.
  4152. QualType ByValType = ValType; // 'CP'
  4153. bool IsPassedByAddress = false;
  4154. if (!IsC11 && !IsN) {
  4155. ByValType = Ptr->getType();
  4156. IsPassedByAddress = true;
  4157. }
  4158. // The first argument's non-CV pointer type is used to deduce the type of
  4159. // subsequent arguments, except for:
  4160. // - weak flag (always converted to bool)
  4161. // - memory order (always converted to int)
  4162. // - scope (always converted to int)
  4163. for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
  4164. QualType Ty;
  4165. if (i < NumVals[Form] + 1) {
  4166. switch (i) {
  4167. case 0:
  4168. // The first argument is always a pointer. It has a fixed type.
  4169. // It is always dereferenced, a nullptr is undefined.
  4170. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
  4171. // Nothing else to do: we already know all we want about this pointer.
  4172. continue;
  4173. case 1:
  4174. // The second argument is the non-atomic operand. For arithmetic, this
  4175. // is always passed by value, and for a compare_exchange it is always
  4176. // passed by address. For the rest, GNU uses by-address and C11 uses
  4177. // by-value.
  4178. assert(Form != Load);
  4179. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  4180. Ty = ValType;
  4181. else if (Form == Copy || Form == Xchg) {
  4182. if (IsPassedByAddress)
  4183. // The value pointer is always dereferenced, a nullptr is undefined.
  4184. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
  4185. Ty = ByValType;
  4186. } else if (Form == Arithmetic)
  4187. Ty = Context.getPointerDiffType();
  4188. else {
  4189. Expr *ValArg = TheCall->getArg(i);
  4190. // The value pointer is always dereferenced, a nullptr is undefined.
  4191. CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
  4192. LangAS AS = LangAS::Default;
  4193. // Keep address space of non-atomic pointer type.
  4194. if (const PointerType *PtrTy =
  4195. ValArg->getType()->getAs<PointerType>()) {
  4196. AS = PtrTy->getPointeeType().getAddressSpace();
  4197. }
  4198. Ty = Context.getPointerType(
  4199. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  4200. }
  4201. break;
  4202. case 2:
  4203. // The third argument to compare_exchange / GNU exchange is the desired
  4204. // value, either by-value (for the C11 and *_n variant) or as a pointer.
  4205. if (IsPassedByAddress)
  4206. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
  4207. Ty = ByValType;
  4208. break;
  4209. case 3:
  4210. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  4211. Ty = Context.BoolTy;
  4212. break;
  4213. }
  4214. } else {
  4215. // The order(s) and scope are always converted to int.
  4216. Ty = Context.IntTy;
  4217. }
  4218. InitializedEntity Entity =
  4219. InitializedEntity::InitializeParameter(Context, Ty, false);
  4220. ExprResult Arg = TheCall->getArg(i);
  4221. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4222. if (Arg.isInvalid())
  4223. return true;
  4224. TheCall->setArg(i, Arg.get());
  4225. }
  4226. // Permute the arguments into a 'consistent' order.
  4227. SmallVector<Expr*, 5> SubExprs;
  4228. SubExprs.push_back(Ptr);
  4229. switch (Form) {
  4230. case Init:
  4231. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  4232. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4233. break;
  4234. case Load:
  4235. SubExprs.push_back(TheCall->getArg(1)); // Order
  4236. break;
  4237. case LoadCopy:
  4238. case Copy:
  4239. case Arithmetic:
  4240. case Xchg:
  4241. SubExprs.push_back(TheCall->getArg(2)); // Order
  4242. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4243. break;
  4244. case GNUXchg:
  4245. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  4246. SubExprs.push_back(TheCall->getArg(3)); // Order
  4247. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4248. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4249. break;
  4250. case C11CmpXchg:
  4251. SubExprs.push_back(TheCall->getArg(3)); // Order
  4252. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4253. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  4254. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4255. break;
  4256. case GNUCmpXchg:
  4257. SubExprs.push_back(TheCall->getArg(4)); // Order
  4258. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4259. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  4260. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4261. SubExprs.push_back(TheCall->getArg(3)); // Weak
  4262. break;
  4263. }
  4264. if (SubExprs.size() >= 2 && Form != Init) {
  4265. llvm::APSInt Result(32);
  4266. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  4267. !isValidOrderingForOp(Result.getSExtValue(), Op))
  4268. Diag(SubExprs[1]->getLocStart(),
  4269. diag::warn_atomic_op_has_invalid_memory_order)
  4270. << SubExprs[1]->getSourceRange();
  4271. }
  4272. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  4273. auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
  4274. llvm::APSInt Result(32);
  4275. if (Scope->isIntegerConstantExpr(Result, Context) &&
  4276. !ScopeModel->isValid(Result.getZExtValue())) {
  4277. Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
  4278. << Scope->getSourceRange();
  4279. }
  4280. SubExprs.push_back(Scope);
  4281. }
  4282. AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  4283. SubExprs, ResultType, Op,
  4284. TheCall->getRParenLoc());
  4285. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  4286. Op == AtomicExpr::AO__c11_atomic_store ||
  4287. Op == AtomicExpr::AO__opencl_atomic_load ||
  4288. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  4289. Context.AtomicUsesUnsupportedLibcall(AE))
  4290. Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
  4291. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  4292. Op == AtomicExpr::AO__opencl_atomic_load)
  4293. ? 0 : 1);
  4294. return AE;
  4295. }
  4296. /// checkBuiltinArgument - Given a call to a builtin function, perform
  4297. /// normal type-checking on the given argument, updating the call in
  4298. /// place. This is useful when a builtin function requires custom
  4299. /// type-checking for some of its arguments but not necessarily all of
  4300. /// them.
  4301. ///
  4302. /// Returns true on error.
  4303. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  4304. FunctionDecl *Fn = E->getDirectCallee();
  4305. assert(Fn && "builtin call without direct callee!");
  4306. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  4307. InitializedEntity Entity =
  4308. InitializedEntity::InitializeParameter(S.Context, Param);
  4309. ExprResult Arg = E->getArg(0);
  4310. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4311. if (Arg.isInvalid())
  4312. return true;
  4313. E->setArg(ArgIndex, Arg.get());
  4314. return false;
  4315. }
  4316. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  4317. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  4318. /// type of its first argument. The main ActOnCallExpr routines have already
  4319. /// promoted the types of arguments because all of these calls are prototyped as
  4320. /// void(...).
  4321. ///
  4322. /// This function goes through and does final semantic checking for these
  4323. /// builtins,
  4324. ExprResult
  4325. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  4326. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  4327. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4328. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4329. // Ensure that we have at least one argument to do type inference from.
  4330. if (TheCall->getNumArgs() < 1) {
  4331. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  4332. << 0 << 1 << TheCall->getNumArgs()
  4333. << TheCall->getCallee()->getSourceRange();
  4334. return ExprError();
  4335. }
  4336. // Inspect the first argument of the atomic builtin. This should always be
  4337. // a pointer type, whose element is an integral scalar or pointer type.
  4338. // Because it is a pointer type, we don't have to worry about any implicit
  4339. // casts here.
  4340. // FIXME: We don't allow floating point scalars as input.
  4341. Expr *FirstArg = TheCall->getArg(0);
  4342. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  4343. if (FirstArgResult.isInvalid())
  4344. return ExprError();
  4345. FirstArg = FirstArgResult.get();
  4346. TheCall->setArg(0, FirstArg);
  4347. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  4348. if (!pointerType) {
  4349. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  4350. << FirstArg->getType() << FirstArg->getSourceRange();
  4351. return ExprError();
  4352. }
  4353. QualType ValType = pointerType->getPointeeType();
  4354. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4355. !ValType->isBlockPointerType()) {
  4356. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  4357. << FirstArg->getType() << FirstArg->getSourceRange();
  4358. return ExprError();
  4359. }
  4360. if (ValType.isConstQualified()) {
  4361. Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
  4362. << FirstArg->getType() << FirstArg->getSourceRange();
  4363. return ExprError();
  4364. }
  4365. switch (ValType.getObjCLifetime()) {
  4366. case Qualifiers::OCL_None:
  4367. case Qualifiers::OCL_ExplicitNone:
  4368. // okay
  4369. break;
  4370. case Qualifiers::OCL_Weak:
  4371. case Qualifiers::OCL_Strong:
  4372. case Qualifiers::OCL_Autoreleasing:
  4373. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  4374. << ValType << FirstArg->getSourceRange();
  4375. return ExprError();
  4376. }
  4377. // Strip any qualifiers off ValType.
  4378. ValType = ValType.getUnqualifiedType();
  4379. // The majority of builtins return a value, but a few have special return
  4380. // types, so allow them to override appropriately below.
  4381. QualType ResultType = ValType;
  4382. // We need to figure out which concrete builtin this maps onto. For example,
  4383. // __sync_fetch_and_add with a 2 byte object turns into
  4384. // __sync_fetch_and_add_2.
  4385. #define BUILTIN_ROW(x) \
  4386. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  4387. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  4388. static const unsigned BuiltinIndices[][5] = {
  4389. BUILTIN_ROW(__sync_fetch_and_add),
  4390. BUILTIN_ROW(__sync_fetch_and_sub),
  4391. BUILTIN_ROW(__sync_fetch_and_or),
  4392. BUILTIN_ROW(__sync_fetch_and_and),
  4393. BUILTIN_ROW(__sync_fetch_and_xor),
  4394. BUILTIN_ROW(__sync_fetch_and_nand),
  4395. BUILTIN_ROW(__sync_add_and_fetch),
  4396. BUILTIN_ROW(__sync_sub_and_fetch),
  4397. BUILTIN_ROW(__sync_and_and_fetch),
  4398. BUILTIN_ROW(__sync_or_and_fetch),
  4399. BUILTIN_ROW(__sync_xor_and_fetch),
  4400. BUILTIN_ROW(__sync_nand_and_fetch),
  4401. BUILTIN_ROW(__sync_val_compare_and_swap),
  4402. BUILTIN_ROW(__sync_bool_compare_and_swap),
  4403. BUILTIN_ROW(__sync_lock_test_and_set),
  4404. BUILTIN_ROW(__sync_lock_release),
  4405. BUILTIN_ROW(__sync_swap)
  4406. };
  4407. #undef BUILTIN_ROW
  4408. // Determine the index of the size.
  4409. unsigned SizeIndex;
  4410. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  4411. case 1: SizeIndex = 0; break;
  4412. case 2: SizeIndex = 1; break;
  4413. case 4: SizeIndex = 2; break;
  4414. case 8: SizeIndex = 3; break;
  4415. case 16: SizeIndex = 4; break;
  4416. default:
  4417. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  4418. << FirstArg->getType() << FirstArg->getSourceRange();
  4419. return ExprError();
  4420. }
  4421. // Each of these builtins has one pointer argument, followed by some number of
  4422. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  4423. // that we ignore. Find out which row of BuiltinIndices to read from as well
  4424. // as the number of fixed args.
  4425. unsigned BuiltinID = FDecl->getBuiltinID();
  4426. unsigned BuiltinIndex, NumFixed = 1;
  4427. bool WarnAboutSemanticsChange = false;
  4428. switch (BuiltinID) {
  4429. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  4430. case Builtin::BI__sync_fetch_and_add:
  4431. case Builtin::BI__sync_fetch_and_add_1:
  4432. case Builtin::BI__sync_fetch_and_add_2:
  4433. case Builtin::BI__sync_fetch_and_add_4:
  4434. case Builtin::BI__sync_fetch_and_add_8:
  4435. case Builtin::BI__sync_fetch_and_add_16:
  4436. BuiltinIndex = 0;
  4437. break;
  4438. case Builtin::BI__sync_fetch_and_sub:
  4439. case Builtin::BI__sync_fetch_and_sub_1:
  4440. case Builtin::BI__sync_fetch_and_sub_2:
  4441. case Builtin::BI__sync_fetch_and_sub_4:
  4442. case Builtin::BI__sync_fetch_and_sub_8:
  4443. case Builtin::BI__sync_fetch_and_sub_16:
  4444. BuiltinIndex = 1;
  4445. break;
  4446. case Builtin::BI__sync_fetch_and_or:
  4447. case Builtin::BI__sync_fetch_and_or_1:
  4448. case Builtin::BI__sync_fetch_and_or_2:
  4449. case Builtin::BI__sync_fetch_and_or_4:
  4450. case Builtin::BI__sync_fetch_and_or_8:
  4451. case Builtin::BI__sync_fetch_and_or_16:
  4452. BuiltinIndex = 2;
  4453. break;
  4454. case Builtin::BI__sync_fetch_and_and:
  4455. case Builtin::BI__sync_fetch_and_and_1:
  4456. case Builtin::BI__sync_fetch_and_and_2:
  4457. case Builtin::BI__sync_fetch_and_and_4:
  4458. case Builtin::BI__sync_fetch_and_and_8:
  4459. case Builtin::BI__sync_fetch_and_and_16:
  4460. BuiltinIndex = 3;
  4461. break;
  4462. case Builtin::BI__sync_fetch_and_xor:
  4463. case Builtin::BI__sync_fetch_and_xor_1:
  4464. case Builtin::BI__sync_fetch_and_xor_2:
  4465. case Builtin::BI__sync_fetch_and_xor_4:
  4466. case Builtin::BI__sync_fetch_and_xor_8:
  4467. case Builtin::BI__sync_fetch_and_xor_16:
  4468. BuiltinIndex = 4;
  4469. break;
  4470. case Builtin::BI__sync_fetch_and_nand:
  4471. case Builtin::BI__sync_fetch_and_nand_1:
  4472. case Builtin::BI__sync_fetch_and_nand_2:
  4473. case Builtin::BI__sync_fetch_and_nand_4:
  4474. case Builtin::BI__sync_fetch_and_nand_8:
  4475. case Builtin::BI__sync_fetch_and_nand_16:
  4476. BuiltinIndex = 5;
  4477. WarnAboutSemanticsChange = true;
  4478. break;
  4479. case Builtin::BI__sync_add_and_fetch:
  4480. case Builtin::BI__sync_add_and_fetch_1:
  4481. case Builtin::BI__sync_add_and_fetch_2:
  4482. case Builtin::BI__sync_add_and_fetch_4:
  4483. case Builtin::BI__sync_add_and_fetch_8:
  4484. case Builtin::BI__sync_add_and_fetch_16:
  4485. BuiltinIndex = 6;
  4486. break;
  4487. case Builtin::BI__sync_sub_and_fetch:
  4488. case Builtin::BI__sync_sub_and_fetch_1:
  4489. case Builtin::BI__sync_sub_and_fetch_2:
  4490. case Builtin::BI__sync_sub_and_fetch_4:
  4491. case Builtin::BI__sync_sub_and_fetch_8:
  4492. case Builtin::BI__sync_sub_and_fetch_16:
  4493. BuiltinIndex = 7;
  4494. break;
  4495. case Builtin::BI__sync_and_and_fetch:
  4496. case Builtin::BI__sync_and_and_fetch_1:
  4497. case Builtin::BI__sync_and_and_fetch_2:
  4498. case Builtin::BI__sync_and_and_fetch_4:
  4499. case Builtin::BI__sync_and_and_fetch_8:
  4500. case Builtin::BI__sync_and_and_fetch_16:
  4501. BuiltinIndex = 8;
  4502. break;
  4503. case Builtin::BI__sync_or_and_fetch:
  4504. case Builtin::BI__sync_or_and_fetch_1:
  4505. case Builtin::BI__sync_or_and_fetch_2:
  4506. case Builtin::BI__sync_or_and_fetch_4:
  4507. case Builtin::BI__sync_or_and_fetch_8:
  4508. case Builtin::BI__sync_or_and_fetch_16:
  4509. BuiltinIndex = 9;
  4510. break;
  4511. case Builtin::BI__sync_xor_and_fetch:
  4512. case Builtin::BI__sync_xor_and_fetch_1:
  4513. case Builtin::BI__sync_xor_and_fetch_2:
  4514. case Builtin::BI__sync_xor_and_fetch_4:
  4515. case Builtin::BI__sync_xor_and_fetch_8:
  4516. case Builtin::BI__sync_xor_and_fetch_16:
  4517. BuiltinIndex = 10;
  4518. break;
  4519. case Builtin::BI__sync_nand_and_fetch:
  4520. case Builtin::BI__sync_nand_and_fetch_1:
  4521. case Builtin::BI__sync_nand_and_fetch_2:
  4522. case Builtin::BI__sync_nand_and_fetch_4:
  4523. case Builtin::BI__sync_nand_and_fetch_8:
  4524. case Builtin::BI__sync_nand_and_fetch_16:
  4525. BuiltinIndex = 11;
  4526. WarnAboutSemanticsChange = true;
  4527. break;
  4528. case Builtin::BI__sync_val_compare_and_swap:
  4529. case Builtin::BI__sync_val_compare_and_swap_1:
  4530. case Builtin::BI__sync_val_compare_and_swap_2:
  4531. case Builtin::BI__sync_val_compare_and_swap_4:
  4532. case Builtin::BI__sync_val_compare_and_swap_8:
  4533. case Builtin::BI__sync_val_compare_and_swap_16:
  4534. BuiltinIndex = 12;
  4535. NumFixed = 2;
  4536. break;
  4537. case Builtin::BI__sync_bool_compare_and_swap:
  4538. case Builtin::BI__sync_bool_compare_and_swap_1:
  4539. case Builtin::BI__sync_bool_compare_and_swap_2:
  4540. case Builtin::BI__sync_bool_compare_and_swap_4:
  4541. case Builtin::BI__sync_bool_compare_and_swap_8:
  4542. case Builtin::BI__sync_bool_compare_and_swap_16:
  4543. BuiltinIndex = 13;
  4544. NumFixed = 2;
  4545. ResultType = Context.BoolTy;
  4546. break;
  4547. case Builtin::BI__sync_lock_test_and_set:
  4548. case Builtin::BI__sync_lock_test_and_set_1:
  4549. case Builtin::BI__sync_lock_test_and_set_2:
  4550. case Builtin::BI__sync_lock_test_and_set_4:
  4551. case Builtin::BI__sync_lock_test_and_set_8:
  4552. case Builtin::BI__sync_lock_test_and_set_16:
  4553. BuiltinIndex = 14;
  4554. break;
  4555. case Builtin::BI__sync_lock_release:
  4556. case Builtin::BI__sync_lock_release_1:
  4557. case Builtin::BI__sync_lock_release_2:
  4558. case Builtin::BI__sync_lock_release_4:
  4559. case Builtin::BI__sync_lock_release_8:
  4560. case Builtin::BI__sync_lock_release_16:
  4561. BuiltinIndex = 15;
  4562. NumFixed = 0;
  4563. ResultType = Context.VoidTy;
  4564. break;
  4565. case Builtin::BI__sync_swap:
  4566. case Builtin::BI__sync_swap_1:
  4567. case Builtin::BI__sync_swap_2:
  4568. case Builtin::BI__sync_swap_4:
  4569. case Builtin::BI__sync_swap_8:
  4570. case Builtin::BI__sync_swap_16:
  4571. BuiltinIndex = 16;
  4572. break;
  4573. }
  4574. // Now that we know how many fixed arguments we expect, first check that we
  4575. // have at least that many.
  4576. if (TheCall->getNumArgs() < 1+NumFixed) {
  4577. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  4578. << 0 << 1+NumFixed << TheCall->getNumArgs()
  4579. << TheCall->getCallee()->getSourceRange();
  4580. return ExprError();
  4581. }
  4582. if (WarnAboutSemanticsChange) {
  4583. Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
  4584. << TheCall->getCallee()->getSourceRange();
  4585. }
  4586. // Get the decl for the concrete builtin from this, we can tell what the
  4587. // concrete integer type we should convert to is.
  4588. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  4589. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  4590. FunctionDecl *NewBuiltinDecl;
  4591. if (NewBuiltinID == BuiltinID)
  4592. NewBuiltinDecl = FDecl;
  4593. else {
  4594. // Perform builtin lookup to avoid redeclaring it.
  4595. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  4596. LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
  4597. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  4598. assert(Res.getFoundDecl());
  4599. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  4600. if (!NewBuiltinDecl)
  4601. return ExprError();
  4602. }
  4603. // The first argument --- the pointer --- has a fixed type; we
  4604. // deduce the types of the rest of the arguments accordingly. Walk
  4605. // the remaining arguments, converting them to the deduced value type.
  4606. for (unsigned i = 0; i != NumFixed; ++i) {
  4607. ExprResult Arg = TheCall->getArg(i+1);
  4608. // GCC does an implicit conversion to the pointer or integer ValType. This
  4609. // can fail in some cases (1i -> int**), check for this error case now.
  4610. // Initialize the argument.
  4611. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  4612. ValType, /*consume*/ false);
  4613. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4614. if (Arg.isInvalid())
  4615. return ExprError();
  4616. // Okay, we have something that *can* be converted to the right type. Check
  4617. // to see if there is a potentially weird extension going on here. This can
  4618. // happen when you do an atomic operation on something like an char* and
  4619. // pass in 42. The 42 gets converted to char. This is even more strange
  4620. // for things like 45.123 -> char, etc.
  4621. // FIXME: Do this check.
  4622. TheCall->setArg(i+1, Arg.get());
  4623. }
  4624. ASTContext& Context = this->getASTContext();
  4625. // Create a new DeclRefExpr to refer to the new decl.
  4626. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  4627. Context,
  4628. DRE->getQualifierLoc(),
  4629. SourceLocation(),
  4630. NewBuiltinDecl,
  4631. /*enclosing*/ false,
  4632. DRE->getLocation(),
  4633. Context.BuiltinFnTy,
  4634. DRE->getValueKind());
  4635. // Set the callee in the CallExpr.
  4636. // FIXME: This loses syntactic information.
  4637. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  4638. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  4639. CK_BuiltinFnToFnPtr);
  4640. TheCall->setCallee(PromotedCall.get());
  4641. // Change the result type of the call to match the original value type. This
  4642. // is arbitrary, but the codegen for these builtins ins design to handle it
  4643. // gracefully.
  4644. TheCall->setType(ResultType);
  4645. return TheCallResult;
  4646. }
  4647. /// SemaBuiltinNontemporalOverloaded - We have a call to
  4648. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  4649. /// overloaded function based on the pointer type of its last argument.
  4650. ///
  4651. /// This function goes through and does final semantic checking for these
  4652. /// builtins.
  4653. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  4654. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  4655. DeclRefExpr *DRE =
  4656. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4657. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4658. unsigned BuiltinID = FDecl->getBuiltinID();
  4659. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  4660. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  4661. "Unexpected nontemporal load/store builtin!");
  4662. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  4663. unsigned numArgs = isStore ? 2 : 1;
  4664. // Ensure that we have the proper number of arguments.
  4665. if (checkArgCount(*this, TheCall, numArgs))
  4666. return ExprError();
  4667. // Inspect the last argument of the nontemporal builtin. This should always
  4668. // be a pointer type, from which we imply the type of the memory access.
  4669. // Because it is a pointer type, we don't have to worry about any implicit
  4670. // casts here.
  4671. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  4672. ExprResult PointerArgResult =
  4673. DefaultFunctionArrayLvalueConversion(PointerArg);
  4674. if (PointerArgResult.isInvalid())
  4675. return ExprError();
  4676. PointerArg = PointerArgResult.get();
  4677. TheCall->setArg(numArgs - 1, PointerArg);
  4678. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  4679. if (!pointerType) {
  4680. Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
  4681. << PointerArg->getType() << PointerArg->getSourceRange();
  4682. return ExprError();
  4683. }
  4684. QualType ValType = pointerType->getPointeeType();
  4685. // Strip any qualifiers off ValType.
  4686. ValType = ValType.getUnqualifiedType();
  4687. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4688. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  4689. !ValType->isVectorType()) {
  4690. Diag(DRE->getLocStart(),
  4691. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  4692. << PointerArg->getType() << PointerArg->getSourceRange();
  4693. return ExprError();
  4694. }
  4695. if (!isStore) {
  4696. TheCall->setType(ValType);
  4697. return TheCallResult;
  4698. }
  4699. ExprResult ValArg = TheCall->getArg(0);
  4700. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4701. Context, ValType, /*consume*/ false);
  4702. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  4703. if (ValArg.isInvalid())
  4704. return ExprError();
  4705. TheCall->setArg(0, ValArg.get());
  4706. TheCall->setType(Context.VoidTy);
  4707. return TheCallResult;
  4708. }
  4709. /// CheckObjCString - Checks that the argument to the builtin
  4710. /// CFString constructor is correct
  4711. /// Note: It might also make sense to do the UTF-16 conversion here (would
  4712. /// simplify the backend).
  4713. bool Sema::CheckObjCString(Expr *Arg) {
  4714. Arg = Arg->IgnoreParenCasts();
  4715. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  4716. if (!Literal || !Literal->isAscii()) {
  4717. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  4718. << Arg->getSourceRange();
  4719. return true;
  4720. }
  4721. if (Literal->containsNonAsciiOrNull()) {
  4722. StringRef String = Literal->getString();
  4723. unsigned NumBytes = String.size();
  4724. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  4725. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  4726. llvm::UTF16 *ToPtr = &ToBuf[0];
  4727. llvm::ConversionResult Result =
  4728. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  4729. ToPtr + NumBytes, llvm::strictConversion);
  4730. // Check for conversion failure.
  4731. if (Result != llvm::conversionOK)
  4732. Diag(Arg->getLocStart(),
  4733. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  4734. }
  4735. return false;
  4736. }
  4737. /// CheckObjCString - Checks that the format string argument to the os_log()
  4738. /// and os_trace() functions is correct, and converts it to const char *.
  4739. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  4740. Arg = Arg->IgnoreParenCasts();
  4741. auto *Literal = dyn_cast<StringLiteral>(Arg);
  4742. if (!Literal) {
  4743. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  4744. Literal = ObjcLiteral->getString();
  4745. }
  4746. }
  4747. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  4748. return ExprError(
  4749. Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
  4750. << Arg->getSourceRange());
  4751. }
  4752. ExprResult Result(Literal);
  4753. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  4754. InitializedEntity Entity =
  4755. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  4756. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  4757. return Result;
  4758. }
  4759. /// Check that the user is calling the appropriate va_start builtin for the
  4760. /// target and calling convention.
  4761. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  4762. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  4763. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  4764. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  4765. bool IsWindows = TT.isOSWindows();
  4766. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  4767. if (IsX64 || IsAArch64) {
  4768. CallingConv CC = CC_C;
  4769. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  4770. CC = FD->getType()->getAs<FunctionType>()->getCallConv();
  4771. if (IsMSVAStart) {
  4772. // Don't allow this in System V ABI functions.
  4773. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  4774. return S.Diag(Fn->getLocStart(),
  4775. diag::err_ms_va_start_used_in_sysv_function);
  4776. } else {
  4777. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  4778. // On x64 Windows, don't allow this in System V ABI functions.
  4779. // (Yes, that means there's no corresponding way to support variadic
  4780. // System V ABI functions on Windows.)
  4781. if ((IsWindows && CC == CC_X86_64SysV) ||
  4782. (!IsWindows && CC == CC_Win64))
  4783. return S.Diag(Fn->getLocStart(),
  4784. diag::err_va_start_used_in_wrong_abi_function)
  4785. << !IsWindows;
  4786. }
  4787. return false;
  4788. }
  4789. if (IsMSVAStart)
  4790. return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
  4791. return false;
  4792. }
  4793. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  4794. ParmVarDecl **LastParam = nullptr) {
  4795. // Determine whether the current function, block, or obj-c method is variadic
  4796. // and get its parameter list.
  4797. bool IsVariadic = false;
  4798. ArrayRef<ParmVarDecl *> Params;
  4799. DeclContext *Caller = S.CurContext;
  4800. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  4801. IsVariadic = Block->isVariadic();
  4802. Params = Block->parameters();
  4803. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  4804. IsVariadic = FD->isVariadic();
  4805. Params = FD->parameters();
  4806. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  4807. IsVariadic = MD->isVariadic();
  4808. // FIXME: This isn't correct for methods (results in bogus warning).
  4809. Params = MD->parameters();
  4810. } else if (isa<CapturedDecl>(Caller)) {
  4811. // We don't support va_start in a CapturedDecl.
  4812. S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
  4813. return true;
  4814. } else {
  4815. // This must be some other declcontext that parses exprs.
  4816. S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
  4817. return true;
  4818. }
  4819. if (!IsVariadic) {
  4820. S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
  4821. return true;
  4822. }
  4823. if (LastParam)
  4824. *LastParam = Params.empty() ? nullptr : Params.back();
  4825. return false;
  4826. }
  4827. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  4828. /// for validity. Emit an error and return true on failure; return false
  4829. /// on success.
  4830. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  4831. Expr *Fn = TheCall->getCallee();
  4832. if (checkVAStartABI(*this, BuiltinID, Fn))
  4833. return true;
  4834. if (TheCall->getNumArgs() > 2) {
  4835. Diag(TheCall->getArg(2)->getLocStart(),
  4836. diag::err_typecheck_call_too_many_args)
  4837. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  4838. << Fn->getSourceRange()
  4839. << SourceRange(TheCall->getArg(2)->getLocStart(),
  4840. (*(TheCall->arg_end()-1))->getLocEnd());
  4841. return true;
  4842. }
  4843. if (TheCall->getNumArgs() < 2) {
  4844. return Diag(TheCall->getLocEnd(),
  4845. diag::err_typecheck_call_too_few_args_at_least)
  4846. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  4847. }
  4848. // Type-check the first argument normally.
  4849. if (checkBuiltinArgument(*this, TheCall, 0))
  4850. return true;
  4851. // Check that the current function is variadic, and get its last parameter.
  4852. ParmVarDecl *LastParam;
  4853. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  4854. return true;
  4855. // Verify that the second argument to the builtin is the last argument of the
  4856. // current function or method.
  4857. bool SecondArgIsLastNamedArgument = false;
  4858. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  4859. // These are valid if SecondArgIsLastNamedArgument is false after the next
  4860. // block.
  4861. QualType Type;
  4862. SourceLocation ParamLoc;
  4863. bool IsCRegister = false;
  4864. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  4865. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  4866. SecondArgIsLastNamedArgument = PV == LastParam;
  4867. Type = PV->getType();
  4868. ParamLoc = PV->getLocation();
  4869. IsCRegister =
  4870. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  4871. }
  4872. }
  4873. if (!SecondArgIsLastNamedArgument)
  4874. Diag(TheCall->getArg(1)->getLocStart(),
  4875. diag::warn_second_arg_of_va_start_not_last_named_param);
  4876. else if (IsCRegister || Type->isReferenceType() ||
  4877. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  4878. // Promotable integers are UB, but enumerations need a bit of
  4879. // extra checking to see what their promotable type actually is.
  4880. if (!Type->isPromotableIntegerType())
  4881. return false;
  4882. if (!Type->isEnumeralType())
  4883. return true;
  4884. const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
  4885. return !(ED &&
  4886. Context.typesAreCompatible(ED->getPromotionType(), Type));
  4887. }()) {
  4888. unsigned Reason = 0;
  4889. if (Type->isReferenceType()) Reason = 1;
  4890. else if (IsCRegister) Reason = 2;
  4891. Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
  4892. Diag(ParamLoc, diag::note_parameter_type) << Type;
  4893. }
  4894. TheCall->setType(Context.VoidTy);
  4895. return false;
  4896. }
  4897. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  4898. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  4899. // const char *named_addr);
  4900. Expr *Func = Call->getCallee();
  4901. if (Call->getNumArgs() < 3)
  4902. return Diag(Call->getLocEnd(),
  4903. diag::err_typecheck_call_too_few_args_at_least)
  4904. << 0 /*function call*/ << 3 << Call->getNumArgs();
  4905. // Type-check the first argument normally.
  4906. if (checkBuiltinArgument(*this, Call, 0))
  4907. return true;
  4908. // Check that the current function is variadic.
  4909. if (checkVAStartIsInVariadicFunction(*this, Func))
  4910. return true;
  4911. // __va_start on Windows does not validate the parameter qualifiers
  4912. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  4913. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  4914. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  4915. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  4916. const QualType &ConstCharPtrTy =
  4917. Context.getPointerType(Context.CharTy.withConst());
  4918. if (!Arg1Ty->isPointerType() ||
  4919. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  4920. Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
  4921. << Arg1->getType() << ConstCharPtrTy
  4922. << 1 /* different class */
  4923. << 0 /* qualifier difference */
  4924. << 3 /* parameter mismatch */
  4925. << 2 << Arg1->getType() << ConstCharPtrTy;
  4926. const QualType SizeTy = Context.getSizeType();
  4927. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  4928. Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
  4929. << Arg2->getType() << SizeTy
  4930. << 1 /* different class */
  4931. << 0 /* qualifier difference */
  4932. << 3 /* parameter mismatch */
  4933. << 3 << Arg2->getType() << SizeTy;
  4934. return false;
  4935. }
  4936. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  4937. /// friends. This is declared to take (...), so we have to check everything.
  4938. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  4939. if (TheCall->getNumArgs() < 2)
  4940. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  4941. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  4942. if (TheCall->getNumArgs() > 2)
  4943. return Diag(TheCall->getArg(2)->getLocStart(),
  4944. diag::err_typecheck_call_too_many_args)
  4945. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  4946. << SourceRange(TheCall->getArg(2)->getLocStart(),
  4947. (*(TheCall->arg_end()-1))->getLocEnd());
  4948. ExprResult OrigArg0 = TheCall->getArg(0);
  4949. ExprResult OrigArg1 = TheCall->getArg(1);
  4950. // Do standard promotions between the two arguments, returning their common
  4951. // type.
  4952. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  4953. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  4954. return true;
  4955. // Make sure any conversions are pushed back into the call; this is
  4956. // type safe since unordered compare builtins are declared as "_Bool
  4957. // foo(...)".
  4958. TheCall->setArg(0, OrigArg0.get());
  4959. TheCall->setArg(1, OrigArg1.get());
  4960. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  4961. return false;
  4962. // If the common type isn't a real floating type, then the arguments were
  4963. // invalid for this operation.
  4964. if (Res.isNull() || !Res->isRealFloatingType())
  4965. return Diag(OrigArg0.get()->getLocStart(),
  4966. diag::err_typecheck_call_invalid_ordered_compare)
  4967. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  4968. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  4969. return false;
  4970. }
  4971. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  4972. /// __builtin_isnan and friends. This is declared to take (...), so we have
  4973. /// to check everything. We expect the last argument to be a floating point
  4974. /// value.
  4975. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  4976. if (TheCall->getNumArgs() < NumArgs)
  4977. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  4978. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  4979. if (TheCall->getNumArgs() > NumArgs)
  4980. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  4981. diag::err_typecheck_call_too_many_args)
  4982. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  4983. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  4984. (*(TheCall->arg_end()-1))->getLocEnd());
  4985. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  4986. if (OrigArg->isTypeDependent())
  4987. return false;
  4988. // This operation requires a non-_Complex floating-point number.
  4989. if (!OrigArg->getType()->isRealFloatingType())
  4990. return Diag(OrigArg->getLocStart(),
  4991. diag::err_typecheck_call_invalid_unary_fp)
  4992. << OrigArg->getType() << OrigArg->getSourceRange();
  4993. // If this is an implicit conversion from float -> float, double, or
  4994. // long double, remove it.
  4995. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  4996. // Only remove standard FloatCasts, leaving other casts inplace
  4997. if (Cast->getCastKind() == CK_FloatingCast) {
  4998. Expr *CastArg = Cast->getSubExpr();
  4999. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  5000. assert(
  5001. (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  5002. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
  5003. Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
  5004. "promotion from float to either float, double, or long double is "
  5005. "the only expected cast here");
  5006. Cast->setSubExpr(nullptr);
  5007. TheCall->setArg(NumArgs-1, CastArg);
  5008. }
  5009. }
  5010. }
  5011. return false;
  5012. }
  5013. // Customized Sema Checking for VSX builtins that have the following signature:
  5014. // vector [...] builtinName(vector [...], vector [...], const int);
  5015. // Which takes the same type of vectors (any legal vector type) for the first
  5016. // two arguments and takes compile time constant for the third argument.
  5017. // Example builtins are :
  5018. // vector double vec_xxpermdi(vector double, vector double, int);
  5019. // vector short vec_xxsldwi(vector short, vector short, int);
  5020. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  5021. unsigned ExpectedNumArgs = 3;
  5022. if (TheCall->getNumArgs() < ExpectedNumArgs)
  5023. return Diag(TheCall->getLocEnd(),
  5024. diag::err_typecheck_call_too_few_args_at_least)
  5025. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5026. << TheCall->getSourceRange();
  5027. if (TheCall->getNumArgs() > ExpectedNumArgs)
  5028. return Diag(TheCall->getLocEnd(),
  5029. diag::err_typecheck_call_too_many_args_at_most)
  5030. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5031. << TheCall->getSourceRange();
  5032. // Check the third argument is a compile time constant
  5033. llvm::APSInt Value;
  5034. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  5035. return Diag(TheCall->getLocStart(),
  5036. diag::err_vsx_builtin_nonconstant_argument)
  5037. << 3 /* argument index */ << TheCall->getDirectCallee()
  5038. << SourceRange(TheCall->getArg(2)->getLocStart(),
  5039. TheCall->getArg(2)->getLocEnd());
  5040. QualType Arg1Ty = TheCall->getArg(0)->getType();
  5041. QualType Arg2Ty = TheCall->getArg(1)->getType();
  5042. // Check the type of argument 1 and argument 2 are vectors.
  5043. SourceLocation BuiltinLoc = TheCall->getLocStart();
  5044. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  5045. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  5046. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  5047. << TheCall->getDirectCallee()
  5048. << SourceRange(TheCall->getArg(0)->getLocStart(),
  5049. TheCall->getArg(1)->getLocEnd());
  5050. }
  5051. // Check the first two arguments are the same type.
  5052. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  5053. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  5054. << TheCall->getDirectCallee()
  5055. << SourceRange(TheCall->getArg(0)->getLocStart(),
  5056. TheCall->getArg(1)->getLocEnd());
  5057. }
  5058. // When default clang type checking is turned off and the customized type
  5059. // checking is used, the returning type of the function must be explicitly
  5060. // set. Otherwise it is _Bool by default.
  5061. TheCall->setType(Arg1Ty);
  5062. return false;
  5063. }
  5064. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  5065. // This is declared to take (...), so we have to check everything.
  5066. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  5067. if (TheCall->getNumArgs() < 2)
  5068. return ExprError(Diag(TheCall->getLocEnd(),
  5069. diag::err_typecheck_call_too_few_args_at_least)
  5070. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5071. << TheCall->getSourceRange());
  5072. // Determine which of the following types of shufflevector we're checking:
  5073. // 1) unary, vector mask: (lhs, mask)
  5074. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  5075. QualType resType = TheCall->getArg(0)->getType();
  5076. unsigned numElements = 0;
  5077. if (!TheCall->getArg(0)->isTypeDependent() &&
  5078. !TheCall->getArg(1)->isTypeDependent()) {
  5079. QualType LHSType = TheCall->getArg(0)->getType();
  5080. QualType RHSType = TheCall->getArg(1)->getType();
  5081. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  5082. return ExprError(Diag(TheCall->getLocStart(),
  5083. diag::err_vec_builtin_non_vector)
  5084. << TheCall->getDirectCallee()
  5085. << SourceRange(TheCall->getArg(0)->getLocStart(),
  5086. TheCall->getArg(1)->getLocEnd()));
  5087. numElements = LHSType->getAs<VectorType>()->getNumElements();
  5088. unsigned numResElements = TheCall->getNumArgs() - 2;
  5089. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  5090. // with mask. If so, verify that RHS is an integer vector type with the
  5091. // same number of elts as lhs.
  5092. if (TheCall->getNumArgs() == 2) {
  5093. if (!RHSType->hasIntegerRepresentation() ||
  5094. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  5095. return ExprError(Diag(TheCall->getLocStart(),
  5096. diag::err_vec_builtin_incompatible_vector)
  5097. << TheCall->getDirectCallee()
  5098. << SourceRange(TheCall->getArg(1)->getLocStart(),
  5099. TheCall->getArg(1)->getLocEnd()));
  5100. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  5101. return ExprError(Diag(TheCall->getLocStart(),
  5102. diag::err_vec_builtin_incompatible_vector)
  5103. << TheCall->getDirectCallee()
  5104. << SourceRange(TheCall->getArg(0)->getLocStart(),
  5105. TheCall->getArg(1)->getLocEnd()));
  5106. } else if (numElements != numResElements) {
  5107. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  5108. resType = Context.getVectorType(eltType, numResElements,
  5109. VectorType::GenericVector);
  5110. }
  5111. }
  5112. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  5113. if (TheCall->getArg(i)->isTypeDependent() ||
  5114. TheCall->getArg(i)->isValueDependent())
  5115. continue;
  5116. llvm::APSInt Result(32);
  5117. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  5118. return ExprError(Diag(TheCall->getLocStart(),
  5119. diag::err_shufflevector_nonconstant_argument)
  5120. << TheCall->getArg(i)->getSourceRange());
  5121. // Allow -1 which will be translated to undef in the IR.
  5122. if (Result.isSigned() && Result.isAllOnesValue())
  5123. continue;
  5124. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  5125. return ExprError(Diag(TheCall->getLocStart(),
  5126. diag::err_shufflevector_argument_too_large)
  5127. << TheCall->getArg(i)->getSourceRange());
  5128. }
  5129. SmallVector<Expr*, 32> exprs;
  5130. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  5131. exprs.push_back(TheCall->getArg(i));
  5132. TheCall->setArg(i, nullptr);
  5133. }
  5134. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  5135. TheCall->getCallee()->getLocStart(),
  5136. TheCall->getRParenLoc());
  5137. }
  5138. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  5139. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  5140. SourceLocation BuiltinLoc,
  5141. SourceLocation RParenLoc) {
  5142. ExprValueKind VK = VK_RValue;
  5143. ExprObjectKind OK = OK_Ordinary;
  5144. QualType DstTy = TInfo->getType();
  5145. QualType SrcTy = E->getType();
  5146. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  5147. return ExprError(Diag(BuiltinLoc,
  5148. diag::err_convertvector_non_vector)
  5149. << E->getSourceRange());
  5150. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  5151. return ExprError(Diag(BuiltinLoc,
  5152. diag::err_convertvector_non_vector_type));
  5153. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  5154. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  5155. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  5156. if (SrcElts != DstElts)
  5157. return ExprError(Diag(BuiltinLoc,
  5158. diag::err_convertvector_incompatible_vector)
  5159. << E->getSourceRange());
  5160. }
  5161. return new (Context)
  5162. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5163. }
  5164. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  5165. // This is declared to take (const void*, ...) and can take two
  5166. // optional constant int args.
  5167. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  5168. unsigned NumArgs = TheCall->getNumArgs();
  5169. if (NumArgs > 3)
  5170. return Diag(TheCall->getLocEnd(),
  5171. diag::err_typecheck_call_too_many_args_at_most)
  5172. << 0 /*function call*/ << 3 << NumArgs
  5173. << TheCall->getSourceRange();
  5174. // Argument 0 is checked for us and the remaining arguments must be
  5175. // constant integers.
  5176. for (unsigned i = 1; i != NumArgs; ++i)
  5177. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  5178. return true;
  5179. return false;
  5180. }
  5181. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  5182. // __assume does not evaluate its arguments, and should warn if its argument
  5183. // has side effects.
  5184. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  5185. Expr *Arg = TheCall->getArg(0);
  5186. if (Arg->isInstantiationDependent()) return false;
  5187. if (Arg->HasSideEffects(Context))
  5188. Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
  5189. << Arg->getSourceRange()
  5190. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  5191. return false;
  5192. }
  5193. /// Handle __builtin_alloca_with_align. This is declared
  5194. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  5195. /// than 8.
  5196. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  5197. // The alignment must be a constant integer.
  5198. Expr *Arg = TheCall->getArg(1);
  5199. // We can't check the value of a dependent argument.
  5200. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5201. if (const auto *UE =
  5202. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  5203. if (UE->getKind() == UETT_AlignOf)
  5204. Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
  5205. << Arg->getSourceRange();
  5206. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  5207. if (!Result.isPowerOf2())
  5208. return Diag(TheCall->getLocStart(),
  5209. diag::err_alignment_not_power_of_two)
  5210. << Arg->getSourceRange();
  5211. if (Result < Context.getCharWidth())
  5212. return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
  5213. << (unsigned)Context.getCharWidth()
  5214. << Arg->getSourceRange();
  5215. if (Result > std::numeric_limits<int32_t>::max())
  5216. return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
  5217. << std::numeric_limits<int32_t>::max()
  5218. << Arg->getSourceRange();
  5219. }
  5220. return false;
  5221. }
  5222. /// Handle __builtin_assume_aligned. This is declared
  5223. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  5224. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  5225. unsigned NumArgs = TheCall->getNumArgs();
  5226. if (NumArgs > 3)
  5227. return Diag(TheCall->getLocEnd(),
  5228. diag::err_typecheck_call_too_many_args_at_most)
  5229. << 0 /*function call*/ << 3 << NumArgs
  5230. << TheCall->getSourceRange();
  5231. // The alignment must be a constant integer.
  5232. Expr *Arg = TheCall->getArg(1);
  5233. // We can't check the value of a dependent argument.
  5234. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5235. llvm::APSInt Result;
  5236. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5237. return true;
  5238. if (!Result.isPowerOf2())
  5239. return Diag(TheCall->getLocStart(),
  5240. diag::err_alignment_not_power_of_two)
  5241. << Arg->getSourceRange();
  5242. }
  5243. if (NumArgs > 2) {
  5244. ExprResult Arg(TheCall->getArg(2));
  5245. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  5246. Context.getSizeType(), false);
  5247. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5248. if (Arg.isInvalid()) return true;
  5249. TheCall->setArg(2, Arg.get());
  5250. }
  5251. return false;
  5252. }
  5253. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  5254. unsigned BuiltinID =
  5255. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  5256. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  5257. unsigned NumArgs = TheCall->getNumArgs();
  5258. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  5259. if (NumArgs < NumRequiredArgs) {
  5260. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  5261. << 0 /* function call */ << NumRequiredArgs << NumArgs
  5262. << TheCall->getSourceRange();
  5263. }
  5264. if (NumArgs >= NumRequiredArgs + 0x100) {
  5265. return Diag(TheCall->getLocEnd(),
  5266. diag::err_typecheck_call_too_many_args_at_most)
  5267. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  5268. << TheCall->getSourceRange();
  5269. }
  5270. unsigned i = 0;
  5271. // For formatting call, check buffer arg.
  5272. if (!IsSizeCall) {
  5273. ExprResult Arg(TheCall->getArg(i));
  5274. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5275. Context, Context.VoidPtrTy, false);
  5276. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5277. if (Arg.isInvalid())
  5278. return true;
  5279. TheCall->setArg(i, Arg.get());
  5280. i++;
  5281. }
  5282. // Check string literal arg.
  5283. unsigned FormatIdx = i;
  5284. {
  5285. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  5286. if (Arg.isInvalid())
  5287. return true;
  5288. TheCall->setArg(i, Arg.get());
  5289. i++;
  5290. }
  5291. // Make sure variadic args are scalar.
  5292. unsigned FirstDataArg = i;
  5293. while (i < NumArgs) {
  5294. ExprResult Arg = DefaultVariadicArgumentPromotion(
  5295. TheCall->getArg(i), VariadicFunction, nullptr);
  5296. if (Arg.isInvalid())
  5297. return true;
  5298. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  5299. if (ArgSize.getQuantity() >= 0x100) {
  5300. return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
  5301. << i << (int)ArgSize.getQuantity() << 0xff
  5302. << TheCall->getSourceRange();
  5303. }
  5304. TheCall->setArg(i, Arg.get());
  5305. i++;
  5306. }
  5307. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  5308. // call to avoid duplicate diagnostics.
  5309. if (!IsSizeCall) {
  5310. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  5311. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  5312. bool Success = CheckFormatArguments(
  5313. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  5314. VariadicFunction, TheCall->getLocStart(), SourceRange(),
  5315. CheckedVarArgs);
  5316. if (!Success)
  5317. return true;
  5318. }
  5319. if (IsSizeCall) {
  5320. TheCall->setType(Context.getSizeType());
  5321. } else {
  5322. TheCall->setType(Context.VoidPtrTy);
  5323. }
  5324. return false;
  5325. }
  5326. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  5327. /// TheCall is a constant expression.
  5328. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  5329. llvm::APSInt &Result) {
  5330. Expr *Arg = TheCall->getArg(ArgNum);
  5331. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5332. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  5333. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  5334. if (!Arg->isIntegerConstantExpr(Result, Context))
  5335. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  5336. << FDecl->getDeclName() << Arg->getSourceRange();
  5337. return false;
  5338. }
  5339. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  5340. /// TheCall is a constant expression in the range [Low, High].
  5341. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  5342. int Low, int High, bool RangeIsError) {
  5343. llvm::APSInt Result;
  5344. // We can't check the value of a dependent argument.
  5345. Expr *Arg = TheCall->getArg(ArgNum);
  5346. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5347. return false;
  5348. // Check constant-ness first.
  5349. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5350. return true;
  5351. if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
  5352. if (RangeIsError)
  5353. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  5354. << Result.toString(10) << Low << High << Arg->getSourceRange();
  5355. else
  5356. // Defer the warning until we know if the code will be emitted so that
  5357. // dead code can ignore this.
  5358. DiagRuntimeBehavior(TheCall->getLocStart(), TheCall,
  5359. PDiag(diag::warn_argument_invalid_range)
  5360. << Result.toString(10) << Low << High
  5361. << Arg->getSourceRange());
  5362. }
  5363. return false;
  5364. }
  5365. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  5366. /// TheCall is a constant expression is a multiple of Num..
  5367. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  5368. unsigned Num) {
  5369. llvm::APSInt Result;
  5370. // We can't check the value of a dependent argument.
  5371. Expr *Arg = TheCall->getArg(ArgNum);
  5372. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5373. return false;
  5374. // Check constant-ness first.
  5375. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5376. return true;
  5377. if (Result.getSExtValue() % Num != 0)
  5378. return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
  5379. << Num << Arg->getSourceRange();
  5380. return false;
  5381. }
  5382. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  5383. /// TheCall is an ARM/AArch64 special register string literal.
  5384. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  5385. int ArgNum, unsigned ExpectedFieldNum,
  5386. bool AllowName) {
  5387. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  5388. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  5389. BuiltinID == ARM::BI__builtin_arm_rsr ||
  5390. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  5391. BuiltinID == ARM::BI__builtin_arm_wsr ||
  5392. BuiltinID == ARM::BI__builtin_arm_wsrp;
  5393. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  5394. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  5395. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  5396. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  5397. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  5398. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  5399. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  5400. // We can't check the value of a dependent argument.
  5401. Expr *Arg = TheCall->getArg(ArgNum);
  5402. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5403. return false;
  5404. // Check if the argument is a string literal.
  5405. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  5406. return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  5407. << Arg->getSourceRange();
  5408. // Check the type of special register given.
  5409. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  5410. SmallVector<StringRef, 6> Fields;
  5411. Reg.split(Fields, ":");
  5412. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  5413. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  5414. << Arg->getSourceRange();
  5415. // If the string is the name of a register then we cannot check that it is
  5416. // valid here but if the string is of one the forms described in ACLE then we
  5417. // can check that the supplied fields are integers and within the valid
  5418. // ranges.
  5419. if (Fields.size() > 1) {
  5420. bool FiveFields = Fields.size() == 5;
  5421. bool ValidString = true;
  5422. if (IsARMBuiltin) {
  5423. ValidString &= Fields[0].startswith_lower("cp") ||
  5424. Fields[0].startswith_lower("p");
  5425. if (ValidString)
  5426. Fields[0] =
  5427. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  5428. ValidString &= Fields[2].startswith_lower("c");
  5429. if (ValidString)
  5430. Fields[2] = Fields[2].drop_front(1);
  5431. if (FiveFields) {
  5432. ValidString &= Fields[3].startswith_lower("c");
  5433. if (ValidString)
  5434. Fields[3] = Fields[3].drop_front(1);
  5435. }
  5436. }
  5437. SmallVector<int, 5> Ranges;
  5438. if (FiveFields)
  5439. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  5440. else
  5441. Ranges.append({15, 7, 15});
  5442. for (unsigned i=0; i<Fields.size(); ++i) {
  5443. int IntField;
  5444. ValidString &= !Fields[i].getAsInteger(10, IntField);
  5445. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  5446. }
  5447. if (!ValidString)
  5448. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  5449. << Arg->getSourceRange();
  5450. } else if (IsAArch64Builtin && Fields.size() == 1) {
  5451. // If the register name is one of those that appear in the condition below
  5452. // and the special register builtin being used is one of the write builtins,
  5453. // then we require that the argument provided for writing to the register
  5454. // is an integer constant expression. This is because it will be lowered to
  5455. // an MSR (immediate) instruction, so we need to know the immediate at
  5456. // compile time.
  5457. if (TheCall->getNumArgs() != 2)
  5458. return false;
  5459. std::string RegLower = Reg.lower();
  5460. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  5461. RegLower != "pan" && RegLower != "uao")
  5462. return false;
  5463. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5464. }
  5465. return false;
  5466. }
  5467. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  5468. /// This checks that the target supports __builtin_longjmp and
  5469. /// that val is a constant 1.
  5470. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  5471. if (!Context.getTargetInfo().hasSjLjLowering())
  5472. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
  5473. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  5474. Expr *Arg = TheCall->getArg(1);
  5475. llvm::APSInt Result;
  5476. // TODO: This is less than ideal. Overload this to take a value.
  5477. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5478. return true;
  5479. if (Result != 1)
  5480. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  5481. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  5482. return false;
  5483. }
  5484. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  5485. /// This checks that the target supports __builtin_setjmp.
  5486. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  5487. if (!Context.getTargetInfo().hasSjLjLowering())
  5488. return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
  5489. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  5490. return false;
  5491. }
  5492. namespace {
  5493. class UncoveredArgHandler {
  5494. enum { Unknown = -1, AllCovered = -2 };
  5495. signed FirstUncoveredArg = Unknown;
  5496. SmallVector<const Expr *, 4> DiagnosticExprs;
  5497. public:
  5498. UncoveredArgHandler() = default;
  5499. bool hasUncoveredArg() const {
  5500. return (FirstUncoveredArg >= 0);
  5501. }
  5502. unsigned getUncoveredArg() const {
  5503. assert(hasUncoveredArg() && "no uncovered argument");
  5504. return FirstUncoveredArg;
  5505. }
  5506. void setAllCovered() {
  5507. // A string has been found with all arguments covered, so clear out
  5508. // the diagnostics.
  5509. DiagnosticExprs.clear();
  5510. FirstUncoveredArg = AllCovered;
  5511. }
  5512. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  5513. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  5514. // Don't update if a previous string covers all arguments.
  5515. if (FirstUncoveredArg == AllCovered)
  5516. return;
  5517. // UncoveredArgHandler tracks the highest uncovered argument index
  5518. // and with it all the strings that match this index.
  5519. if (NewFirstUncoveredArg == FirstUncoveredArg)
  5520. DiagnosticExprs.push_back(StrExpr);
  5521. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  5522. DiagnosticExprs.clear();
  5523. DiagnosticExprs.push_back(StrExpr);
  5524. FirstUncoveredArg = NewFirstUncoveredArg;
  5525. }
  5526. }
  5527. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  5528. };
  5529. enum StringLiteralCheckType {
  5530. SLCT_NotALiteral,
  5531. SLCT_UncheckedLiteral,
  5532. SLCT_CheckedLiteral
  5533. };
  5534. } // namespace
  5535. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  5536. BinaryOperatorKind BinOpKind,
  5537. bool AddendIsRight) {
  5538. unsigned BitWidth = Offset.getBitWidth();
  5539. unsigned AddendBitWidth = Addend.getBitWidth();
  5540. // There might be negative interim results.
  5541. if (Addend.isUnsigned()) {
  5542. Addend = Addend.zext(++AddendBitWidth);
  5543. Addend.setIsSigned(true);
  5544. }
  5545. // Adjust the bit width of the APSInts.
  5546. if (AddendBitWidth > BitWidth) {
  5547. Offset = Offset.sext(AddendBitWidth);
  5548. BitWidth = AddendBitWidth;
  5549. } else if (BitWidth > AddendBitWidth) {
  5550. Addend = Addend.sext(BitWidth);
  5551. }
  5552. bool Ov = false;
  5553. llvm::APSInt ResOffset = Offset;
  5554. if (BinOpKind == BO_Add)
  5555. ResOffset = Offset.sadd_ov(Addend, Ov);
  5556. else {
  5557. assert(AddendIsRight && BinOpKind == BO_Sub &&
  5558. "operator must be add or sub with addend on the right");
  5559. ResOffset = Offset.ssub_ov(Addend, Ov);
  5560. }
  5561. // We add an offset to a pointer here so we should support an offset as big as
  5562. // possible.
  5563. if (Ov) {
  5564. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  5565. "index (intermediate) result too big");
  5566. Offset = Offset.sext(2 * BitWidth);
  5567. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  5568. return;
  5569. }
  5570. Offset = ResOffset;
  5571. }
  5572. namespace {
  5573. // This is a wrapper class around StringLiteral to support offsetted string
  5574. // literals as format strings. It takes the offset into account when returning
  5575. // the string and its length or the source locations to display notes correctly.
  5576. class FormatStringLiteral {
  5577. const StringLiteral *FExpr;
  5578. int64_t Offset;
  5579. public:
  5580. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  5581. : FExpr(fexpr), Offset(Offset) {}
  5582. StringRef getString() const {
  5583. return FExpr->getString().drop_front(Offset);
  5584. }
  5585. unsigned getByteLength() const {
  5586. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  5587. }
  5588. unsigned getLength() const { return FExpr->getLength() - Offset; }
  5589. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  5590. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  5591. QualType getType() const { return FExpr->getType(); }
  5592. bool isAscii() const { return FExpr->isAscii(); }
  5593. bool isWide() const { return FExpr->isWide(); }
  5594. bool isUTF8() const { return FExpr->isUTF8(); }
  5595. bool isUTF16() const { return FExpr->isUTF16(); }
  5596. bool isUTF32() const { return FExpr->isUTF32(); }
  5597. bool isPascal() const { return FExpr->isPascal(); }
  5598. SourceLocation getLocationOfByte(
  5599. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  5600. const TargetInfo &Target, unsigned *StartToken = nullptr,
  5601. unsigned *StartTokenByteOffset = nullptr) const {
  5602. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  5603. StartToken, StartTokenByteOffset);
  5604. }
  5605. SourceLocation getLocStart() const LLVM_READONLY {
  5606. return FExpr->getLocStart().getLocWithOffset(Offset);
  5607. }
  5608. SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
  5609. };
  5610. } // namespace
  5611. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  5612. const Expr *OrigFormatExpr,
  5613. ArrayRef<const Expr *> Args,
  5614. bool HasVAListArg, unsigned format_idx,
  5615. unsigned firstDataArg,
  5616. Sema::FormatStringType Type,
  5617. bool inFunctionCall,
  5618. Sema::VariadicCallType CallType,
  5619. llvm::SmallBitVector &CheckedVarArgs,
  5620. UncoveredArgHandler &UncoveredArg);
  5621. // Determine if an expression is a string literal or constant string.
  5622. // If this function returns false on the arguments to a function expecting a
  5623. // format string, we will usually need to emit a warning.
  5624. // True string literals are then checked by CheckFormatString.
  5625. static StringLiteralCheckType
  5626. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  5627. bool HasVAListArg, unsigned format_idx,
  5628. unsigned firstDataArg, Sema::FormatStringType Type,
  5629. Sema::VariadicCallType CallType, bool InFunctionCall,
  5630. llvm::SmallBitVector &CheckedVarArgs,
  5631. UncoveredArgHandler &UncoveredArg,
  5632. llvm::APSInt Offset) {
  5633. tryAgain:
  5634. assert(Offset.isSigned() && "invalid offset");
  5635. if (E->isTypeDependent() || E->isValueDependent())
  5636. return SLCT_NotALiteral;
  5637. E = E->IgnoreParenCasts();
  5638. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  5639. // Technically -Wformat-nonliteral does not warn about this case.
  5640. // The behavior of printf and friends in this case is implementation
  5641. // dependent. Ideally if the format string cannot be null then
  5642. // it should have a 'nonnull' attribute in the function prototype.
  5643. return SLCT_UncheckedLiteral;
  5644. switch (E->getStmtClass()) {
  5645. case Stmt::BinaryConditionalOperatorClass:
  5646. case Stmt::ConditionalOperatorClass: {
  5647. // The expression is a literal if both sub-expressions were, and it was
  5648. // completely checked only if both sub-expressions were checked.
  5649. const AbstractConditionalOperator *C =
  5650. cast<AbstractConditionalOperator>(E);
  5651. // Determine whether it is necessary to check both sub-expressions, for
  5652. // example, because the condition expression is a constant that can be
  5653. // evaluated at compile time.
  5654. bool CheckLeft = true, CheckRight = true;
  5655. bool Cond;
  5656. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
  5657. if (Cond)
  5658. CheckRight = false;
  5659. else
  5660. CheckLeft = false;
  5661. }
  5662. // We need to maintain the offsets for the right and the left hand side
  5663. // separately to check if every possible indexed expression is a valid
  5664. // string literal. They might have different offsets for different string
  5665. // literals in the end.
  5666. StringLiteralCheckType Left;
  5667. if (!CheckLeft)
  5668. Left = SLCT_UncheckedLiteral;
  5669. else {
  5670. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  5671. HasVAListArg, format_idx, firstDataArg,
  5672. Type, CallType, InFunctionCall,
  5673. CheckedVarArgs, UncoveredArg, Offset);
  5674. if (Left == SLCT_NotALiteral || !CheckRight) {
  5675. return Left;
  5676. }
  5677. }
  5678. StringLiteralCheckType Right =
  5679. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  5680. HasVAListArg, format_idx, firstDataArg,
  5681. Type, CallType, InFunctionCall, CheckedVarArgs,
  5682. UncoveredArg, Offset);
  5683. return (CheckLeft && Left < Right) ? Left : Right;
  5684. }
  5685. case Stmt::ImplicitCastExprClass:
  5686. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  5687. goto tryAgain;
  5688. case Stmt::OpaqueValueExprClass:
  5689. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  5690. E = src;
  5691. goto tryAgain;
  5692. }
  5693. return SLCT_NotALiteral;
  5694. case Stmt::PredefinedExprClass:
  5695. // While __func__, etc., are technically not string literals, they
  5696. // cannot contain format specifiers and thus are not a security
  5697. // liability.
  5698. return SLCT_UncheckedLiteral;
  5699. case Stmt::DeclRefExprClass: {
  5700. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  5701. // As an exception, do not flag errors for variables binding to
  5702. // const string literals.
  5703. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  5704. bool isConstant = false;
  5705. QualType T = DR->getType();
  5706. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  5707. isConstant = AT->getElementType().isConstant(S.Context);
  5708. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  5709. isConstant = T.isConstant(S.Context) &&
  5710. PT->getPointeeType().isConstant(S.Context);
  5711. } else if (T->isObjCObjectPointerType()) {
  5712. // In ObjC, there is usually no "const ObjectPointer" type,
  5713. // so don't check if the pointee type is constant.
  5714. isConstant = T.isConstant(S.Context);
  5715. }
  5716. if (isConstant) {
  5717. if (const Expr *Init = VD->getAnyInitializer()) {
  5718. // Look through initializers like const char c[] = { "foo" }
  5719. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  5720. if (InitList->isStringLiteralInit())
  5721. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  5722. }
  5723. return checkFormatStringExpr(S, Init, Args,
  5724. HasVAListArg, format_idx,
  5725. firstDataArg, Type, CallType,
  5726. /*InFunctionCall*/ false, CheckedVarArgs,
  5727. UncoveredArg, Offset);
  5728. }
  5729. }
  5730. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  5731. // special check to see if the format string is a function parameter
  5732. // of the function calling the printf function. If the function
  5733. // has an attribute indicating it is a printf-like function, then we
  5734. // should suppress warnings concerning non-literals being used in a call
  5735. // to a vprintf function. For example:
  5736. //
  5737. // void
  5738. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  5739. // va_list ap;
  5740. // va_start(ap, fmt);
  5741. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  5742. // ...
  5743. // }
  5744. if (HasVAListArg) {
  5745. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  5746. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  5747. int PVIndex = PV->getFunctionScopeIndex() + 1;
  5748. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  5749. // adjust for implicit parameter
  5750. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  5751. if (MD->isInstance())
  5752. ++PVIndex;
  5753. // We also check if the formats are compatible.
  5754. // We can't pass a 'scanf' string to a 'printf' function.
  5755. if (PVIndex == PVFormat->getFormatIdx() &&
  5756. Type == S.GetFormatStringType(PVFormat))
  5757. return SLCT_UncheckedLiteral;
  5758. }
  5759. }
  5760. }
  5761. }
  5762. }
  5763. return SLCT_NotALiteral;
  5764. }
  5765. case Stmt::CallExprClass:
  5766. case Stmt::CXXMemberCallExprClass: {
  5767. const CallExpr *CE = cast<CallExpr>(E);
  5768. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  5769. bool IsFirst = true;
  5770. StringLiteralCheckType CommonResult;
  5771. for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
  5772. const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
  5773. StringLiteralCheckType Result = checkFormatStringExpr(
  5774. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  5775. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  5776. if (IsFirst) {
  5777. CommonResult = Result;
  5778. IsFirst = false;
  5779. }
  5780. }
  5781. if (!IsFirst)
  5782. return CommonResult;
  5783. if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
  5784. unsigned BuiltinID = FD->getBuiltinID();
  5785. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  5786. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  5787. const Expr *Arg = CE->getArg(0);
  5788. return checkFormatStringExpr(S, Arg, Args,
  5789. HasVAListArg, format_idx,
  5790. firstDataArg, Type, CallType,
  5791. InFunctionCall, CheckedVarArgs,
  5792. UncoveredArg, Offset);
  5793. }
  5794. }
  5795. }
  5796. return SLCT_NotALiteral;
  5797. }
  5798. case Stmt::ObjCMessageExprClass: {
  5799. const auto *ME = cast<ObjCMessageExpr>(E);
  5800. if (const auto *ND = ME->getMethodDecl()) {
  5801. if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
  5802. const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
  5803. return checkFormatStringExpr(
  5804. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  5805. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  5806. }
  5807. }
  5808. return SLCT_NotALiteral;
  5809. }
  5810. case Stmt::ObjCStringLiteralClass:
  5811. case Stmt::StringLiteralClass: {
  5812. const StringLiteral *StrE = nullptr;
  5813. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  5814. StrE = ObjCFExpr->getString();
  5815. else
  5816. StrE = cast<StringLiteral>(E);
  5817. if (StrE) {
  5818. if (Offset.isNegative() || Offset > StrE->getLength()) {
  5819. // TODO: It would be better to have an explicit warning for out of
  5820. // bounds literals.
  5821. return SLCT_NotALiteral;
  5822. }
  5823. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  5824. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  5825. firstDataArg, Type, InFunctionCall, CallType,
  5826. CheckedVarArgs, UncoveredArg);
  5827. return SLCT_CheckedLiteral;
  5828. }
  5829. return SLCT_NotALiteral;
  5830. }
  5831. case Stmt::BinaryOperatorClass: {
  5832. llvm::APSInt LResult;
  5833. llvm::APSInt RResult;
  5834. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  5835. // A string literal + an int offset is still a string literal.
  5836. if (BinOp->isAdditiveOp()) {
  5837. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
  5838. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
  5839. if (LIsInt != RIsInt) {
  5840. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  5841. if (LIsInt) {
  5842. if (BinOpKind == BO_Add) {
  5843. sumOffsets(Offset, LResult, BinOpKind, RIsInt);
  5844. E = BinOp->getRHS();
  5845. goto tryAgain;
  5846. }
  5847. } else {
  5848. sumOffsets(Offset, RResult, BinOpKind, RIsInt);
  5849. E = BinOp->getLHS();
  5850. goto tryAgain;
  5851. }
  5852. }
  5853. }
  5854. return SLCT_NotALiteral;
  5855. }
  5856. case Stmt::UnaryOperatorClass: {
  5857. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  5858. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  5859. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  5860. llvm::APSInt IndexResult;
  5861. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
  5862. sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
  5863. E = ASE->getBase();
  5864. goto tryAgain;
  5865. }
  5866. }
  5867. return SLCT_NotALiteral;
  5868. }
  5869. default:
  5870. return SLCT_NotALiteral;
  5871. }
  5872. }
  5873. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  5874. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  5875. .Case("scanf", FST_Scanf)
  5876. .Cases("printf", "printf0", FST_Printf)
  5877. .Cases("NSString", "CFString", FST_NSString)
  5878. .Case("strftime", FST_Strftime)
  5879. .Case("strfmon", FST_Strfmon)
  5880. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  5881. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  5882. .Case("os_trace", FST_OSLog)
  5883. .Case("os_log", FST_OSLog)
  5884. .Default(FST_Unknown);
  5885. }
  5886. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  5887. /// functions) for correct use of format strings.
  5888. /// Returns true if a format string has been fully checked.
  5889. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  5890. ArrayRef<const Expr *> Args,
  5891. bool IsCXXMember,
  5892. VariadicCallType CallType,
  5893. SourceLocation Loc, SourceRange Range,
  5894. llvm::SmallBitVector &CheckedVarArgs) {
  5895. FormatStringInfo FSI;
  5896. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  5897. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  5898. FSI.FirstDataArg, GetFormatStringType(Format),
  5899. CallType, Loc, Range, CheckedVarArgs);
  5900. return false;
  5901. }
  5902. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  5903. bool HasVAListArg, unsigned format_idx,
  5904. unsigned firstDataArg, FormatStringType Type,
  5905. VariadicCallType CallType,
  5906. SourceLocation Loc, SourceRange Range,
  5907. llvm::SmallBitVector &CheckedVarArgs) {
  5908. // CHECK: printf/scanf-like function is called with no format string.
  5909. if (format_idx >= Args.size()) {
  5910. Diag(Loc, diag::warn_missing_format_string) << Range;
  5911. return false;
  5912. }
  5913. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  5914. // CHECK: format string is not a string literal.
  5915. //
  5916. // Dynamically generated format strings are difficult to
  5917. // automatically vet at compile time. Requiring that format strings
  5918. // are string literals: (1) permits the checking of format strings by
  5919. // the compiler and thereby (2) can practically remove the source of
  5920. // many format string exploits.
  5921. // Format string can be either ObjC string (e.g. @"%d") or
  5922. // C string (e.g. "%d")
  5923. // ObjC string uses the same format specifiers as C string, so we can use
  5924. // the same format string checking logic for both ObjC and C strings.
  5925. UncoveredArgHandler UncoveredArg;
  5926. StringLiteralCheckType CT =
  5927. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  5928. format_idx, firstDataArg, Type, CallType,
  5929. /*IsFunctionCall*/ true, CheckedVarArgs,
  5930. UncoveredArg,
  5931. /*no string offset*/ llvm::APSInt(64, false) = 0);
  5932. // Generate a diagnostic where an uncovered argument is detected.
  5933. if (UncoveredArg.hasUncoveredArg()) {
  5934. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  5935. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  5936. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  5937. }
  5938. if (CT != SLCT_NotALiteral)
  5939. // Literal format string found, check done!
  5940. return CT == SLCT_CheckedLiteral;
  5941. // Strftime is particular as it always uses a single 'time' argument,
  5942. // so it is safe to pass a non-literal string.
  5943. if (Type == FST_Strftime)
  5944. return false;
  5945. // Do not emit diag when the string param is a macro expansion and the
  5946. // format is either NSString or CFString. This is a hack to prevent
  5947. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  5948. // which are usually used in place of NS and CF string literals.
  5949. SourceLocation FormatLoc = Args[format_idx]->getLocStart();
  5950. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  5951. return false;
  5952. // If there are no arguments specified, warn with -Wformat-security, otherwise
  5953. // warn only with -Wformat-nonliteral.
  5954. if (Args.size() == firstDataArg) {
  5955. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  5956. << OrigFormatExpr->getSourceRange();
  5957. switch (Type) {
  5958. default:
  5959. break;
  5960. case FST_Kprintf:
  5961. case FST_FreeBSDKPrintf:
  5962. case FST_Printf:
  5963. Diag(FormatLoc, diag::note_format_security_fixit)
  5964. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  5965. break;
  5966. case FST_NSString:
  5967. Diag(FormatLoc, diag::note_format_security_fixit)
  5968. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  5969. break;
  5970. }
  5971. } else {
  5972. Diag(FormatLoc, diag::warn_format_nonliteral)
  5973. << OrigFormatExpr->getSourceRange();
  5974. }
  5975. return false;
  5976. }
  5977. namespace {
  5978. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  5979. protected:
  5980. Sema &S;
  5981. const FormatStringLiteral *FExpr;
  5982. const Expr *OrigFormatExpr;
  5983. const Sema::FormatStringType FSType;
  5984. const unsigned FirstDataArg;
  5985. const unsigned NumDataArgs;
  5986. const char *Beg; // Start of format string.
  5987. const bool HasVAListArg;
  5988. ArrayRef<const Expr *> Args;
  5989. unsigned FormatIdx;
  5990. llvm::SmallBitVector CoveredArgs;
  5991. bool usesPositionalArgs = false;
  5992. bool atFirstArg = true;
  5993. bool inFunctionCall;
  5994. Sema::VariadicCallType CallType;
  5995. llvm::SmallBitVector &CheckedVarArgs;
  5996. UncoveredArgHandler &UncoveredArg;
  5997. public:
  5998. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  5999. const Expr *origFormatExpr,
  6000. const Sema::FormatStringType type, unsigned firstDataArg,
  6001. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  6002. ArrayRef<const Expr *> Args, unsigned formatIdx,
  6003. bool inFunctionCall, Sema::VariadicCallType callType,
  6004. llvm::SmallBitVector &CheckedVarArgs,
  6005. UncoveredArgHandler &UncoveredArg)
  6006. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  6007. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  6008. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  6009. inFunctionCall(inFunctionCall), CallType(callType),
  6010. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  6011. CoveredArgs.resize(numDataArgs);
  6012. CoveredArgs.reset();
  6013. }
  6014. void DoneProcessing();
  6015. void HandleIncompleteSpecifier(const char *startSpecifier,
  6016. unsigned specifierLen) override;
  6017. void HandleInvalidLengthModifier(
  6018. const analyze_format_string::FormatSpecifier &FS,
  6019. const analyze_format_string::ConversionSpecifier &CS,
  6020. const char *startSpecifier, unsigned specifierLen,
  6021. unsigned DiagID);
  6022. void HandleNonStandardLengthModifier(
  6023. const analyze_format_string::FormatSpecifier &FS,
  6024. const char *startSpecifier, unsigned specifierLen);
  6025. void HandleNonStandardConversionSpecifier(
  6026. const analyze_format_string::ConversionSpecifier &CS,
  6027. const char *startSpecifier, unsigned specifierLen);
  6028. void HandlePosition(const char *startPos, unsigned posLen) override;
  6029. void HandleInvalidPosition(const char *startSpecifier,
  6030. unsigned specifierLen,
  6031. analyze_format_string::PositionContext p) override;
  6032. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  6033. void HandleNullChar(const char *nullCharacter) override;
  6034. template <typename Range>
  6035. static void
  6036. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  6037. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  6038. bool IsStringLocation, Range StringRange,
  6039. ArrayRef<FixItHint> Fixit = None);
  6040. protected:
  6041. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  6042. const char *startSpec,
  6043. unsigned specifierLen,
  6044. const char *csStart, unsigned csLen);
  6045. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6046. const char *startSpec,
  6047. unsigned specifierLen);
  6048. SourceRange getFormatStringRange();
  6049. CharSourceRange getSpecifierRange(const char *startSpecifier,
  6050. unsigned specifierLen);
  6051. SourceLocation getLocationOfByte(const char *x);
  6052. const Expr *getDataArg(unsigned i) const;
  6053. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  6054. const analyze_format_string::ConversionSpecifier &CS,
  6055. const char *startSpecifier, unsigned specifierLen,
  6056. unsigned argIndex);
  6057. template <typename Range>
  6058. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  6059. bool IsStringLocation, Range StringRange,
  6060. ArrayRef<FixItHint> Fixit = None);
  6061. };
  6062. } // namespace
  6063. SourceRange CheckFormatHandler::getFormatStringRange() {
  6064. return OrigFormatExpr->getSourceRange();
  6065. }
  6066. CharSourceRange CheckFormatHandler::
  6067. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  6068. SourceLocation Start = getLocationOfByte(startSpecifier);
  6069. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  6070. // Advance the end SourceLocation by one due to half-open ranges.
  6071. End = End.getLocWithOffset(1);
  6072. return CharSourceRange::getCharRange(Start, End);
  6073. }
  6074. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  6075. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  6076. S.getLangOpts(), S.Context.getTargetInfo());
  6077. }
  6078. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  6079. unsigned specifierLen){
  6080. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  6081. getLocationOfByte(startSpecifier),
  6082. /*IsStringLocation*/true,
  6083. getSpecifierRange(startSpecifier, specifierLen));
  6084. }
  6085. void CheckFormatHandler::HandleInvalidLengthModifier(
  6086. const analyze_format_string::FormatSpecifier &FS,
  6087. const analyze_format_string::ConversionSpecifier &CS,
  6088. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  6089. using namespace analyze_format_string;
  6090. const LengthModifier &LM = FS.getLengthModifier();
  6091. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6092. // See if we know how to fix this length modifier.
  6093. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6094. if (FixedLM) {
  6095. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6096. getLocationOfByte(LM.getStart()),
  6097. /*IsStringLocation*/true,
  6098. getSpecifierRange(startSpecifier, specifierLen));
  6099. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6100. << FixedLM->toString()
  6101. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6102. } else {
  6103. FixItHint Hint;
  6104. if (DiagID == diag::warn_format_nonsensical_length)
  6105. Hint = FixItHint::CreateRemoval(LMRange);
  6106. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6107. getLocationOfByte(LM.getStart()),
  6108. /*IsStringLocation*/true,
  6109. getSpecifierRange(startSpecifier, specifierLen),
  6110. Hint);
  6111. }
  6112. }
  6113. void CheckFormatHandler::HandleNonStandardLengthModifier(
  6114. const analyze_format_string::FormatSpecifier &FS,
  6115. const char *startSpecifier, unsigned specifierLen) {
  6116. using namespace analyze_format_string;
  6117. const LengthModifier &LM = FS.getLengthModifier();
  6118. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6119. // See if we know how to fix this length modifier.
  6120. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6121. if (FixedLM) {
  6122. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6123. << LM.toString() << 0,
  6124. getLocationOfByte(LM.getStart()),
  6125. /*IsStringLocation*/true,
  6126. getSpecifierRange(startSpecifier, specifierLen));
  6127. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6128. << FixedLM->toString()
  6129. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6130. } else {
  6131. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6132. << LM.toString() << 0,
  6133. getLocationOfByte(LM.getStart()),
  6134. /*IsStringLocation*/true,
  6135. getSpecifierRange(startSpecifier, specifierLen));
  6136. }
  6137. }
  6138. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  6139. const analyze_format_string::ConversionSpecifier &CS,
  6140. const char *startSpecifier, unsigned specifierLen) {
  6141. using namespace analyze_format_string;
  6142. // See if we know how to fix this conversion specifier.
  6143. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  6144. if (FixedCS) {
  6145. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6146. << CS.toString() << /*conversion specifier*/1,
  6147. getLocationOfByte(CS.getStart()),
  6148. /*IsStringLocation*/true,
  6149. getSpecifierRange(startSpecifier, specifierLen));
  6150. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  6151. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  6152. << FixedCS->toString()
  6153. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  6154. } else {
  6155. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6156. << CS.toString() << /*conversion specifier*/1,
  6157. getLocationOfByte(CS.getStart()),
  6158. /*IsStringLocation*/true,
  6159. getSpecifierRange(startSpecifier, specifierLen));
  6160. }
  6161. }
  6162. void CheckFormatHandler::HandlePosition(const char *startPos,
  6163. unsigned posLen) {
  6164. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  6165. getLocationOfByte(startPos),
  6166. /*IsStringLocation*/true,
  6167. getSpecifierRange(startPos, posLen));
  6168. }
  6169. void
  6170. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  6171. analyze_format_string::PositionContext p) {
  6172. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  6173. << (unsigned) p,
  6174. getLocationOfByte(startPos), /*IsStringLocation*/true,
  6175. getSpecifierRange(startPos, posLen));
  6176. }
  6177. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  6178. unsigned posLen) {
  6179. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  6180. getLocationOfByte(startPos),
  6181. /*IsStringLocation*/true,
  6182. getSpecifierRange(startPos, posLen));
  6183. }
  6184. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  6185. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  6186. // The presence of a null character is likely an error.
  6187. EmitFormatDiagnostic(
  6188. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  6189. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  6190. getFormatStringRange());
  6191. }
  6192. }
  6193. // Note that this may return NULL if there was an error parsing or building
  6194. // one of the argument expressions.
  6195. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  6196. return Args[FirstDataArg + i];
  6197. }
  6198. void CheckFormatHandler::DoneProcessing() {
  6199. // Does the number of data arguments exceed the number of
  6200. // format conversions in the format string?
  6201. if (!HasVAListArg) {
  6202. // Find any arguments that weren't covered.
  6203. CoveredArgs.flip();
  6204. signed notCoveredArg = CoveredArgs.find_first();
  6205. if (notCoveredArg >= 0) {
  6206. assert((unsigned)notCoveredArg < NumDataArgs);
  6207. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  6208. } else {
  6209. UncoveredArg.setAllCovered();
  6210. }
  6211. }
  6212. }
  6213. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  6214. const Expr *ArgExpr) {
  6215. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  6216. "Invalid state");
  6217. if (!ArgExpr)
  6218. return;
  6219. SourceLocation Loc = ArgExpr->getLocStart();
  6220. if (S.getSourceManager().isInSystemMacro(Loc))
  6221. return;
  6222. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  6223. for (auto E : DiagnosticExprs)
  6224. PDiag << E->getSourceRange();
  6225. CheckFormatHandler::EmitFormatDiagnostic(
  6226. S, IsFunctionCall, DiagnosticExprs[0],
  6227. PDiag, Loc, /*IsStringLocation*/false,
  6228. DiagnosticExprs[0]->getSourceRange());
  6229. }
  6230. bool
  6231. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  6232. SourceLocation Loc,
  6233. const char *startSpec,
  6234. unsigned specifierLen,
  6235. const char *csStart,
  6236. unsigned csLen) {
  6237. bool keepGoing = true;
  6238. if (argIndex < NumDataArgs) {
  6239. // Consider the argument coverered, even though the specifier doesn't
  6240. // make sense.
  6241. CoveredArgs.set(argIndex);
  6242. }
  6243. else {
  6244. // If argIndex exceeds the number of data arguments we
  6245. // don't issue a warning because that is just a cascade of warnings (and
  6246. // they may have intended '%%' anyway). We don't want to continue processing
  6247. // the format string after this point, however, as we will like just get
  6248. // gibberish when trying to match arguments.
  6249. keepGoing = false;
  6250. }
  6251. StringRef Specifier(csStart, csLen);
  6252. // If the specifier in non-printable, it could be the first byte of a UTF-8
  6253. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  6254. // hex value.
  6255. std::string CodePointStr;
  6256. if (!llvm::sys::locale::isPrint(*csStart)) {
  6257. llvm::UTF32 CodePoint;
  6258. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  6259. const llvm::UTF8 *E =
  6260. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  6261. llvm::ConversionResult Result =
  6262. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  6263. if (Result != llvm::conversionOK) {
  6264. unsigned char FirstChar = *csStart;
  6265. CodePoint = (llvm::UTF32)FirstChar;
  6266. }
  6267. llvm::raw_string_ostream OS(CodePointStr);
  6268. if (CodePoint < 256)
  6269. OS << "\\x" << llvm::format("%02x", CodePoint);
  6270. else if (CodePoint <= 0xFFFF)
  6271. OS << "\\u" << llvm::format("%04x", CodePoint);
  6272. else
  6273. OS << "\\U" << llvm::format("%08x", CodePoint);
  6274. OS.flush();
  6275. Specifier = CodePointStr;
  6276. }
  6277. EmitFormatDiagnostic(
  6278. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  6279. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  6280. return keepGoing;
  6281. }
  6282. void
  6283. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6284. const char *startSpec,
  6285. unsigned specifierLen) {
  6286. EmitFormatDiagnostic(
  6287. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  6288. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  6289. }
  6290. bool
  6291. CheckFormatHandler::CheckNumArgs(
  6292. const analyze_format_string::FormatSpecifier &FS,
  6293. const analyze_format_string::ConversionSpecifier &CS,
  6294. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  6295. if (argIndex >= NumDataArgs) {
  6296. PartialDiagnostic PDiag = FS.usesPositionalArg()
  6297. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  6298. << (argIndex+1) << NumDataArgs)
  6299. : S.PDiag(diag::warn_printf_insufficient_data_args);
  6300. EmitFormatDiagnostic(
  6301. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  6302. getSpecifierRange(startSpecifier, specifierLen));
  6303. // Since more arguments than conversion tokens are given, by extension
  6304. // all arguments are covered, so mark this as so.
  6305. UncoveredArg.setAllCovered();
  6306. return false;
  6307. }
  6308. return true;
  6309. }
  6310. template<typename Range>
  6311. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  6312. SourceLocation Loc,
  6313. bool IsStringLocation,
  6314. Range StringRange,
  6315. ArrayRef<FixItHint> FixIt) {
  6316. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  6317. Loc, IsStringLocation, StringRange, FixIt);
  6318. }
  6319. /// If the format string is not within the function call, emit a note
  6320. /// so that the function call and string are in diagnostic messages.
  6321. ///
  6322. /// \param InFunctionCall if true, the format string is within the function
  6323. /// call and only one diagnostic message will be produced. Otherwise, an
  6324. /// extra note will be emitted pointing to location of the format string.
  6325. ///
  6326. /// \param ArgumentExpr the expression that is passed as the format string
  6327. /// argument in the function call. Used for getting locations when two
  6328. /// diagnostics are emitted.
  6329. ///
  6330. /// \param PDiag the callee should already have provided any strings for the
  6331. /// diagnostic message. This function only adds locations and fixits
  6332. /// to diagnostics.
  6333. ///
  6334. /// \param Loc primary location for diagnostic. If two diagnostics are
  6335. /// required, one will be at Loc and a new SourceLocation will be created for
  6336. /// the other one.
  6337. ///
  6338. /// \param IsStringLocation if true, Loc points to the format string should be
  6339. /// used for the note. Otherwise, Loc points to the argument list and will
  6340. /// be used with PDiag.
  6341. ///
  6342. /// \param StringRange some or all of the string to highlight. This is
  6343. /// templated so it can accept either a CharSourceRange or a SourceRange.
  6344. ///
  6345. /// \param FixIt optional fix it hint for the format string.
  6346. template <typename Range>
  6347. void CheckFormatHandler::EmitFormatDiagnostic(
  6348. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  6349. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  6350. Range StringRange, ArrayRef<FixItHint> FixIt) {
  6351. if (InFunctionCall) {
  6352. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  6353. D << StringRange;
  6354. D << FixIt;
  6355. } else {
  6356. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  6357. << ArgumentExpr->getSourceRange();
  6358. const Sema::SemaDiagnosticBuilder &Note =
  6359. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  6360. diag::note_format_string_defined);
  6361. Note << StringRange;
  6362. Note << FixIt;
  6363. }
  6364. }
  6365. //===--- CHECK: Printf format string checking ------------------------------===//
  6366. namespace {
  6367. class CheckPrintfHandler : public CheckFormatHandler {
  6368. public:
  6369. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  6370. const Expr *origFormatExpr,
  6371. const Sema::FormatStringType type, unsigned firstDataArg,
  6372. unsigned numDataArgs, bool isObjC, const char *beg,
  6373. bool hasVAListArg, ArrayRef<const Expr *> Args,
  6374. unsigned formatIdx, bool inFunctionCall,
  6375. Sema::VariadicCallType CallType,
  6376. llvm::SmallBitVector &CheckedVarArgs,
  6377. UncoveredArgHandler &UncoveredArg)
  6378. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  6379. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  6380. inFunctionCall, CallType, CheckedVarArgs,
  6381. UncoveredArg) {}
  6382. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  6383. /// Returns true if '%@' specifiers are allowed in the format string.
  6384. bool allowsObjCArg() const {
  6385. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  6386. FSType == Sema::FST_OSTrace;
  6387. }
  6388. bool HandleInvalidPrintfConversionSpecifier(
  6389. const analyze_printf::PrintfSpecifier &FS,
  6390. const char *startSpecifier,
  6391. unsigned specifierLen) override;
  6392. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  6393. const char *startSpecifier,
  6394. unsigned specifierLen) override;
  6395. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  6396. const char *StartSpecifier,
  6397. unsigned SpecifierLen,
  6398. const Expr *E);
  6399. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  6400. const char *startSpecifier, unsigned specifierLen);
  6401. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  6402. const analyze_printf::OptionalAmount &Amt,
  6403. unsigned type,
  6404. const char *startSpecifier, unsigned specifierLen);
  6405. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6406. const analyze_printf::OptionalFlag &flag,
  6407. const char *startSpecifier, unsigned specifierLen);
  6408. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  6409. const analyze_printf::OptionalFlag &ignoredFlag,
  6410. const analyze_printf::OptionalFlag &flag,
  6411. const char *startSpecifier, unsigned specifierLen);
  6412. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  6413. const Expr *E);
  6414. void HandleEmptyObjCModifierFlag(const char *startFlag,
  6415. unsigned flagLen) override;
  6416. void HandleInvalidObjCModifierFlag(const char *startFlag,
  6417. unsigned flagLen) override;
  6418. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  6419. const char *flagsEnd,
  6420. const char *conversionPosition)
  6421. override;
  6422. };
  6423. } // namespace
  6424. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  6425. const analyze_printf::PrintfSpecifier &FS,
  6426. const char *startSpecifier,
  6427. unsigned specifierLen) {
  6428. const analyze_printf::PrintfConversionSpecifier &CS =
  6429. FS.getConversionSpecifier();
  6430. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  6431. getLocationOfByte(CS.getStart()),
  6432. startSpecifier, specifierLen,
  6433. CS.getStart(), CS.getLength());
  6434. }
  6435. bool CheckPrintfHandler::HandleAmount(
  6436. const analyze_format_string::OptionalAmount &Amt,
  6437. unsigned k, const char *startSpecifier,
  6438. unsigned specifierLen) {
  6439. if (Amt.hasDataArgument()) {
  6440. if (!HasVAListArg) {
  6441. unsigned argIndex = Amt.getArgIndex();
  6442. if (argIndex >= NumDataArgs) {
  6443. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  6444. << k,
  6445. getLocationOfByte(Amt.getStart()),
  6446. /*IsStringLocation*/true,
  6447. getSpecifierRange(startSpecifier, specifierLen));
  6448. // Don't do any more checking. We will just emit
  6449. // spurious errors.
  6450. return false;
  6451. }
  6452. // Type check the data argument. It should be an 'int'.
  6453. // Although not in conformance with C99, we also allow the argument to be
  6454. // an 'unsigned int' as that is a reasonably safe case. GCC also
  6455. // doesn't emit a warning for that case.
  6456. CoveredArgs.set(argIndex);
  6457. const Expr *Arg = getDataArg(argIndex);
  6458. if (!Arg)
  6459. return false;
  6460. QualType T = Arg->getType();
  6461. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  6462. assert(AT.isValid());
  6463. if (!AT.matchesType(S.Context, T)) {
  6464. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  6465. << k << AT.getRepresentativeTypeName(S.Context)
  6466. << T << Arg->getSourceRange(),
  6467. getLocationOfByte(Amt.getStart()),
  6468. /*IsStringLocation*/true,
  6469. getSpecifierRange(startSpecifier, specifierLen));
  6470. // Don't do any more checking. We will just emit
  6471. // spurious errors.
  6472. return false;
  6473. }
  6474. }
  6475. }
  6476. return true;
  6477. }
  6478. void CheckPrintfHandler::HandleInvalidAmount(
  6479. const analyze_printf::PrintfSpecifier &FS,
  6480. const analyze_printf::OptionalAmount &Amt,
  6481. unsigned type,
  6482. const char *startSpecifier,
  6483. unsigned specifierLen) {
  6484. const analyze_printf::PrintfConversionSpecifier &CS =
  6485. FS.getConversionSpecifier();
  6486. FixItHint fixit =
  6487. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  6488. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  6489. Amt.getConstantLength()))
  6490. : FixItHint();
  6491. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  6492. << type << CS.toString(),
  6493. getLocationOfByte(Amt.getStart()),
  6494. /*IsStringLocation*/true,
  6495. getSpecifierRange(startSpecifier, specifierLen),
  6496. fixit);
  6497. }
  6498. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6499. const analyze_printf::OptionalFlag &flag,
  6500. const char *startSpecifier,
  6501. unsigned specifierLen) {
  6502. // Warn about pointless flag with a fixit removal.
  6503. const analyze_printf::PrintfConversionSpecifier &CS =
  6504. FS.getConversionSpecifier();
  6505. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  6506. << flag.toString() << CS.toString(),
  6507. getLocationOfByte(flag.getPosition()),
  6508. /*IsStringLocation*/true,
  6509. getSpecifierRange(startSpecifier, specifierLen),
  6510. FixItHint::CreateRemoval(
  6511. getSpecifierRange(flag.getPosition(), 1)));
  6512. }
  6513. void CheckPrintfHandler::HandleIgnoredFlag(
  6514. const analyze_printf::PrintfSpecifier &FS,
  6515. const analyze_printf::OptionalFlag &ignoredFlag,
  6516. const analyze_printf::OptionalFlag &flag,
  6517. const char *startSpecifier,
  6518. unsigned specifierLen) {
  6519. // Warn about ignored flag with a fixit removal.
  6520. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  6521. << ignoredFlag.toString() << flag.toString(),
  6522. getLocationOfByte(ignoredFlag.getPosition()),
  6523. /*IsStringLocation*/true,
  6524. getSpecifierRange(startSpecifier, specifierLen),
  6525. FixItHint::CreateRemoval(
  6526. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  6527. }
  6528. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  6529. unsigned flagLen) {
  6530. // Warn about an empty flag.
  6531. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  6532. getLocationOfByte(startFlag),
  6533. /*IsStringLocation*/true,
  6534. getSpecifierRange(startFlag, flagLen));
  6535. }
  6536. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  6537. unsigned flagLen) {
  6538. // Warn about an invalid flag.
  6539. auto Range = getSpecifierRange(startFlag, flagLen);
  6540. StringRef flag(startFlag, flagLen);
  6541. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  6542. getLocationOfByte(startFlag),
  6543. /*IsStringLocation*/true,
  6544. Range, FixItHint::CreateRemoval(Range));
  6545. }
  6546. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  6547. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  6548. // Warn about using '[...]' without a '@' conversion.
  6549. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  6550. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  6551. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  6552. getLocationOfByte(conversionPosition),
  6553. /*IsStringLocation*/true,
  6554. Range, FixItHint::CreateRemoval(Range));
  6555. }
  6556. // Determines if the specified is a C++ class or struct containing
  6557. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  6558. // "c_str()").
  6559. template<typename MemberKind>
  6560. static llvm::SmallPtrSet<MemberKind*, 1>
  6561. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  6562. const RecordType *RT = Ty->getAs<RecordType>();
  6563. llvm::SmallPtrSet<MemberKind*, 1> Results;
  6564. if (!RT)
  6565. return Results;
  6566. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  6567. if (!RD || !RD->getDefinition())
  6568. return Results;
  6569. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  6570. Sema::LookupMemberName);
  6571. R.suppressDiagnostics();
  6572. // We just need to include all members of the right kind turned up by the
  6573. // filter, at this point.
  6574. if (S.LookupQualifiedName(R, RT->getDecl()))
  6575. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  6576. NamedDecl *decl = (*I)->getUnderlyingDecl();
  6577. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  6578. Results.insert(FK);
  6579. }
  6580. return Results;
  6581. }
  6582. /// Check if we could call '.c_str()' on an object.
  6583. ///
  6584. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  6585. /// allow the call, or if it would be ambiguous).
  6586. bool Sema::hasCStrMethod(const Expr *E) {
  6587. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6588. MethodSet Results =
  6589. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  6590. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6591. MI != ME; ++MI)
  6592. if ((*MI)->getMinRequiredArguments() == 0)
  6593. return true;
  6594. return false;
  6595. }
  6596. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  6597. // better diagnostic if so. AT is assumed to be valid.
  6598. // Returns true when a c_str() conversion method is found.
  6599. bool CheckPrintfHandler::checkForCStrMembers(
  6600. const analyze_printf::ArgType &AT, const Expr *E) {
  6601. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6602. MethodSet Results =
  6603. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  6604. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6605. MI != ME; ++MI) {
  6606. const CXXMethodDecl *Method = *MI;
  6607. if (Method->getMinRequiredArguments() == 0 &&
  6608. AT.matchesType(S.Context, Method->getReturnType())) {
  6609. // FIXME: Suggest parens if the expression needs them.
  6610. SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
  6611. S.Diag(E->getLocStart(), diag::note_printf_c_str)
  6612. << "c_str()"
  6613. << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  6614. return true;
  6615. }
  6616. }
  6617. return false;
  6618. }
  6619. bool
  6620. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  6621. &FS,
  6622. const char *startSpecifier,
  6623. unsigned specifierLen) {
  6624. using namespace analyze_format_string;
  6625. using namespace analyze_printf;
  6626. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  6627. if (FS.consumesDataArgument()) {
  6628. if (atFirstArg) {
  6629. atFirstArg = false;
  6630. usesPositionalArgs = FS.usesPositionalArg();
  6631. }
  6632. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  6633. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  6634. startSpecifier, specifierLen);
  6635. return false;
  6636. }
  6637. }
  6638. // First check if the field width, precision, and conversion specifier
  6639. // have matching data arguments.
  6640. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  6641. startSpecifier, specifierLen)) {
  6642. return false;
  6643. }
  6644. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  6645. startSpecifier, specifierLen)) {
  6646. return false;
  6647. }
  6648. if (!CS.consumesDataArgument()) {
  6649. // FIXME: Technically specifying a precision or field width here
  6650. // makes no sense. Worth issuing a warning at some point.
  6651. return true;
  6652. }
  6653. // Consume the argument.
  6654. unsigned argIndex = FS.getArgIndex();
  6655. if (argIndex < NumDataArgs) {
  6656. // The check to see if the argIndex is valid will come later.
  6657. // We set the bit here because we may exit early from this
  6658. // function if we encounter some other error.
  6659. CoveredArgs.set(argIndex);
  6660. }
  6661. // FreeBSD kernel extensions.
  6662. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  6663. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  6664. // We need at least two arguments.
  6665. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  6666. return false;
  6667. // Claim the second argument.
  6668. CoveredArgs.set(argIndex + 1);
  6669. // Type check the first argument (int for %b, pointer for %D)
  6670. const Expr *Ex = getDataArg(argIndex);
  6671. const analyze_printf::ArgType &AT =
  6672. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  6673. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  6674. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  6675. EmitFormatDiagnostic(
  6676. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  6677. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  6678. << false << Ex->getSourceRange(),
  6679. Ex->getLocStart(), /*IsStringLocation*/false,
  6680. getSpecifierRange(startSpecifier, specifierLen));
  6681. // Type check the second argument (char * for both %b and %D)
  6682. Ex = getDataArg(argIndex + 1);
  6683. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  6684. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  6685. EmitFormatDiagnostic(
  6686. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  6687. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  6688. << false << Ex->getSourceRange(),
  6689. Ex->getLocStart(), /*IsStringLocation*/false,
  6690. getSpecifierRange(startSpecifier, specifierLen));
  6691. return true;
  6692. }
  6693. // Check for using an Objective-C specific conversion specifier
  6694. // in a non-ObjC literal.
  6695. if (!allowsObjCArg() && CS.isObjCArg()) {
  6696. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  6697. specifierLen);
  6698. }
  6699. // %P can only be used with os_log.
  6700. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  6701. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  6702. specifierLen);
  6703. }
  6704. // %n is not allowed with os_log.
  6705. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  6706. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  6707. getLocationOfByte(CS.getStart()),
  6708. /*IsStringLocation*/ false,
  6709. getSpecifierRange(startSpecifier, specifierLen));
  6710. return true;
  6711. }
  6712. // Only scalars are allowed for os_trace.
  6713. if (FSType == Sema::FST_OSTrace &&
  6714. (CS.getKind() == ConversionSpecifier::PArg ||
  6715. CS.getKind() == ConversionSpecifier::sArg ||
  6716. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  6717. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  6718. specifierLen);
  6719. }
  6720. // Check for use of public/private annotation outside of os_log().
  6721. if (FSType != Sema::FST_OSLog) {
  6722. if (FS.isPublic().isSet()) {
  6723. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  6724. << "public",
  6725. getLocationOfByte(FS.isPublic().getPosition()),
  6726. /*IsStringLocation*/ false,
  6727. getSpecifierRange(startSpecifier, specifierLen));
  6728. }
  6729. if (FS.isPrivate().isSet()) {
  6730. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  6731. << "private",
  6732. getLocationOfByte(FS.isPrivate().getPosition()),
  6733. /*IsStringLocation*/ false,
  6734. getSpecifierRange(startSpecifier, specifierLen));
  6735. }
  6736. }
  6737. // Check for invalid use of field width
  6738. if (!FS.hasValidFieldWidth()) {
  6739. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  6740. startSpecifier, specifierLen);
  6741. }
  6742. // Check for invalid use of precision
  6743. if (!FS.hasValidPrecision()) {
  6744. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  6745. startSpecifier, specifierLen);
  6746. }
  6747. // Precision is mandatory for %P specifier.
  6748. if (CS.getKind() == ConversionSpecifier::PArg &&
  6749. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  6750. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  6751. getLocationOfByte(startSpecifier),
  6752. /*IsStringLocation*/ false,
  6753. getSpecifierRange(startSpecifier, specifierLen));
  6754. }
  6755. // Check each flag does not conflict with any other component.
  6756. if (!FS.hasValidThousandsGroupingPrefix())
  6757. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  6758. if (!FS.hasValidLeadingZeros())
  6759. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  6760. if (!FS.hasValidPlusPrefix())
  6761. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  6762. if (!FS.hasValidSpacePrefix())
  6763. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  6764. if (!FS.hasValidAlternativeForm())
  6765. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  6766. if (!FS.hasValidLeftJustified())
  6767. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  6768. // Check that flags are not ignored by another flag
  6769. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  6770. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  6771. startSpecifier, specifierLen);
  6772. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  6773. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  6774. startSpecifier, specifierLen);
  6775. // Check the length modifier is valid with the given conversion specifier.
  6776. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  6777. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  6778. diag::warn_format_nonsensical_length);
  6779. else if (!FS.hasStandardLengthModifier())
  6780. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  6781. else if (!FS.hasStandardLengthConversionCombination())
  6782. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  6783. diag::warn_format_non_standard_conversion_spec);
  6784. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  6785. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  6786. // The remaining checks depend on the data arguments.
  6787. if (HasVAListArg)
  6788. return true;
  6789. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  6790. return false;
  6791. const Expr *Arg = getDataArg(argIndex);
  6792. if (!Arg)
  6793. return true;
  6794. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  6795. }
  6796. static bool requiresParensToAddCast(const Expr *E) {
  6797. // FIXME: We should have a general way to reason about operator
  6798. // precedence and whether parens are actually needed here.
  6799. // Take care of a few common cases where they aren't.
  6800. const Expr *Inside = E->IgnoreImpCasts();
  6801. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  6802. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  6803. switch (Inside->getStmtClass()) {
  6804. case Stmt::ArraySubscriptExprClass:
  6805. case Stmt::CallExprClass:
  6806. case Stmt::CharacterLiteralClass:
  6807. case Stmt::CXXBoolLiteralExprClass:
  6808. case Stmt::DeclRefExprClass:
  6809. case Stmt::FloatingLiteralClass:
  6810. case Stmt::IntegerLiteralClass:
  6811. case Stmt::MemberExprClass:
  6812. case Stmt::ObjCArrayLiteralClass:
  6813. case Stmt::ObjCBoolLiteralExprClass:
  6814. case Stmt::ObjCBoxedExprClass:
  6815. case Stmt::ObjCDictionaryLiteralClass:
  6816. case Stmt::ObjCEncodeExprClass:
  6817. case Stmt::ObjCIvarRefExprClass:
  6818. case Stmt::ObjCMessageExprClass:
  6819. case Stmt::ObjCPropertyRefExprClass:
  6820. case Stmt::ObjCStringLiteralClass:
  6821. case Stmt::ObjCSubscriptRefExprClass:
  6822. case Stmt::ParenExprClass:
  6823. case Stmt::StringLiteralClass:
  6824. case Stmt::UnaryOperatorClass:
  6825. return false;
  6826. default:
  6827. return true;
  6828. }
  6829. }
  6830. static std::pair<QualType, StringRef>
  6831. shouldNotPrintDirectly(const ASTContext &Context,
  6832. QualType IntendedTy,
  6833. const Expr *E) {
  6834. // Use a 'while' to peel off layers of typedefs.
  6835. QualType TyTy = IntendedTy;
  6836. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  6837. StringRef Name = UserTy->getDecl()->getName();
  6838. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  6839. .Case("CFIndex", Context.getNSIntegerType())
  6840. .Case("NSInteger", Context.getNSIntegerType())
  6841. .Case("NSUInteger", Context.getNSUIntegerType())
  6842. .Case("SInt32", Context.IntTy)
  6843. .Case("UInt32", Context.UnsignedIntTy)
  6844. .Default(QualType());
  6845. if (!CastTy.isNull())
  6846. return std::make_pair(CastTy, Name);
  6847. TyTy = UserTy->desugar();
  6848. }
  6849. // Strip parens if necessary.
  6850. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  6851. return shouldNotPrintDirectly(Context,
  6852. PE->getSubExpr()->getType(),
  6853. PE->getSubExpr());
  6854. // If this is a conditional expression, then its result type is constructed
  6855. // via usual arithmetic conversions and thus there might be no necessary
  6856. // typedef sugar there. Recurse to operands to check for NSInteger &
  6857. // Co. usage condition.
  6858. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  6859. QualType TrueTy, FalseTy;
  6860. StringRef TrueName, FalseName;
  6861. std::tie(TrueTy, TrueName) =
  6862. shouldNotPrintDirectly(Context,
  6863. CO->getTrueExpr()->getType(),
  6864. CO->getTrueExpr());
  6865. std::tie(FalseTy, FalseName) =
  6866. shouldNotPrintDirectly(Context,
  6867. CO->getFalseExpr()->getType(),
  6868. CO->getFalseExpr());
  6869. if (TrueTy == FalseTy)
  6870. return std::make_pair(TrueTy, TrueName);
  6871. else if (TrueTy.isNull())
  6872. return std::make_pair(FalseTy, FalseName);
  6873. else if (FalseTy.isNull())
  6874. return std::make_pair(TrueTy, TrueName);
  6875. }
  6876. return std::make_pair(QualType(), StringRef());
  6877. }
  6878. bool
  6879. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  6880. const char *StartSpecifier,
  6881. unsigned SpecifierLen,
  6882. const Expr *E) {
  6883. using namespace analyze_format_string;
  6884. using namespace analyze_printf;
  6885. // Now type check the data expression that matches the
  6886. // format specifier.
  6887. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  6888. if (!AT.isValid())
  6889. return true;
  6890. QualType ExprTy = E->getType();
  6891. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  6892. ExprTy = TET->getUnderlyingExpr()->getType();
  6893. }
  6894. const analyze_printf::ArgType::MatchKind Match =
  6895. AT.matchesType(S.Context, ExprTy);
  6896. bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
  6897. if (Match == analyze_printf::ArgType::Match)
  6898. return true;
  6899. // Look through argument promotions for our error message's reported type.
  6900. // This includes the integral and floating promotions, but excludes array
  6901. // and function pointer decay; seeing that an argument intended to be a
  6902. // string has type 'char [6]' is probably more confusing than 'char *'.
  6903. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  6904. if (ICE->getCastKind() == CK_IntegralCast ||
  6905. ICE->getCastKind() == CK_FloatingCast) {
  6906. E = ICE->getSubExpr();
  6907. ExprTy = E->getType();
  6908. // Check if we didn't match because of an implicit cast from a 'char'
  6909. // or 'short' to an 'int'. This is done because printf is a varargs
  6910. // function.
  6911. if (ICE->getType() == S.Context.IntTy ||
  6912. ICE->getType() == S.Context.UnsignedIntTy) {
  6913. // All further checking is done on the subexpression.
  6914. if (AT.matchesType(S.Context, ExprTy))
  6915. return true;
  6916. }
  6917. }
  6918. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  6919. // Special case for 'a', which has type 'int' in C.
  6920. // Note, however, that we do /not/ want to treat multibyte constants like
  6921. // 'MooV' as characters! This form is deprecated but still exists.
  6922. if (ExprTy == S.Context.IntTy)
  6923. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  6924. ExprTy = S.Context.CharTy;
  6925. }
  6926. // Look through enums to their underlying type.
  6927. bool IsEnum = false;
  6928. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  6929. ExprTy = EnumTy->getDecl()->getIntegerType();
  6930. IsEnum = true;
  6931. }
  6932. // %C in an Objective-C context prints a unichar, not a wchar_t.
  6933. // If the argument is an integer of some kind, believe the %C and suggest
  6934. // a cast instead of changing the conversion specifier.
  6935. QualType IntendedTy = ExprTy;
  6936. if (isObjCContext() &&
  6937. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  6938. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  6939. !ExprTy->isCharType()) {
  6940. // 'unichar' is defined as a typedef of unsigned short, but we should
  6941. // prefer using the typedef if it is visible.
  6942. IntendedTy = S.Context.UnsignedShortTy;
  6943. // While we are here, check if the value is an IntegerLiteral that happens
  6944. // to be within the valid range.
  6945. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  6946. const llvm::APInt &V = IL->getValue();
  6947. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  6948. return true;
  6949. }
  6950. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
  6951. Sema::LookupOrdinaryName);
  6952. if (S.LookupName(Result, S.getCurScope())) {
  6953. NamedDecl *ND = Result.getFoundDecl();
  6954. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  6955. if (TD->getUnderlyingType() == IntendedTy)
  6956. IntendedTy = S.Context.getTypedefType(TD);
  6957. }
  6958. }
  6959. }
  6960. // Special-case some of Darwin's platform-independence types by suggesting
  6961. // casts to primitive types that are known to be large enough.
  6962. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  6963. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  6964. QualType CastTy;
  6965. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  6966. if (!CastTy.isNull()) {
  6967. // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
  6968. // (long in ASTContext). Only complain to pedants.
  6969. if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
  6970. (AT.isSizeT() || AT.isPtrdiffT()) &&
  6971. AT.matchesType(S.Context, CastTy))
  6972. Pedantic = true;
  6973. IntendedTy = CastTy;
  6974. ShouldNotPrintDirectly = true;
  6975. }
  6976. }
  6977. // We may be able to offer a FixItHint if it is a supported type.
  6978. PrintfSpecifier fixedFS = FS;
  6979. bool Success =
  6980. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  6981. if (Success) {
  6982. // Get the fix string from the fixed format specifier
  6983. SmallString<16> buf;
  6984. llvm::raw_svector_ostream os(buf);
  6985. fixedFS.toString(os);
  6986. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  6987. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  6988. unsigned Diag =
  6989. Pedantic
  6990. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  6991. : diag::warn_format_conversion_argument_type_mismatch;
  6992. // In this case, the specifier is wrong and should be changed to match
  6993. // the argument.
  6994. EmitFormatDiagnostic(S.PDiag(Diag)
  6995. << AT.getRepresentativeTypeName(S.Context)
  6996. << IntendedTy << IsEnum << E->getSourceRange(),
  6997. E->getLocStart(),
  6998. /*IsStringLocation*/ false, SpecRange,
  6999. FixItHint::CreateReplacement(SpecRange, os.str()));
  7000. } else {
  7001. // The canonical type for formatting this value is different from the
  7002. // actual type of the expression. (This occurs, for example, with Darwin's
  7003. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  7004. // should be printed as 'long' for 64-bit compatibility.)
  7005. // Rather than emitting a normal format/argument mismatch, we want to
  7006. // add a cast to the recommended type (and correct the format string
  7007. // if necessary).
  7008. SmallString<16> CastBuf;
  7009. llvm::raw_svector_ostream CastFix(CastBuf);
  7010. CastFix << "(";
  7011. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  7012. CastFix << ")";
  7013. SmallVector<FixItHint,4> Hints;
  7014. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  7015. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  7016. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  7017. // If there's already a cast present, just replace it.
  7018. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  7019. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  7020. } else if (!requiresParensToAddCast(E)) {
  7021. // If the expression has high enough precedence,
  7022. // just write the C-style cast.
  7023. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  7024. CastFix.str()));
  7025. } else {
  7026. // Otherwise, add parens around the expression as well as the cast.
  7027. CastFix << "(";
  7028. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  7029. CastFix.str()));
  7030. SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
  7031. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  7032. }
  7033. if (ShouldNotPrintDirectly) {
  7034. // The expression has a type that should not be printed directly.
  7035. // We extract the name from the typedef because we don't want to show
  7036. // the underlying type in the diagnostic.
  7037. StringRef Name;
  7038. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  7039. Name = TypedefTy->getDecl()->getName();
  7040. else
  7041. Name = CastTyName;
  7042. unsigned Diag = Pedantic
  7043. ? diag::warn_format_argument_needs_cast_pedantic
  7044. : diag::warn_format_argument_needs_cast;
  7045. EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
  7046. << E->getSourceRange(),
  7047. E->getLocStart(), /*IsStringLocation=*/false,
  7048. SpecRange, Hints);
  7049. } else {
  7050. // In this case, the expression could be printed using a different
  7051. // specifier, but we've decided that the specifier is probably correct
  7052. // and we should cast instead. Just use the normal warning message.
  7053. EmitFormatDiagnostic(
  7054. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7055. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  7056. << E->getSourceRange(),
  7057. E->getLocStart(), /*IsStringLocation*/false,
  7058. SpecRange, Hints);
  7059. }
  7060. }
  7061. } else {
  7062. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  7063. SpecifierLen);
  7064. // Since the warning for passing non-POD types to variadic functions
  7065. // was deferred until now, we emit a warning for non-POD
  7066. // arguments here.
  7067. switch (S.isValidVarArgType(ExprTy)) {
  7068. case Sema::VAK_Valid:
  7069. case Sema::VAK_ValidInCXX11: {
  7070. unsigned Diag =
  7071. Pedantic
  7072. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7073. : diag::warn_format_conversion_argument_type_mismatch;
  7074. EmitFormatDiagnostic(
  7075. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  7076. << IsEnum << CSR << E->getSourceRange(),
  7077. E->getLocStart(), /*IsStringLocation*/ false, CSR);
  7078. break;
  7079. }
  7080. case Sema::VAK_Undefined:
  7081. case Sema::VAK_MSVCUndefined:
  7082. EmitFormatDiagnostic(
  7083. S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  7084. << S.getLangOpts().CPlusPlus11
  7085. << ExprTy
  7086. << CallType
  7087. << AT.getRepresentativeTypeName(S.Context)
  7088. << CSR
  7089. << E->getSourceRange(),
  7090. E->getLocStart(), /*IsStringLocation*/false, CSR);
  7091. checkForCStrMembers(AT, E);
  7092. break;
  7093. case Sema::VAK_Invalid:
  7094. if (ExprTy->isObjCObjectType())
  7095. EmitFormatDiagnostic(
  7096. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  7097. << S.getLangOpts().CPlusPlus11
  7098. << ExprTy
  7099. << CallType
  7100. << AT.getRepresentativeTypeName(S.Context)
  7101. << CSR
  7102. << E->getSourceRange(),
  7103. E->getLocStart(), /*IsStringLocation*/false, CSR);
  7104. else
  7105. // FIXME: If this is an initializer list, suggest removing the braces
  7106. // or inserting a cast to the target type.
  7107. S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
  7108. << isa<InitListExpr>(E) << ExprTy << CallType
  7109. << AT.getRepresentativeTypeName(S.Context)
  7110. << E->getSourceRange();
  7111. break;
  7112. }
  7113. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  7114. "format string specifier index out of range");
  7115. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  7116. }
  7117. return true;
  7118. }
  7119. //===--- CHECK: Scanf format string checking ------------------------------===//
  7120. namespace {
  7121. class CheckScanfHandler : public CheckFormatHandler {
  7122. public:
  7123. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  7124. const Expr *origFormatExpr, Sema::FormatStringType type,
  7125. unsigned firstDataArg, unsigned numDataArgs,
  7126. const char *beg, bool hasVAListArg,
  7127. ArrayRef<const Expr *> Args, unsigned formatIdx,
  7128. bool inFunctionCall, Sema::VariadicCallType CallType,
  7129. llvm::SmallBitVector &CheckedVarArgs,
  7130. UncoveredArgHandler &UncoveredArg)
  7131. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  7132. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  7133. inFunctionCall, CallType, CheckedVarArgs,
  7134. UncoveredArg) {}
  7135. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  7136. const char *startSpecifier,
  7137. unsigned specifierLen) override;
  7138. bool HandleInvalidScanfConversionSpecifier(
  7139. const analyze_scanf::ScanfSpecifier &FS,
  7140. const char *startSpecifier,
  7141. unsigned specifierLen) override;
  7142. void HandleIncompleteScanList(const char *start, const char *end) override;
  7143. };
  7144. } // namespace
  7145. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  7146. const char *end) {
  7147. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  7148. getLocationOfByte(end), /*IsStringLocation*/true,
  7149. getSpecifierRange(start, end - start));
  7150. }
  7151. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  7152. const analyze_scanf::ScanfSpecifier &FS,
  7153. const char *startSpecifier,
  7154. unsigned specifierLen) {
  7155. const analyze_scanf::ScanfConversionSpecifier &CS =
  7156. FS.getConversionSpecifier();
  7157. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  7158. getLocationOfByte(CS.getStart()),
  7159. startSpecifier, specifierLen,
  7160. CS.getStart(), CS.getLength());
  7161. }
  7162. bool CheckScanfHandler::HandleScanfSpecifier(
  7163. const analyze_scanf::ScanfSpecifier &FS,
  7164. const char *startSpecifier,
  7165. unsigned specifierLen) {
  7166. using namespace analyze_scanf;
  7167. using namespace analyze_format_string;
  7168. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  7169. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  7170. // be used to decide if we are using positional arguments consistently.
  7171. if (FS.consumesDataArgument()) {
  7172. if (atFirstArg) {
  7173. atFirstArg = false;
  7174. usesPositionalArgs = FS.usesPositionalArg();
  7175. }
  7176. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7177. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7178. startSpecifier, specifierLen);
  7179. return false;
  7180. }
  7181. }
  7182. // Check if the field with is non-zero.
  7183. const OptionalAmount &Amt = FS.getFieldWidth();
  7184. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  7185. if (Amt.getConstantAmount() == 0) {
  7186. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  7187. Amt.getConstantLength());
  7188. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  7189. getLocationOfByte(Amt.getStart()),
  7190. /*IsStringLocation*/true, R,
  7191. FixItHint::CreateRemoval(R));
  7192. }
  7193. }
  7194. if (!FS.consumesDataArgument()) {
  7195. // FIXME: Technically specifying a precision or field width here
  7196. // makes no sense. Worth issuing a warning at some point.
  7197. return true;
  7198. }
  7199. // Consume the argument.
  7200. unsigned argIndex = FS.getArgIndex();
  7201. if (argIndex < NumDataArgs) {
  7202. // The check to see if the argIndex is valid will come later.
  7203. // We set the bit here because we may exit early from this
  7204. // function if we encounter some other error.
  7205. CoveredArgs.set(argIndex);
  7206. }
  7207. // Check the length modifier is valid with the given conversion specifier.
  7208. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  7209. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7210. diag::warn_format_nonsensical_length);
  7211. else if (!FS.hasStandardLengthModifier())
  7212. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7213. else if (!FS.hasStandardLengthConversionCombination())
  7214. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7215. diag::warn_format_non_standard_conversion_spec);
  7216. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7217. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7218. // The remaining checks depend on the data arguments.
  7219. if (HasVAListArg)
  7220. return true;
  7221. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7222. return false;
  7223. // Check that the argument type matches the format specifier.
  7224. const Expr *Ex = getDataArg(argIndex);
  7225. if (!Ex)
  7226. return true;
  7227. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  7228. if (!AT.isValid()) {
  7229. return true;
  7230. }
  7231. analyze_format_string::ArgType::MatchKind Match =
  7232. AT.matchesType(S.Context, Ex->getType());
  7233. bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
  7234. if (Match == analyze_format_string::ArgType::Match)
  7235. return true;
  7236. ScanfSpecifier fixedFS = FS;
  7237. bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  7238. S.getLangOpts(), S.Context);
  7239. unsigned Diag =
  7240. Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7241. : diag::warn_format_conversion_argument_type_mismatch;
  7242. if (Success) {
  7243. // Get the fix string from the fixed format specifier.
  7244. SmallString<128> buf;
  7245. llvm::raw_svector_ostream os(buf);
  7246. fixedFS.toString(os);
  7247. EmitFormatDiagnostic(
  7248. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
  7249. << Ex->getType() << false << Ex->getSourceRange(),
  7250. Ex->getLocStart(),
  7251. /*IsStringLocation*/ false,
  7252. getSpecifierRange(startSpecifier, specifierLen),
  7253. FixItHint::CreateReplacement(
  7254. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  7255. } else {
  7256. EmitFormatDiagnostic(S.PDiag(Diag)
  7257. << AT.getRepresentativeTypeName(S.Context)
  7258. << Ex->getType() << false << Ex->getSourceRange(),
  7259. Ex->getLocStart(),
  7260. /*IsStringLocation*/ false,
  7261. getSpecifierRange(startSpecifier, specifierLen));
  7262. }
  7263. return true;
  7264. }
  7265. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  7266. const Expr *OrigFormatExpr,
  7267. ArrayRef<const Expr *> Args,
  7268. bool HasVAListArg, unsigned format_idx,
  7269. unsigned firstDataArg,
  7270. Sema::FormatStringType Type,
  7271. bool inFunctionCall,
  7272. Sema::VariadicCallType CallType,
  7273. llvm::SmallBitVector &CheckedVarArgs,
  7274. UncoveredArgHandler &UncoveredArg) {
  7275. // CHECK: is the format string a wide literal?
  7276. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  7277. CheckFormatHandler::EmitFormatDiagnostic(
  7278. S, inFunctionCall, Args[format_idx],
  7279. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  7280. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  7281. return;
  7282. }
  7283. // Str - The format string. NOTE: this is NOT null-terminated!
  7284. StringRef StrRef = FExpr->getString();
  7285. const char *Str = StrRef.data();
  7286. // Account for cases where the string literal is truncated in a declaration.
  7287. const ConstantArrayType *T =
  7288. S.Context.getAsConstantArrayType(FExpr->getType());
  7289. assert(T && "String literal not of constant array type!");
  7290. size_t TypeSize = T->getSize().getZExtValue();
  7291. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7292. const unsigned numDataArgs = Args.size() - firstDataArg;
  7293. // Emit a warning if the string literal is truncated and does not contain an
  7294. // embedded null character.
  7295. if (TypeSize <= StrRef.size() &&
  7296. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  7297. CheckFormatHandler::EmitFormatDiagnostic(
  7298. S, inFunctionCall, Args[format_idx],
  7299. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  7300. FExpr->getLocStart(),
  7301. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  7302. return;
  7303. }
  7304. // CHECK: empty format string?
  7305. if (StrLen == 0 && numDataArgs > 0) {
  7306. CheckFormatHandler::EmitFormatDiagnostic(
  7307. S, inFunctionCall, Args[format_idx],
  7308. S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  7309. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  7310. return;
  7311. }
  7312. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  7313. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  7314. Type == Sema::FST_OSTrace) {
  7315. CheckPrintfHandler H(
  7316. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  7317. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  7318. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  7319. CheckedVarArgs, UncoveredArg);
  7320. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  7321. S.getLangOpts(),
  7322. S.Context.getTargetInfo(),
  7323. Type == Sema::FST_FreeBSDKPrintf))
  7324. H.DoneProcessing();
  7325. } else if (Type == Sema::FST_Scanf) {
  7326. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  7327. numDataArgs, Str, HasVAListArg, Args, format_idx,
  7328. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  7329. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  7330. S.getLangOpts(),
  7331. S.Context.getTargetInfo()))
  7332. H.DoneProcessing();
  7333. } // TODO: handle other formats
  7334. }
  7335. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  7336. // Str - The format string. NOTE: this is NOT null-terminated!
  7337. StringRef StrRef = FExpr->getString();
  7338. const char *Str = StrRef.data();
  7339. // Account for cases where the string literal is truncated in a declaration.
  7340. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  7341. assert(T && "String literal not of constant array type!");
  7342. size_t TypeSize = T->getSize().getZExtValue();
  7343. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7344. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  7345. getLangOpts(),
  7346. Context.getTargetInfo());
  7347. }
  7348. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  7349. // Returns the related absolute value function that is larger, of 0 if one
  7350. // does not exist.
  7351. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  7352. switch (AbsFunction) {
  7353. default:
  7354. return 0;
  7355. case Builtin::BI__builtin_abs:
  7356. return Builtin::BI__builtin_labs;
  7357. case Builtin::BI__builtin_labs:
  7358. return Builtin::BI__builtin_llabs;
  7359. case Builtin::BI__builtin_llabs:
  7360. return 0;
  7361. case Builtin::BI__builtin_fabsf:
  7362. return Builtin::BI__builtin_fabs;
  7363. case Builtin::BI__builtin_fabs:
  7364. return Builtin::BI__builtin_fabsl;
  7365. case Builtin::BI__builtin_fabsl:
  7366. return 0;
  7367. case Builtin::BI__builtin_cabsf:
  7368. return Builtin::BI__builtin_cabs;
  7369. case Builtin::BI__builtin_cabs:
  7370. return Builtin::BI__builtin_cabsl;
  7371. case Builtin::BI__builtin_cabsl:
  7372. return 0;
  7373. case Builtin::BIabs:
  7374. return Builtin::BIlabs;
  7375. case Builtin::BIlabs:
  7376. return Builtin::BIllabs;
  7377. case Builtin::BIllabs:
  7378. return 0;
  7379. case Builtin::BIfabsf:
  7380. return Builtin::BIfabs;
  7381. case Builtin::BIfabs:
  7382. return Builtin::BIfabsl;
  7383. case Builtin::BIfabsl:
  7384. return 0;
  7385. case Builtin::BIcabsf:
  7386. return Builtin::BIcabs;
  7387. case Builtin::BIcabs:
  7388. return Builtin::BIcabsl;
  7389. case Builtin::BIcabsl:
  7390. return 0;
  7391. }
  7392. }
  7393. // Returns the argument type of the absolute value function.
  7394. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  7395. unsigned AbsType) {
  7396. if (AbsType == 0)
  7397. return QualType();
  7398. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  7399. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  7400. if (Error != ASTContext::GE_None)
  7401. return QualType();
  7402. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  7403. if (!FT)
  7404. return QualType();
  7405. if (FT->getNumParams() != 1)
  7406. return QualType();
  7407. return FT->getParamType(0);
  7408. }
  7409. // Returns the best absolute value function, or zero, based on type and
  7410. // current absolute value function.
  7411. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  7412. unsigned AbsFunctionKind) {
  7413. unsigned BestKind = 0;
  7414. uint64_t ArgSize = Context.getTypeSize(ArgType);
  7415. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  7416. Kind = getLargerAbsoluteValueFunction(Kind)) {
  7417. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  7418. if (Context.getTypeSize(ParamType) >= ArgSize) {
  7419. if (BestKind == 0)
  7420. BestKind = Kind;
  7421. else if (Context.hasSameType(ParamType, ArgType)) {
  7422. BestKind = Kind;
  7423. break;
  7424. }
  7425. }
  7426. }
  7427. return BestKind;
  7428. }
  7429. enum AbsoluteValueKind {
  7430. AVK_Integer,
  7431. AVK_Floating,
  7432. AVK_Complex
  7433. };
  7434. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  7435. if (T->isIntegralOrEnumerationType())
  7436. return AVK_Integer;
  7437. if (T->isRealFloatingType())
  7438. return AVK_Floating;
  7439. if (T->isAnyComplexType())
  7440. return AVK_Complex;
  7441. llvm_unreachable("Type not integer, floating, or complex");
  7442. }
  7443. // Changes the absolute value function to a different type. Preserves whether
  7444. // the function is a builtin.
  7445. static unsigned changeAbsFunction(unsigned AbsKind,
  7446. AbsoluteValueKind ValueKind) {
  7447. switch (ValueKind) {
  7448. case AVK_Integer:
  7449. switch (AbsKind) {
  7450. default:
  7451. return 0;
  7452. case Builtin::BI__builtin_fabsf:
  7453. case Builtin::BI__builtin_fabs:
  7454. case Builtin::BI__builtin_fabsl:
  7455. case Builtin::BI__builtin_cabsf:
  7456. case Builtin::BI__builtin_cabs:
  7457. case Builtin::BI__builtin_cabsl:
  7458. return Builtin::BI__builtin_abs;
  7459. case Builtin::BIfabsf:
  7460. case Builtin::BIfabs:
  7461. case Builtin::BIfabsl:
  7462. case Builtin::BIcabsf:
  7463. case Builtin::BIcabs:
  7464. case Builtin::BIcabsl:
  7465. return Builtin::BIabs;
  7466. }
  7467. case AVK_Floating:
  7468. switch (AbsKind) {
  7469. default:
  7470. return 0;
  7471. case Builtin::BI__builtin_abs:
  7472. case Builtin::BI__builtin_labs:
  7473. case Builtin::BI__builtin_llabs:
  7474. case Builtin::BI__builtin_cabsf:
  7475. case Builtin::BI__builtin_cabs:
  7476. case Builtin::BI__builtin_cabsl:
  7477. return Builtin::BI__builtin_fabsf;
  7478. case Builtin::BIabs:
  7479. case Builtin::BIlabs:
  7480. case Builtin::BIllabs:
  7481. case Builtin::BIcabsf:
  7482. case Builtin::BIcabs:
  7483. case Builtin::BIcabsl:
  7484. return Builtin::BIfabsf;
  7485. }
  7486. case AVK_Complex:
  7487. switch (AbsKind) {
  7488. default:
  7489. return 0;
  7490. case Builtin::BI__builtin_abs:
  7491. case Builtin::BI__builtin_labs:
  7492. case Builtin::BI__builtin_llabs:
  7493. case Builtin::BI__builtin_fabsf:
  7494. case Builtin::BI__builtin_fabs:
  7495. case Builtin::BI__builtin_fabsl:
  7496. return Builtin::BI__builtin_cabsf;
  7497. case Builtin::BIabs:
  7498. case Builtin::BIlabs:
  7499. case Builtin::BIllabs:
  7500. case Builtin::BIfabsf:
  7501. case Builtin::BIfabs:
  7502. case Builtin::BIfabsl:
  7503. return Builtin::BIcabsf;
  7504. }
  7505. }
  7506. llvm_unreachable("Unable to convert function");
  7507. }
  7508. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  7509. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  7510. if (!FnInfo)
  7511. return 0;
  7512. switch (FDecl->getBuiltinID()) {
  7513. default:
  7514. return 0;
  7515. case Builtin::BI__builtin_abs:
  7516. case Builtin::BI__builtin_fabs:
  7517. case Builtin::BI__builtin_fabsf:
  7518. case Builtin::BI__builtin_fabsl:
  7519. case Builtin::BI__builtin_labs:
  7520. case Builtin::BI__builtin_llabs:
  7521. case Builtin::BI__builtin_cabs:
  7522. case Builtin::BI__builtin_cabsf:
  7523. case Builtin::BI__builtin_cabsl:
  7524. case Builtin::BIabs:
  7525. case Builtin::BIlabs:
  7526. case Builtin::BIllabs:
  7527. case Builtin::BIfabs:
  7528. case Builtin::BIfabsf:
  7529. case Builtin::BIfabsl:
  7530. case Builtin::BIcabs:
  7531. case Builtin::BIcabsf:
  7532. case Builtin::BIcabsl:
  7533. return FDecl->getBuiltinID();
  7534. }
  7535. llvm_unreachable("Unknown Builtin type");
  7536. }
  7537. // If the replacement is valid, emit a note with replacement function.
  7538. // Additionally, suggest including the proper header if not already included.
  7539. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  7540. unsigned AbsKind, QualType ArgType) {
  7541. bool EmitHeaderHint = true;
  7542. const char *HeaderName = nullptr;
  7543. const char *FunctionName = nullptr;
  7544. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  7545. FunctionName = "std::abs";
  7546. if (ArgType->isIntegralOrEnumerationType()) {
  7547. HeaderName = "cstdlib";
  7548. } else if (ArgType->isRealFloatingType()) {
  7549. HeaderName = "cmath";
  7550. } else {
  7551. llvm_unreachable("Invalid Type");
  7552. }
  7553. // Lookup all std::abs
  7554. if (NamespaceDecl *Std = S.getStdNamespace()) {
  7555. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  7556. R.suppressDiagnostics();
  7557. S.LookupQualifiedName(R, Std);
  7558. for (const auto *I : R) {
  7559. const FunctionDecl *FDecl = nullptr;
  7560. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  7561. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  7562. } else {
  7563. FDecl = dyn_cast<FunctionDecl>(I);
  7564. }
  7565. if (!FDecl)
  7566. continue;
  7567. // Found std::abs(), check that they are the right ones.
  7568. if (FDecl->getNumParams() != 1)
  7569. continue;
  7570. // Check that the parameter type can handle the argument.
  7571. QualType ParamType = FDecl->getParamDecl(0)->getType();
  7572. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  7573. S.Context.getTypeSize(ArgType) <=
  7574. S.Context.getTypeSize(ParamType)) {
  7575. // Found a function, don't need the header hint.
  7576. EmitHeaderHint = false;
  7577. break;
  7578. }
  7579. }
  7580. }
  7581. } else {
  7582. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  7583. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  7584. if (HeaderName) {
  7585. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  7586. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  7587. R.suppressDiagnostics();
  7588. S.LookupName(R, S.getCurScope());
  7589. if (R.isSingleResult()) {
  7590. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  7591. if (FD && FD->getBuiltinID() == AbsKind) {
  7592. EmitHeaderHint = false;
  7593. } else {
  7594. return;
  7595. }
  7596. } else if (!R.empty()) {
  7597. return;
  7598. }
  7599. }
  7600. }
  7601. S.Diag(Loc, diag::note_replace_abs_function)
  7602. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  7603. if (!HeaderName)
  7604. return;
  7605. if (!EmitHeaderHint)
  7606. return;
  7607. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  7608. << FunctionName;
  7609. }
  7610. template <std::size_t StrLen>
  7611. static bool IsStdFunction(const FunctionDecl *FDecl,
  7612. const char (&Str)[StrLen]) {
  7613. if (!FDecl)
  7614. return false;
  7615. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  7616. return false;
  7617. if (!FDecl->isInStdNamespace())
  7618. return false;
  7619. return true;
  7620. }
  7621. // Warn when using the wrong abs() function.
  7622. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  7623. const FunctionDecl *FDecl) {
  7624. if (Call->getNumArgs() != 1)
  7625. return;
  7626. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  7627. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  7628. if (AbsKind == 0 && !IsStdAbs)
  7629. return;
  7630. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  7631. QualType ParamType = Call->getArg(0)->getType();
  7632. // Unsigned types cannot be negative. Suggest removing the absolute value
  7633. // function call.
  7634. if (ArgType->isUnsignedIntegerType()) {
  7635. const char *FunctionName =
  7636. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  7637. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  7638. Diag(Call->getExprLoc(), diag::note_remove_abs)
  7639. << FunctionName
  7640. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  7641. return;
  7642. }
  7643. // Taking the absolute value of a pointer is very suspicious, they probably
  7644. // wanted to index into an array, dereference a pointer, call a function, etc.
  7645. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  7646. unsigned DiagType = 0;
  7647. if (ArgType->isFunctionType())
  7648. DiagType = 1;
  7649. else if (ArgType->isArrayType())
  7650. DiagType = 2;
  7651. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  7652. return;
  7653. }
  7654. // std::abs has overloads which prevent most of the absolute value problems
  7655. // from occurring.
  7656. if (IsStdAbs)
  7657. return;
  7658. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  7659. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  7660. // The argument and parameter are the same kind. Check if they are the right
  7661. // size.
  7662. if (ArgValueKind == ParamValueKind) {
  7663. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  7664. return;
  7665. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  7666. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  7667. << FDecl << ArgType << ParamType;
  7668. if (NewAbsKind == 0)
  7669. return;
  7670. emitReplacement(*this, Call->getExprLoc(),
  7671. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  7672. return;
  7673. }
  7674. // ArgValueKind != ParamValueKind
  7675. // The wrong type of absolute value function was used. Attempt to find the
  7676. // proper one.
  7677. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  7678. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  7679. if (NewAbsKind == 0)
  7680. return;
  7681. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  7682. << FDecl << ParamValueKind << ArgValueKind;
  7683. emitReplacement(*this, Call->getExprLoc(),
  7684. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  7685. }
  7686. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  7687. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  7688. const FunctionDecl *FDecl) {
  7689. if (!Call || !FDecl) return;
  7690. // Ignore template specializations and macros.
  7691. if (inTemplateInstantiation()) return;
  7692. if (Call->getExprLoc().isMacroID()) return;
  7693. // Only care about the one template argument, two function parameter std::max
  7694. if (Call->getNumArgs() != 2) return;
  7695. if (!IsStdFunction(FDecl, "max")) return;
  7696. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  7697. if (!ArgList) return;
  7698. if (ArgList->size() != 1) return;
  7699. // Check that template type argument is unsigned integer.
  7700. const auto& TA = ArgList->get(0);
  7701. if (TA.getKind() != TemplateArgument::Type) return;
  7702. QualType ArgType = TA.getAsType();
  7703. if (!ArgType->isUnsignedIntegerType()) return;
  7704. // See if either argument is a literal zero.
  7705. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  7706. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  7707. if (!MTE) return false;
  7708. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  7709. if (!Num) return false;
  7710. if (Num->getValue() != 0) return false;
  7711. return true;
  7712. };
  7713. const Expr *FirstArg = Call->getArg(0);
  7714. const Expr *SecondArg = Call->getArg(1);
  7715. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  7716. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  7717. // Only warn when exactly one argument is zero.
  7718. if (IsFirstArgZero == IsSecondArgZero) return;
  7719. SourceRange FirstRange = FirstArg->getSourceRange();
  7720. SourceRange SecondRange = SecondArg->getSourceRange();
  7721. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  7722. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  7723. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  7724. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  7725. SourceRange RemovalRange;
  7726. if (IsFirstArgZero) {
  7727. RemovalRange = SourceRange(FirstRange.getBegin(),
  7728. SecondRange.getBegin().getLocWithOffset(-1));
  7729. } else {
  7730. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  7731. SecondRange.getEnd());
  7732. }
  7733. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  7734. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  7735. << FixItHint::CreateRemoval(RemovalRange);
  7736. }
  7737. //===--- CHECK: Standard memory functions ---------------------------------===//
  7738. /// Takes the expression passed to the size_t parameter of functions
  7739. /// such as memcmp, strncat, etc and warns if it's a comparison.
  7740. ///
  7741. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  7742. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  7743. IdentifierInfo *FnName,
  7744. SourceLocation FnLoc,
  7745. SourceLocation RParenLoc) {
  7746. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  7747. if (!Size)
  7748. return false;
  7749. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  7750. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  7751. return false;
  7752. SourceRange SizeRange = Size->getSourceRange();
  7753. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  7754. << SizeRange << FnName;
  7755. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  7756. << FnName << FixItHint::CreateInsertion(
  7757. S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
  7758. << FixItHint::CreateRemoval(RParenLoc);
  7759. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  7760. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  7761. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  7762. ")");
  7763. return true;
  7764. }
  7765. /// Determine whether the given type is or contains a dynamic class type
  7766. /// (e.g., whether it has a vtable).
  7767. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  7768. bool &IsContained) {
  7769. // Look through array types while ignoring qualifiers.
  7770. const Type *Ty = T->getBaseElementTypeUnsafe();
  7771. IsContained = false;
  7772. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  7773. RD = RD ? RD->getDefinition() : nullptr;
  7774. if (!RD || RD->isInvalidDecl())
  7775. return nullptr;
  7776. if (RD->isDynamicClass())
  7777. return RD;
  7778. // Check all the fields. If any bases were dynamic, the class is dynamic.
  7779. // It's impossible for a class to transitively contain itself by value, so
  7780. // infinite recursion is impossible.
  7781. for (auto *FD : RD->fields()) {
  7782. bool SubContained;
  7783. if (const CXXRecordDecl *ContainedRD =
  7784. getContainedDynamicClass(FD->getType(), SubContained)) {
  7785. IsContained = true;
  7786. return ContainedRD;
  7787. }
  7788. }
  7789. return nullptr;
  7790. }
  7791. static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
  7792. if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  7793. if (Unary->getKind() == UETT_SizeOf)
  7794. return Unary;
  7795. return nullptr;
  7796. }
  7797. /// If E is a sizeof expression, returns its argument expression,
  7798. /// otherwise returns NULL.
  7799. static const Expr *getSizeOfExprArg(const Expr *E) {
  7800. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  7801. if (!SizeOf->isArgumentType())
  7802. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  7803. return nullptr;
  7804. }
  7805. /// If E is a sizeof expression, returns its argument type.
  7806. static QualType getSizeOfArgType(const Expr *E) {
  7807. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  7808. return SizeOf->getTypeOfArgument();
  7809. return QualType();
  7810. }
  7811. namespace {
  7812. struct SearchNonTrivialToInitializeField
  7813. : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
  7814. using Super =
  7815. DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
  7816. SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
  7817. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
  7818. SourceLocation SL) {
  7819. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  7820. asDerived().visitArray(PDIK, AT, SL);
  7821. return;
  7822. }
  7823. Super::visitWithKind(PDIK, FT, SL);
  7824. }
  7825. void visitARCStrong(QualType FT, SourceLocation SL) {
  7826. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  7827. }
  7828. void visitARCWeak(QualType FT, SourceLocation SL) {
  7829. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  7830. }
  7831. void visitStruct(QualType FT, SourceLocation SL) {
  7832. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  7833. visit(FD->getType(), FD->getLocation());
  7834. }
  7835. void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
  7836. const ArrayType *AT, SourceLocation SL) {
  7837. visit(getContext().getBaseElementType(AT), SL);
  7838. }
  7839. void visitTrivial(QualType FT, SourceLocation SL) {}
  7840. static void diag(QualType RT, const Expr *E, Sema &S) {
  7841. SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
  7842. }
  7843. ASTContext &getContext() { return S.getASTContext(); }
  7844. const Expr *E;
  7845. Sema &S;
  7846. };
  7847. struct SearchNonTrivialToCopyField
  7848. : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
  7849. using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
  7850. SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
  7851. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
  7852. SourceLocation SL) {
  7853. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  7854. asDerived().visitArray(PCK, AT, SL);
  7855. return;
  7856. }
  7857. Super::visitWithKind(PCK, FT, SL);
  7858. }
  7859. void visitARCStrong(QualType FT, SourceLocation SL) {
  7860. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  7861. }
  7862. void visitARCWeak(QualType FT, SourceLocation SL) {
  7863. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  7864. }
  7865. void visitStruct(QualType FT, SourceLocation SL) {
  7866. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  7867. visit(FD->getType(), FD->getLocation());
  7868. }
  7869. void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
  7870. SourceLocation SL) {
  7871. visit(getContext().getBaseElementType(AT), SL);
  7872. }
  7873. void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
  7874. SourceLocation SL) {}
  7875. void visitTrivial(QualType FT, SourceLocation SL) {}
  7876. void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
  7877. static void diag(QualType RT, const Expr *E, Sema &S) {
  7878. SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
  7879. }
  7880. ASTContext &getContext() { return S.getASTContext(); }
  7881. const Expr *E;
  7882. Sema &S;
  7883. };
  7884. }
  7885. /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
  7886. static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
  7887. SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
  7888. if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
  7889. if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
  7890. return false;
  7891. return doesExprLikelyComputeSize(BO->getLHS()) ||
  7892. doesExprLikelyComputeSize(BO->getRHS());
  7893. }
  7894. return getAsSizeOfExpr(SizeofExpr) != nullptr;
  7895. }
  7896. /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
  7897. ///
  7898. /// \code
  7899. /// #define MACRO 0
  7900. /// foo(MACRO);
  7901. /// foo(0);
  7902. /// \endcode
  7903. ///
  7904. /// This should return true for the first call to foo, but not for the second
  7905. /// (regardless of whether foo is a macro or function).
  7906. static bool isArgumentExpandedFromMacro(SourceManager &SM,
  7907. SourceLocation CallLoc,
  7908. SourceLocation ArgLoc) {
  7909. if (!CallLoc.isMacroID())
  7910. return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
  7911. return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
  7912. SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
  7913. }
  7914. /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
  7915. /// last two arguments transposed.
  7916. static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
  7917. if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
  7918. return;
  7919. const Expr *SizeArg =
  7920. Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
  7921. auto isLiteralZero = [](const Expr *E) {
  7922. return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
  7923. };
  7924. // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
  7925. SourceLocation CallLoc = Call->getRParenLoc();
  7926. SourceManager &SM = S.getSourceManager();
  7927. if (isLiteralZero(SizeArg) &&
  7928. !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
  7929. SourceLocation DiagLoc = SizeArg->getExprLoc();
  7930. // Some platforms #define bzero to __builtin_memset. See if this is the
  7931. // case, and if so, emit a better diagnostic.
  7932. if (BId == Builtin::BIbzero ||
  7933. (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
  7934. CallLoc, SM, S.getLangOpts()) == "bzero")) {
  7935. S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
  7936. S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
  7937. } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
  7938. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
  7939. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
  7940. }
  7941. return;
  7942. }
  7943. // If the second argument to a memset is a sizeof expression and the third
  7944. // isn't, this is also likely an error. This should catch
  7945. // 'memset(buf, sizeof(buf), 0xff)'.
  7946. if (BId == Builtin::BImemset &&
  7947. doesExprLikelyComputeSize(Call->getArg(1)) &&
  7948. !doesExprLikelyComputeSize(Call->getArg(2))) {
  7949. SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
  7950. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
  7951. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
  7952. return;
  7953. }
  7954. }
  7955. /// Check for dangerous or invalid arguments to memset().
  7956. ///
  7957. /// This issues warnings on known problematic, dangerous or unspecified
  7958. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  7959. /// function calls.
  7960. ///
  7961. /// \param Call The call expression to diagnose.
  7962. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  7963. unsigned BId,
  7964. IdentifierInfo *FnName) {
  7965. assert(BId != 0);
  7966. // It is possible to have a non-standard definition of memset. Validate
  7967. // we have enough arguments, and if not, abort further checking.
  7968. unsigned ExpectedNumArgs =
  7969. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  7970. if (Call->getNumArgs() < ExpectedNumArgs)
  7971. return;
  7972. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  7973. BId == Builtin::BIstrndup ? 1 : 2);
  7974. unsigned LenArg =
  7975. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  7976. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  7977. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  7978. Call->getLocStart(), Call->getRParenLoc()))
  7979. return;
  7980. // Catch cases like 'memset(buf, sizeof(buf), 0)'.
  7981. CheckMemaccessSize(*this, BId, Call);
  7982. // We have special checking when the length is a sizeof expression.
  7983. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  7984. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  7985. llvm::FoldingSetNodeID SizeOfArgID;
  7986. // Although widely used, 'bzero' is not a standard function. Be more strict
  7987. // with the argument types before allowing diagnostics and only allow the
  7988. // form bzero(ptr, sizeof(...)).
  7989. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  7990. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  7991. return;
  7992. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  7993. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  7994. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  7995. QualType DestTy = Dest->getType();
  7996. QualType PointeeTy;
  7997. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  7998. PointeeTy = DestPtrTy->getPointeeType();
  7999. // Never warn about void type pointers. This can be used to suppress
  8000. // false positives.
  8001. if (PointeeTy->isVoidType())
  8002. continue;
  8003. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  8004. // actually comparing the expressions for equality. Because computing the
  8005. // expression IDs can be expensive, we only do this if the diagnostic is
  8006. // enabled.
  8007. if (SizeOfArg &&
  8008. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  8009. SizeOfArg->getExprLoc())) {
  8010. // We only compute IDs for expressions if the warning is enabled, and
  8011. // cache the sizeof arg's ID.
  8012. if (SizeOfArgID == llvm::FoldingSetNodeID())
  8013. SizeOfArg->Profile(SizeOfArgID, Context, true);
  8014. llvm::FoldingSetNodeID DestID;
  8015. Dest->Profile(DestID, Context, true);
  8016. if (DestID == SizeOfArgID) {
  8017. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  8018. // over sizeof(src) as well.
  8019. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  8020. StringRef ReadableName = FnName->getName();
  8021. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  8022. if (UnaryOp->getOpcode() == UO_AddrOf)
  8023. ActionIdx = 1; // If its an address-of operator, just remove it.
  8024. if (!PointeeTy->isIncompleteType() &&
  8025. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  8026. ActionIdx = 2; // If the pointee's size is sizeof(char),
  8027. // suggest an explicit length.
  8028. // If the function is defined as a builtin macro, do not show macro
  8029. // expansion.
  8030. SourceLocation SL = SizeOfArg->getExprLoc();
  8031. SourceRange DSR = Dest->getSourceRange();
  8032. SourceRange SSR = SizeOfArg->getSourceRange();
  8033. SourceManager &SM = getSourceManager();
  8034. if (SM.isMacroArgExpansion(SL)) {
  8035. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  8036. SL = SM.getSpellingLoc(SL);
  8037. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  8038. SM.getSpellingLoc(DSR.getEnd()));
  8039. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  8040. SM.getSpellingLoc(SSR.getEnd()));
  8041. }
  8042. DiagRuntimeBehavior(SL, SizeOfArg,
  8043. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  8044. << ReadableName
  8045. << PointeeTy
  8046. << DestTy
  8047. << DSR
  8048. << SSR);
  8049. DiagRuntimeBehavior(SL, SizeOfArg,
  8050. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  8051. << ActionIdx
  8052. << SSR);
  8053. break;
  8054. }
  8055. }
  8056. // Also check for cases where the sizeof argument is the exact same
  8057. // type as the memory argument, and where it points to a user-defined
  8058. // record type.
  8059. if (SizeOfArgTy != QualType()) {
  8060. if (PointeeTy->isRecordType() &&
  8061. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  8062. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  8063. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  8064. << FnName << SizeOfArgTy << ArgIdx
  8065. << PointeeTy << Dest->getSourceRange()
  8066. << LenExpr->getSourceRange());
  8067. break;
  8068. }
  8069. }
  8070. } else if (DestTy->isArrayType()) {
  8071. PointeeTy = DestTy;
  8072. }
  8073. if (PointeeTy == QualType())
  8074. continue;
  8075. // Always complain about dynamic classes.
  8076. bool IsContained;
  8077. if (const CXXRecordDecl *ContainedRD =
  8078. getContainedDynamicClass(PointeeTy, IsContained)) {
  8079. unsigned OperationType = 0;
  8080. // "overwritten" if we're warning about the destination for any call
  8081. // but memcmp; otherwise a verb appropriate to the call.
  8082. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  8083. if (BId == Builtin::BImemcpy)
  8084. OperationType = 1;
  8085. else if(BId == Builtin::BImemmove)
  8086. OperationType = 2;
  8087. else if (BId == Builtin::BImemcmp)
  8088. OperationType = 3;
  8089. }
  8090. DiagRuntimeBehavior(
  8091. Dest->getExprLoc(), Dest,
  8092. PDiag(diag::warn_dyn_class_memaccess)
  8093. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  8094. << FnName << IsContained << ContainedRD << OperationType
  8095. << Call->getCallee()->getSourceRange());
  8096. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  8097. BId != Builtin::BImemset)
  8098. DiagRuntimeBehavior(
  8099. Dest->getExprLoc(), Dest,
  8100. PDiag(diag::warn_arc_object_memaccess)
  8101. << ArgIdx << FnName << PointeeTy
  8102. << Call->getCallee()->getSourceRange());
  8103. else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
  8104. if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
  8105. RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
  8106. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8107. PDiag(diag::warn_cstruct_memaccess)
  8108. << ArgIdx << FnName << PointeeTy << 0);
  8109. SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
  8110. } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  8111. RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
  8112. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8113. PDiag(diag::warn_cstruct_memaccess)
  8114. << ArgIdx << FnName << PointeeTy << 1);
  8115. SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
  8116. } else {
  8117. continue;
  8118. }
  8119. } else
  8120. continue;
  8121. DiagRuntimeBehavior(
  8122. Dest->getExprLoc(), Dest,
  8123. PDiag(diag::note_bad_memaccess_silence)
  8124. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  8125. break;
  8126. }
  8127. }
  8128. // A little helper routine: ignore addition and subtraction of integer literals.
  8129. // This intentionally does not ignore all integer constant expressions because
  8130. // we don't want to remove sizeof().
  8131. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  8132. Ex = Ex->IgnoreParenCasts();
  8133. while (true) {
  8134. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  8135. if (!BO || !BO->isAdditiveOp())
  8136. break;
  8137. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  8138. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  8139. if (isa<IntegerLiteral>(RHS))
  8140. Ex = LHS;
  8141. else if (isa<IntegerLiteral>(LHS))
  8142. Ex = RHS;
  8143. else
  8144. break;
  8145. }
  8146. return Ex;
  8147. }
  8148. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  8149. ASTContext &Context) {
  8150. // Only handle constant-sized or VLAs, but not flexible members.
  8151. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  8152. // Only issue the FIXIT for arrays of size > 1.
  8153. if (CAT->getSize().getSExtValue() <= 1)
  8154. return false;
  8155. } else if (!Ty->isVariableArrayType()) {
  8156. return false;
  8157. }
  8158. return true;
  8159. }
  8160. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  8161. // be the size of the source, instead of the destination.
  8162. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  8163. IdentifierInfo *FnName) {
  8164. // Don't crash if the user has the wrong number of arguments
  8165. unsigned NumArgs = Call->getNumArgs();
  8166. if ((NumArgs != 3) && (NumArgs != 4))
  8167. return;
  8168. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  8169. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  8170. const Expr *CompareWithSrc = nullptr;
  8171. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  8172. Call->getLocStart(), Call->getRParenLoc()))
  8173. return;
  8174. // Look for 'strlcpy(dst, x, sizeof(x))'
  8175. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  8176. CompareWithSrc = Ex;
  8177. else {
  8178. // Look for 'strlcpy(dst, x, strlen(x))'
  8179. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  8180. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  8181. SizeCall->getNumArgs() == 1)
  8182. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  8183. }
  8184. }
  8185. if (!CompareWithSrc)
  8186. return;
  8187. // Determine if the argument to sizeof/strlen is equal to the source
  8188. // argument. In principle there's all kinds of things you could do
  8189. // here, for instance creating an == expression and evaluating it with
  8190. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  8191. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  8192. if (!SrcArgDRE)
  8193. return;
  8194. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  8195. if (!CompareWithSrcDRE ||
  8196. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  8197. return;
  8198. const Expr *OriginalSizeArg = Call->getArg(2);
  8199. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  8200. << OriginalSizeArg->getSourceRange() << FnName;
  8201. // Output a FIXIT hint if the destination is an array (rather than a
  8202. // pointer to an array). This could be enhanced to handle some
  8203. // pointers if we know the actual size, like if DstArg is 'array+2'
  8204. // we could say 'sizeof(array)-2'.
  8205. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  8206. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  8207. return;
  8208. SmallString<128> sizeString;
  8209. llvm::raw_svector_ostream OS(sizeString);
  8210. OS << "sizeof(";
  8211. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8212. OS << ")";
  8213. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  8214. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  8215. OS.str());
  8216. }
  8217. /// Check if two expressions refer to the same declaration.
  8218. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  8219. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  8220. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  8221. return D1->getDecl() == D2->getDecl();
  8222. return false;
  8223. }
  8224. static const Expr *getStrlenExprArg(const Expr *E) {
  8225. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8226. const FunctionDecl *FD = CE->getDirectCallee();
  8227. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  8228. return nullptr;
  8229. return CE->getArg(0)->IgnoreParenCasts();
  8230. }
  8231. return nullptr;
  8232. }
  8233. // Warn on anti-patterns as the 'size' argument to strncat.
  8234. // The correct size argument should look like following:
  8235. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  8236. void Sema::CheckStrncatArguments(const CallExpr *CE,
  8237. IdentifierInfo *FnName) {
  8238. // Don't crash if the user has the wrong number of arguments.
  8239. if (CE->getNumArgs() < 3)
  8240. return;
  8241. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  8242. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  8243. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  8244. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
  8245. CE->getRParenLoc()))
  8246. return;
  8247. // Identify common expressions, which are wrongly used as the size argument
  8248. // to strncat and may lead to buffer overflows.
  8249. unsigned PatternType = 0;
  8250. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  8251. // - sizeof(dst)
  8252. if (referToTheSameDecl(SizeOfArg, DstArg))
  8253. PatternType = 1;
  8254. // - sizeof(src)
  8255. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  8256. PatternType = 2;
  8257. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  8258. if (BE->getOpcode() == BO_Sub) {
  8259. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  8260. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  8261. // - sizeof(dst) - strlen(dst)
  8262. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  8263. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  8264. PatternType = 1;
  8265. // - sizeof(src) - (anything)
  8266. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  8267. PatternType = 2;
  8268. }
  8269. }
  8270. if (PatternType == 0)
  8271. return;
  8272. // Generate the diagnostic.
  8273. SourceLocation SL = LenArg->getLocStart();
  8274. SourceRange SR = LenArg->getSourceRange();
  8275. SourceManager &SM = getSourceManager();
  8276. // If the function is defined as a builtin macro, do not show macro expansion.
  8277. if (SM.isMacroArgExpansion(SL)) {
  8278. SL = SM.getSpellingLoc(SL);
  8279. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  8280. SM.getSpellingLoc(SR.getEnd()));
  8281. }
  8282. // Check if the destination is an array (rather than a pointer to an array).
  8283. QualType DstTy = DstArg->getType();
  8284. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  8285. Context);
  8286. if (!isKnownSizeArray) {
  8287. if (PatternType == 1)
  8288. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  8289. else
  8290. Diag(SL, diag::warn_strncat_src_size) << SR;
  8291. return;
  8292. }
  8293. if (PatternType == 1)
  8294. Diag(SL, diag::warn_strncat_large_size) << SR;
  8295. else
  8296. Diag(SL, diag::warn_strncat_src_size) << SR;
  8297. SmallString<128> sizeString;
  8298. llvm::raw_svector_ostream OS(sizeString);
  8299. OS << "sizeof(";
  8300. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8301. OS << ") - ";
  8302. OS << "strlen(";
  8303. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8304. OS << ") - 1";
  8305. Diag(SL, diag::note_strncat_wrong_size)
  8306. << FixItHint::CreateReplacement(SR, OS.str());
  8307. }
  8308. void
  8309. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  8310. SourceLocation ReturnLoc,
  8311. bool isObjCMethod,
  8312. const AttrVec *Attrs,
  8313. const FunctionDecl *FD) {
  8314. // Check if the return value is null but should not be.
  8315. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  8316. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  8317. CheckNonNullExpr(*this, RetValExp))
  8318. Diag(ReturnLoc, diag::warn_null_ret)
  8319. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  8320. // C++11 [basic.stc.dynamic.allocation]p4:
  8321. // If an allocation function declared with a non-throwing
  8322. // exception-specification fails to allocate storage, it shall return
  8323. // a null pointer. Any other allocation function that fails to allocate
  8324. // storage shall indicate failure only by throwing an exception [...]
  8325. if (FD) {
  8326. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  8327. if (Op == OO_New || Op == OO_Array_New) {
  8328. const FunctionProtoType *Proto
  8329. = FD->getType()->castAs<FunctionProtoType>();
  8330. if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
  8331. CheckNonNullExpr(*this, RetValExp))
  8332. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  8333. << FD << getLangOpts().CPlusPlus11;
  8334. }
  8335. }
  8336. }
  8337. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  8338. /// Check for comparisons of floating point operands using != and ==.
  8339. /// Issue a warning if these are no self-comparisons, as they are not likely
  8340. /// to do what the programmer intended.
  8341. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  8342. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  8343. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  8344. // Special case: check for x == x (which is OK).
  8345. // Do not emit warnings for such cases.
  8346. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  8347. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  8348. if (DRL->getDecl() == DRR->getDecl())
  8349. return;
  8350. // Special case: check for comparisons against literals that can be exactly
  8351. // represented by APFloat. In such cases, do not emit a warning. This
  8352. // is a heuristic: often comparison against such literals are used to
  8353. // detect if a value in a variable has not changed. This clearly can
  8354. // lead to false negatives.
  8355. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  8356. if (FLL->isExact())
  8357. return;
  8358. } else
  8359. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  8360. if (FLR->isExact())
  8361. return;
  8362. // Check for comparisons with builtin types.
  8363. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  8364. if (CL->getBuiltinCallee())
  8365. return;
  8366. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  8367. if (CR->getBuiltinCallee())
  8368. return;
  8369. // Emit the diagnostic.
  8370. Diag(Loc, diag::warn_floatingpoint_eq)
  8371. << LHS->getSourceRange() << RHS->getSourceRange();
  8372. }
  8373. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  8374. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  8375. namespace {
  8376. /// Structure recording the 'active' range of an integer-valued
  8377. /// expression.
  8378. struct IntRange {
  8379. /// The number of bits active in the int.
  8380. unsigned Width;
  8381. /// True if the int is known not to have negative values.
  8382. bool NonNegative;
  8383. IntRange(unsigned Width, bool NonNegative)
  8384. : Width(Width), NonNegative(NonNegative) {}
  8385. /// Returns the range of the bool type.
  8386. static IntRange forBoolType() {
  8387. return IntRange(1, true);
  8388. }
  8389. /// Returns the range of an opaque value of the given integral type.
  8390. static IntRange forValueOfType(ASTContext &C, QualType T) {
  8391. return forValueOfCanonicalType(C,
  8392. T->getCanonicalTypeInternal().getTypePtr());
  8393. }
  8394. /// Returns the range of an opaque value of a canonical integral type.
  8395. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  8396. assert(T->isCanonicalUnqualified());
  8397. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8398. T = VT->getElementType().getTypePtr();
  8399. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8400. T = CT->getElementType().getTypePtr();
  8401. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8402. T = AT->getValueType().getTypePtr();
  8403. if (!C.getLangOpts().CPlusPlus) {
  8404. // For enum types in C code, use the underlying datatype.
  8405. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8406. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  8407. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  8408. // For enum types in C++, use the known bit width of the enumerators.
  8409. EnumDecl *Enum = ET->getDecl();
  8410. // In C++11, enums can have a fixed underlying type. Use this type to
  8411. // compute the range.
  8412. if (Enum->isFixed()) {
  8413. return IntRange(C.getIntWidth(QualType(T, 0)),
  8414. !ET->isSignedIntegerOrEnumerationType());
  8415. }
  8416. unsigned NumPositive = Enum->getNumPositiveBits();
  8417. unsigned NumNegative = Enum->getNumNegativeBits();
  8418. if (NumNegative == 0)
  8419. return IntRange(NumPositive, true/*NonNegative*/);
  8420. else
  8421. return IntRange(std::max(NumPositive + 1, NumNegative),
  8422. false/*NonNegative*/);
  8423. }
  8424. const BuiltinType *BT = cast<BuiltinType>(T);
  8425. assert(BT->isInteger());
  8426. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8427. }
  8428. /// Returns the "target" range of a canonical integral type, i.e.
  8429. /// the range of values expressible in the type.
  8430. ///
  8431. /// This matches forValueOfCanonicalType except that enums have the
  8432. /// full range of their type, not the range of their enumerators.
  8433. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  8434. assert(T->isCanonicalUnqualified());
  8435. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8436. T = VT->getElementType().getTypePtr();
  8437. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8438. T = CT->getElementType().getTypePtr();
  8439. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8440. T = AT->getValueType().getTypePtr();
  8441. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8442. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  8443. const BuiltinType *BT = cast<BuiltinType>(T);
  8444. assert(BT->isInteger());
  8445. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8446. }
  8447. /// Returns the supremum of two ranges: i.e. their conservative merge.
  8448. static IntRange join(IntRange L, IntRange R) {
  8449. return IntRange(std::max(L.Width, R.Width),
  8450. L.NonNegative && R.NonNegative);
  8451. }
  8452. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  8453. static IntRange meet(IntRange L, IntRange R) {
  8454. return IntRange(std::min(L.Width, R.Width),
  8455. L.NonNegative || R.NonNegative);
  8456. }
  8457. };
  8458. } // namespace
  8459. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  8460. unsigned MaxWidth) {
  8461. if (value.isSigned() && value.isNegative())
  8462. return IntRange(value.getMinSignedBits(), false);
  8463. if (value.getBitWidth() > MaxWidth)
  8464. value = value.trunc(MaxWidth);
  8465. // isNonNegative() just checks the sign bit without considering
  8466. // signedness.
  8467. return IntRange(value.getActiveBits(), true);
  8468. }
  8469. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  8470. unsigned MaxWidth) {
  8471. if (result.isInt())
  8472. return GetValueRange(C, result.getInt(), MaxWidth);
  8473. if (result.isVector()) {
  8474. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  8475. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  8476. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  8477. R = IntRange::join(R, El);
  8478. }
  8479. return R;
  8480. }
  8481. if (result.isComplexInt()) {
  8482. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  8483. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  8484. return IntRange::join(R, I);
  8485. }
  8486. // This can happen with lossless casts to intptr_t of "based" lvalues.
  8487. // Assume it might use arbitrary bits.
  8488. // FIXME: The only reason we need to pass the type in here is to get
  8489. // the sign right on this one case. It would be nice if APValue
  8490. // preserved this.
  8491. assert(result.isLValue() || result.isAddrLabelDiff());
  8492. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  8493. }
  8494. static QualType GetExprType(const Expr *E) {
  8495. QualType Ty = E->getType();
  8496. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  8497. Ty = AtomicRHS->getValueType();
  8498. return Ty;
  8499. }
  8500. /// Pseudo-evaluate the given integer expression, estimating the
  8501. /// range of values it might take.
  8502. ///
  8503. /// \param MaxWidth - the width to which the value will be truncated
  8504. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
  8505. E = E->IgnoreParens();
  8506. // Try a full evaluation first.
  8507. Expr::EvalResult result;
  8508. if (E->EvaluateAsRValue(result, C))
  8509. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  8510. // I think we only want to look through implicit casts here; if the
  8511. // user has an explicit widening cast, we should treat the value as
  8512. // being of the new, wider type.
  8513. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  8514. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  8515. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  8516. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  8517. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  8518. CE->getCastKind() == CK_BooleanToSignedIntegral;
  8519. // Assume that non-integer casts can span the full range of the type.
  8520. if (!isIntegerCast)
  8521. return OutputTypeRange;
  8522. IntRange SubRange
  8523. = GetExprRange(C, CE->getSubExpr(),
  8524. std::min(MaxWidth, OutputTypeRange.Width));
  8525. // Bail out if the subexpr's range is as wide as the cast type.
  8526. if (SubRange.Width >= OutputTypeRange.Width)
  8527. return OutputTypeRange;
  8528. // Otherwise, we take the smaller width, and we're non-negative if
  8529. // either the output type or the subexpr is.
  8530. return IntRange(SubRange.Width,
  8531. SubRange.NonNegative || OutputTypeRange.NonNegative);
  8532. }
  8533. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  8534. // If we can fold the condition, just take that operand.
  8535. bool CondResult;
  8536. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  8537. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  8538. : CO->getFalseExpr(),
  8539. MaxWidth);
  8540. // Otherwise, conservatively merge.
  8541. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  8542. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  8543. return IntRange::join(L, R);
  8544. }
  8545. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  8546. switch (BO->getOpcode()) {
  8547. case BO_Cmp:
  8548. llvm_unreachable("builtin <=> should have class type");
  8549. // Boolean-valued operations are single-bit and positive.
  8550. case BO_LAnd:
  8551. case BO_LOr:
  8552. case BO_LT:
  8553. case BO_GT:
  8554. case BO_LE:
  8555. case BO_GE:
  8556. case BO_EQ:
  8557. case BO_NE:
  8558. return IntRange::forBoolType();
  8559. // The type of the assignments is the type of the LHS, so the RHS
  8560. // is not necessarily the same type.
  8561. case BO_MulAssign:
  8562. case BO_DivAssign:
  8563. case BO_RemAssign:
  8564. case BO_AddAssign:
  8565. case BO_SubAssign:
  8566. case BO_XorAssign:
  8567. case BO_OrAssign:
  8568. // TODO: bitfields?
  8569. return IntRange::forValueOfType(C, GetExprType(E));
  8570. // Simple assignments just pass through the RHS, which will have
  8571. // been coerced to the LHS type.
  8572. case BO_Assign:
  8573. // TODO: bitfields?
  8574. return GetExprRange(C, BO->getRHS(), MaxWidth);
  8575. // Operations with opaque sources are black-listed.
  8576. case BO_PtrMemD:
  8577. case BO_PtrMemI:
  8578. return IntRange::forValueOfType(C, GetExprType(E));
  8579. // Bitwise-and uses the *infinum* of the two source ranges.
  8580. case BO_And:
  8581. case BO_AndAssign:
  8582. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  8583. GetExprRange(C, BO->getRHS(), MaxWidth));
  8584. // Left shift gets black-listed based on a judgement call.
  8585. case BO_Shl:
  8586. // ...except that we want to treat '1 << (blah)' as logically
  8587. // positive. It's an important idiom.
  8588. if (IntegerLiteral *I
  8589. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  8590. if (I->getValue() == 1) {
  8591. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  8592. return IntRange(R.Width, /*NonNegative*/ true);
  8593. }
  8594. }
  8595. LLVM_FALLTHROUGH;
  8596. case BO_ShlAssign:
  8597. return IntRange::forValueOfType(C, GetExprType(E));
  8598. // Right shift by a constant can narrow its left argument.
  8599. case BO_Shr:
  8600. case BO_ShrAssign: {
  8601. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  8602. // If the shift amount is a positive constant, drop the width by
  8603. // that much.
  8604. llvm::APSInt shift;
  8605. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  8606. shift.isNonNegative()) {
  8607. unsigned zext = shift.getZExtValue();
  8608. if (zext >= L.Width)
  8609. L.Width = (L.NonNegative ? 0 : 1);
  8610. else
  8611. L.Width -= zext;
  8612. }
  8613. return L;
  8614. }
  8615. // Comma acts as its right operand.
  8616. case BO_Comma:
  8617. return GetExprRange(C, BO->getRHS(), MaxWidth);
  8618. // Black-list pointer subtractions.
  8619. case BO_Sub:
  8620. if (BO->getLHS()->getType()->isPointerType())
  8621. return IntRange::forValueOfType(C, GetExprType(E));
  8622. break;
  8623. // The width of a division result is mostly determined by the size
  8624. // of the LHS.
  8625. case BO_Div: {
  8626. // Don't 'pre-truncate' the operands.
  8627. unsigned opWidth = C.getIntWidth(GetExprType(E));
  8628. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  8629. // If the divisor is constant, use that.
  8630. llvm::APSInt divisor;
  8631. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  8632. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  8633. if (log2 >= L.Width)
  8634. L.Width = (L.NonNegative ? 0 : 1);
  8635. else
  8636. L.Width = std::min(L.Width - log2, MaxWidth);
  8637. return L;
  8638. }
  8639. // Otherwise, just use the LHS's width.
  8640. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  8641. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  8642. }
  8643. // The result of a remainder can't be larger than the result of
  8644. // either side.
  8645. case BO_Rem: {
  8646. // Don't 'pre-truncate' the operands.
  8647. unsigned opWidth = C.getIntWidth(GetExprType(E));
  8648. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  8649. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  8650. IntRange meet = IntRange::meet(L, R);
  8651. meet.Width = std::min(meet.Width, MaxWidth);
  8652. return meet;
  8653. }
  8654. // The default behavior is okay for these.
  8655. case BO_Mul:
  8656. case BO_Add:
  8657. case BO_Xor:
  8658. case BO_Or:
  8659. break;
  8660. }
  8661. // The default case is to treat the operation as if it were closed
  8662. // on the narrowest type that encompasses both operands.
  8663. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  8664. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  8665. return IntRange::join(L, R);
  8666. }
  8667. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  8668. switch (UO->getOpcode()) {
  8669. // Boolean-valued operations are white-listed.
  8670. case UO_LNot:
  8671. return IntRange::forBoolType();
  8672. // Operations with opaque sources are black-listed.
  8673. case UO_Deref:
  8674. case UO_AddrOf: // should be impossible
  8675. return IntRange::forValueOfType(C, GetExprType(E));
  8676. default:
  8677. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  8678. }
  8679. }
  8680. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  8681. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
  8682. if (const auto *BitField = E->getSourceBitField())
  8683. return IntRange(BitField->getBitWidthValue(C),
  8684. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  8685. return IntRange::forValueOfType(C, GetExprType(E));
  8686. }
  8687. static IntRange GetExprRange(ASTContext &C, const Expr *E) {
  8688. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
  8689. }
  8690. /// Checks whether the given value, which currently has the given
  8691. /// source semantics, has the same value when coerced through the
  8692. /// target semantics.
  8693. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  8694. const llvm::fltSemantics &Src,
  8695. const llvm::fltSemantics &Tgt) {
  8696. llvm::APFloat truncated = value;
  8697. bool ignored;
  8698. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  8699. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  8700. return truncated.bitwiseIsEqual(value);
  8701. }
  8702. /// Checks whether the given value, which currently has the given
  8703. /// source semantics, has the same value when coerced through the
  8704. /// target semantics.
  8705. ///
  8706. /// The value might be a vector of floats (or a complex number).
  8707. static bool IsSameFloatAfterCast(const APValue &value,
  8708. const llvm::fltSemantics &Src,
  8709. const llvm::fltSemantics &Tgt) {
  8710. if (value.isFloat())
  8711. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  8712. if (value.isVector()) {
  8713. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  8714. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  8715. return false;
  8716. return true;
  8717. }
  8718. assert(value.isComplexFloat());
  8719. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  8720. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  8721. }
  8722. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  8723. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  8724. // Suppress cases where we are comparing against an enum constant.
  8725. if (const DeclRefExpr *DR =
  8726. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  8727. if (isa<EnumConstantDecl>(DR->getDecl()))
  8728. return true;
  8729. // Suppress cases where the '0' value is expanded from a macro.
  8730. if (E->getLocStart().isMacroID())
  8731. return true;
  8732. return false;
  8733. }
  8734. static bool isKnownToHaveUnsignedValue(Expr *E) {
  8735. return E->getType()->isIntegerType() &&
  8736. (!E->getType()->isSignedIntegerType() ||
  8737. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  8738. }
  8739. namespace {
  8740. /// The promoted range of values of a type. In general this has the
  8741. /// following structure:
  8742. ///
  8743. /// |-----------| . . . |-----------|
  8744. /// ^ ^ ^ ^
  8745. /// Min HoleMin HoleMax Max
  8746. ///
  8747. /// ... where there is only a hole if a signed type is promoted to unsigned
  8748. /// (in which case Min and Max are the smallest and largest representable
  8749. /// values).
  8750. struct PromotedRange {
  8751. // Min, or HoleMax if there is a hole.
  8752. llvm::APSInt PromotedMin;
  8753. // Max, or HoleMin if there is a hole.
  8754. llvm::APSInt PromotedMax;
  8755. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  8756. if (R.Width == 0)
  8757. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  8758. else if (R.Width >= BitWidth && !Unsigned) {
  8759. // Promotion made the type *narrower*. This happens when promoting
  8760. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  8761. // Treat all values of 'signed int' as being in range for now.
  8762. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  8763. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  8764. } else {
  8765. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  8766. .extOrTrunc(BitWidth);
  8767. PromotedMin.setIsUnsigned(Unsigned);
  8768. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  8769. .extOrTrunc(BitWidth);
  8770. PromotedMax.setIsUnsigned(Unsigned);
  8771. }
  8772. }
  8773. // Determine whether this range is contiguous (has no hole).
  8774. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  8775. // Where a constant value is within the range.
  8776. enum ComparisonResult {
  8777. LT = 0x1,
  8778. LE = 0x2,
  8779. GT = 0x4,
  8780. GE = 0x8,
  8781. EQ = 0x10,
  8782. NE = 0x20,
  8783. InRangeFlag = 0x40,
  8784. Less = LE | LT | NE,
  8785. Min = LE | InRangeFlag,
  8786. InRange = InRangeFlag,
  8787. Max = GE | InRangeFlag,
  8788. Greater = GE | GT | NE,
  8789. OnlyValue = LE | GE | EQ | InRangeFlag,
  8790. InHole = NE
  8791. };
  8792. ComparisonResult compare(const llvm::APSInt &Value) const {
  8793. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  8794. Value.isUnsigned() == PromotedMin.isUnsigned());
  8795. if (!isContiguous()) {
  8796. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  8797. if (Value.isMinValue()) return Min;
  8798. if (Value.isMaxValue()) return Max;
  8799. if (Value >= PromotedMin) return InRange;
  8800. if (Value <= PromotedMax) return InRange;
  8801. return InHole;
  8802. }
  8803. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  8804. case -1: return Less;
  8805. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  8806. case 1:
  8807. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  8808. case -1: return InRange;
  8809. case 0: return Max;
  8810. case 1: return Greater;
  8811. }
  8812. }
  8813. llvm_unreachable("impossible compare result");
  8814. }
  8815. static llvm::Optional<StringRef>
  8816. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  8817. if (Op == BO_Cmp) {
  8818. ComparisonResult LTFlag = LT, GTFlag = GT;
  8819. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  8820. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  8821. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  8822. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  8823. return llvm::None;
  8824. }
  8825. ComparisonResult TrueFlag, FalseFlag;
  8826. if (Op == BO_EQ) {
  8827. TrueFlag = EQ;
  8828. FalseFlag = NE;
  8829. } else if (Op == BO_NE) {
  8830. TrueFlag = NE;
  8831. FalseFlag = EQ;
  8832. } else {
  8833. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  8834. TrueFlag = LT;
  8835. FalseFlag = GE;
  8836. } else {
  8837. TrueFlag = GT;
  8838. FalseFlag = LE;
  8839. }
  8840. if (Op == BO_GE || Op == BO_LE)
  8841. std::swap(TrueFlag, FalseFlag);
  8842. }
  8843. if (R & TrueFlag)
  8844. return StringRef("true");
  8845. if (R & FalseFlag)
  8846. return StringRef("false");
  8847. return llvm::None;
  8848. }
  8849. };
  8850. }
  8851. static bool HasEnumType(Expr *E) {
  8852. // Strip off implicit integral promotions.
  8853. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  8854. if (ICE->getCastKind() != CK_IntegralCast &&
  8855. ICE->getCastKind() != CK_NoOp)
  8856. break;
  8857. E = ICE->getSubExpr();
  8858. }
  8859. return E->getType()->isEnumeralType();
  8860. }
  8861. static int classifyConstantValue(Expr *Constant) {
  8862. // The values of this enumeration are used in the diagnostics
  8863. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  8864. enum ConstantValueKind {
  8865. Miscellaneous = 0,
  8866. LiteralTrue,
  8867. LiteralFalse
  8868. };
  8869. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  8870. return BL->getValue() ? ConstantValueKind::LiteralTrue
  8871. : ConstantValueKind::LiteralFalse;
  8872. return ConstantValueKind::Miscellaneous;
  8873. }
  8874. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  8875. Expr *Constant, Expr *Other,
  8876. const llvm::APSInt &Value,
  8877. bool RhsConstant) {
  8878. if (S.inTemplateInstantiation())
  8879. return false;
  8880. Expr *OriginalOther = Other;
  8881. Constant = Constant->IgnoreParenImpCasts();
  8882. Other = Other->IgnoreParenImpCasts();
  8883. // Suppress warnings on tautological comparisons between values of the same
  8884. // enumeration type. There are only two ways we could warn on this:
  8885. // - If the constant is outside the range of representable values of
  8886. // the enumeration. In such a case, we should warn about the cast
  8887. // to enumeration type, not about the comparison.
  8888. // - If the constant is the maximum / minimum in-range value. For an
  8889. // enumeratin type, such comparisons can be meaningful and useful.
  8890. if (Constant->getType()->isEnumeralType() &&
  8891. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  8892. return false;
  8893. // TODO: Investigate using GetExprRange() to get tighter bounds
  8894. // on the bit ranges.
  8895. QualType OtherT = Other->getType();
  8896. if (const auto *AT = OtherT->getAs<AtomicType>())
  8897. OtherT = AT->getValueType();
  8898. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  8899. // Whether we're treating Other as being a bool because of the form of
  8900. // expression despite it having another type (typically 'int' in C).
  8901. bool OtherIsBooleanDespiteType =
  8902. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  8903. if (OtherIsBooleanDespiteType)
  8904. OtherRange = IntRange::forBoolType();
  8905. // Determine the promoted range of the other type and see if a comparison of
  8906. // the constant against that range is tautological.
  8907. PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
  8908. Value.isUnsigned());
  8909. auto Cmp = OtherPromotedRange.compare(Value);
  8910. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  8911. if (!Result)
  8912. return false;
  8913. // Suppress the diagnostic for an in-range comparison if the constant comes
  8914. // from a macro or enumerator. We don't want to diagnose
  8915. //
  8916. // some_long_value <= INT_MAX
  8917. //
  8918. // when sizeof(int) == sizeof(long).
  8919. bool InRange = Cmp & PromotedRange::InRangeFlag;
  8920. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  8921. return false;
  8922. // If this is a comparison to an enum constant, include that
  8923. // constant in the diagnostic.
  8924. const EnumConstantDecl *ED = nullptr;
  8925. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  8926. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  8927. // Should be enough for uint128 (39 decimal digits)
  8928. SmallString<64> PrettySourceValue;
  8929. llvm::raw_svector_ostream OS(PrettySourceValue);
  8930. if (ED)
  8931. OS << '\'' << *ED << "' (" << Value << ")";
  8932. else
  8933. OS << Value;
  8934. // FIXME: We use a somewhat different formatting for the in-range cases and
  8935. // cases involving boolean values for historical reasons. We should pick a
  8936. // consistent way of presenting these diagnostics.
  8937. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  8938. S.DiagRuntimeBehavior(
  8939. E->getOperatorLoc(), E,
  8940. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  8941. : diag::warn_tautological_bool_compare)
  8942. << OS.str() << classifyConstantValue(Constant)
  8943. << OtherT << OtherIsBooleanDespiteType << *Result
  8944. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  8945. } else {
  8946. unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  8947. ? (HasEnumType(OriginalOther)
  8948. ? diag::warn_unsigned_enum_always_true_comparison
  8949. : diag::warn_unsigned_always_true_comparison)
  8950. : diag::warn_tautological_constant_compare;
  8951. S.Diag(E->getOperatorLoc(), Diag)
  8952. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  8953. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  8954. }
  8955. return true;
  8956. }
  8957. /// Analyze the operands of the given comparison. Implements the
  8958. /// fallback case from AnalyzeComparison.
  8959. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  8960. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  8961. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  8962. }
  8963. /// Implements -Wsign-compare.
  8964. ///
  8965. /// \param E the binary operator to check for warnings
  8966. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  8967. // The type the comparison is being performed in.
  8968. QualType T = E->getLHS()->getType();
  8969. // Only analyze comparison operators where both sides have been converted to
  8970. // the same type.
  8971. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  8972. return AnalyzeImpConvsInComparison(S, E);
  8973. // Don't analyze value-dependent comparisons directly.
  8974. if (E->isValueDependent())
  8975. return AnalyzeImpConvsInComparison(S, E);
  8976. Expr *LHS = E->getLHS();
  8977. Expr *RHS = E->getRHS();
  8978. if (T->isIntegralType(S.Context)) {
  8979. llvm::APSInt RHSValue;
  8980. llvm::APSInt LHSValue;
  8981. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  8982. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  8983. // We don't care about expressions whose result is a constant.
  8984. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  8985. return AnalyzeImpConvsInComparison(S, E);
  8986. // We only care about expressions where just one side is literal
  8987. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  8988. // Is the constant on the RHS or LHS?
  8989. const bool RhsConstant = IsRHSIntegralLiteral;
  8990. Expr *Const = RhsConstant ? RHS : LHS;
  8991. Expr *Other = RhsConstant ? LHS : RHS;
  8992. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  8993. // Check whether an integer constant comparison results in a value
  8994. // of 'true' or 'false'.
  8995. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  8996. return AnalyzeImpConvsInComparison(S, E);
  8997. }
  8998. }
  8999. if (!T->hasUnsignedIntegerRepresentation()) {
  9000. // We don't do anything special if this isn't an unsigned integral
  9001. // comparison: we're only interested in integral comparisons, and
  9002. // signed comparisons only happen in cases we don't care to warn about.
  9003. return AnalyzeImpConvsInComparison(S, E);
  9004. }
  9005. LHS = LHS->IgnoreParenImpCasts();
  9006. RHS = RHS->IgnoreParenImpCasts();
  9007. if (!S.getLangOpts().CPlusPlus) {
  9008. // Avoid warning about comparison of integers with different signs when
  9009. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  9010. // the type of `E`.
  9011. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  9012. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9013. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  9014. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9015. }
  9016. // Check to see if one of the (unmodified) operands is of different
  9017. // signedness.
  9018. Expr *signedOperand, *unsignedOperand;
  9019. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  9020. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  9021. "unsigned comparison between two signed integer expressions?");
  9022. signedOperand = LHS;
  9023. unsignedOperand = RHS;
  9024. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  9025. signedOperand = RHS;
  9026. unsignedOperand = LHS;
  9027. } else {
  9028. return AnalyzeImpConvsInComparison(S, E);
  9029. }
  9030. // Otherwise, calculate the effective range of the signed operand.
  9031. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  9032. // Go ahead and analyze implicit conversions in the operands. Note
  9033. // that we skip the implicit conversions on both sides.
  9034. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  9035. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  9036. // If the signed range is non-negative, -Wsign-compare won't fire.
  9037. if (signedRange.NonNegative)
  9038. return;
  9039. // For (in)equality comparisons, if the unsigned operand is a
  9040. // constant which cannot collide with a overflowed signed operand,
  9041. // then reinterpreting the signed operand as unsigned will not
  9042. // change the result of the comparison.
  9043. if (E->isEqualityOp()) {
  9044. unsigned comparisonWidth = S.Context.getIntWidth(T);
  9045. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  9046. // We should never be unable to prove that the unsigned operand is
  9047. // non-negative.
  9048. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  9049. if (unsignedRange.Width < comparisonWidth)
  9050. return;
  9051. }
  9052. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9053. S.PDiag(diag::warn_mixed_sign_comparison)
  9054. << LHS->getType() << RHS->getType()
  9055. << LHS->getSourceRange() << RHS->getSourceRange());
  9056. }
  9057. /// Analyzes an attempt to assign the given value to a bitfield.
  9058. ///
  9059. /// Returns true if there was something fishy about the attempt.
  9060. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  9061. SourceLocation InitLoc) {
  9062. assert(Bitfield->isBitField());
  9063. if (Bitfield->isInvalidDecl())
  9064. return false;
  9065. // White-list bool bitfields.
  9066. QualType BitfieldType = Bitfield->getType();
  9067. if (BitfieldType->isBooleanType())
  9068. return false;
  9069. if (BitfieldType->isEnumeralType()) {
  9070. EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
  9071. // If the underlying enum type was not explicitly specified as an unsigned
  9072. // type and the enum contain only positive values, MSVC++ will cause an
  9073. // inconsistency by storing this as a signed type.
  9074. if (S.getLangOpts().CPlusPlus11 &&
  9075. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  9076. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  9077. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  9078. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  9079. << BitfieldEnumDecl->getNameAsString();
  9080. }
  9081. }
  9082. if (Bitfield->getType()->isBooleanType())
  9083. return false;
  9084. // Ignore value- or type-dependent expressions.
  9085. if (Bitfield->getBitWidth()->isValueDependent() ||
  9086. Bitfield->getBitWidth()->isTypeDependent() ||
  9087. Init->isValueDependent() ||
  9088. Init->isTypeDependent())
  9089. return false;
  9090. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  9091. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  9092. llvm::APSInt Value;
  9093. if (!OriginalInit->EvaluateAsInt(Value, S.Context,
  9094. Expr::SE_AllowSideEffects)) {
  9095. // The RHS is not constant. If the RHS has an enum type, make sure the
  9096. // bitfield is wide enough to hold all the values of the enum without
  9097. // truncation.
  9098. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  9099. EnumDecl *ED = EnumTy->getDecl();
  9100. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  9101. // Enum types are implicitly signed on Windows, so check if there are any
  9102. // negative enumerators to see if the enum was intended to be signed or
  9103. // not.
  9104. bool SignedEnum = ED->getNumNegativeBits() > 0;
  9105. // Check for surprising sign changes when assigning enum values to a
  9106. // bitfield of different signedness. If the bitfield is signed and we
  9107. // have exactly the right number of bits to store this unsigned enum,
  9108. // suggest changing the enum to an unsigned type. This typically happens
  9109. // on Windows where unfixed enums always use an underlying type of 'int'.
  9110. unsigned DiagID = 0;
  9111. if (SignedEnum && !SignedBitfield) {
  9112. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  9113. } else if (SignedBitfield && !SignedEnum &&
  9114. ED->getNumPositiveBits() == FieldWidth) {
  9115. DiagID = diag::warn_signed_bitfield_enum_conversion;
  9116. }
  9117. if (DiagID) {
  9118. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  9119. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  9120. SourceRange TypeRange =
  9121. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  9122. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  9123. << SignedEnum << TypeRange;
  9124. }
  9125. // Compute the required bitwidth. If the enum has negative values, we need
  9126. // one more bit than the normal number of positive bits to represent the
  9127. // sign bit.
  9128. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  9129. ED->getNumNegativeBits())
  9130. : ED->getNumPositiveBits();
  9131. // Check the bitwidth.
  9132. if (BitsNeeded > FieldWidth) {
  9133. Expr *WidthExpr = Bitfield->getBitWidth();
  9134. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  9135. << Bitfield << ED;
  9136. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  9137. << BitsNeeded << ED << WidthExpr->getSourceRange();
  9138. }
  9139. }
  9140. return false;
  9141. }
  9142. unsigned OriginalWidth = Value.getBitWidth();
  9143. if (!Value.isSigned() || Value.isNegative())
  9144. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  9145. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  9146. OriginalWidth = Value.getMinSignedBits();
  9147. if (OriginalWidth <= FieldWidth)
  9148. return false;
  9149. // Compute the value which the bitfield will contain.
  9150. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  9151. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  9152. // Check whether the stored value is equal to the original value.
  9153. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  9154. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  9155. return false;
  9156. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  9157. // therefore don't strictly fit into a signed bitfield of width 1.
  9158. if (FieldWidth == 1 && Value == 1)
  9159. return false;
  9160. std::string PrettyValue = Value.toString(10);
  9161. std::string PrettyTrunc = TruncatedValue.toString(10);
  9162. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  9163. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  9164. << Init->getSourceRange();
  9165. return true;
  9166. }
  9167. /// Analyze the given simple or compound assignment for warning-worthy
  9168. /// operations.
  9169. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  9170. // Just recurse on the LHS.
  9171. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9172. // We want to recurse on the RHS as normal unless we're assigning to
  9173. // a bitfield.
  9174. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  9175. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  9176. E->getOperatorLoc())) {
  9177. // Recurse, ignoring any implicit conversions on the RHS.
  9178. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  9179. E->getOperatorLoc());
  9180. }
  9181. }
  9182. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9183. }
  9184. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9185. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  9186. SourceLocation CContext, unsigned diag,
  9187. bool pruneControlFlow = false) {
  9188. if (pruneControlFlow) {
  9189. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9190. S.PDiag(diag)
  9191. << SourceType << T << E->getSourceRange()
  9192. << SourceRange(CContext));
  9193. return;
  9194. }
  9195. S.Diag(E->getExprLoc(), diag)
  9196. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  9197. }
  9198. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9199. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  9200. SourceLocation CContext,
  9201. unsigned diag, bool pruneControlFlow = false) {
  9202. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  9203. }
  9204. /// Analyze the given compound assignment for the possible losing of
  9205. /// floating-point precision.
  9206. static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
  9207. assert(isa<CompoundAssignOperator>(E) &&
  9208. "Must be compound assignment operation");
  9209. // Recurse on the LHS and RHS in here
  9210. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9211. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9212. // Now check the outermost expression
  9213. const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
  9214. const auto *RBT = cast<CompoundAssignOperator>(E)
  9215. ->getComputationResultType()
  9216. ->getAs<BuiltinType>();
  9217. // If both source and target are floating points.
  9218. if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
  9219. // Builtin FP kinds are ordered by increasing FP rank.
  9220. if (ResultBT->getKind() < RBT->getKind())
  9221. // We don't want to warn for system macro.
  9222. if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
  9223. // warn about dropping FP rank.
  9224. DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
  9225. E->getOperatorLoc(),
  9226. diag::warn_impcast_float_result_precision);
  9227. }
  9228. /// Diagnose an implicit cast from a floating point value to an integer value.
  9229. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  9230. SourceLocation CContext) {
  9231. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  9232. const bool PruneWarnings = S.inTemplateInstantiation();
  9233. Expr *InnerE = E->IgnoreParenImpCasts();
  9234. // We also want to warn on, e.g., "int i = -1.234"
  9235. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  9236. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  9237. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  9238. const bool IsLiteral =
  9239. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  9240. llvm::APFloat Value(0.0);
  9241. bool IsConstant =
  9242. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  9243. if (!IsConstant) {
  9244. return DiagnoseImpCast(S, E, T, CContext,
  9245. diag::warn_impcast_float_integer, PruneWarnings);
  9246. }
  9247. bool isExact = false;
  9248. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  9249. T->hasUnsignedIntegerRepresentation());
  9250. llvm::APFloat::opStatus Result = Value.convertToInteger(
  9251. IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
  9252. if (Result == llvm::APFloat::opOK && isExact) {
  9253. if (IsLiteral) return;
  9254. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  9255. PruneWarnings);
  9256. }
  9257. // Conversion of a floating-point value to a non-bool integer where the
  9258. // integral part cannot be represented by the integer type is undefined.
  9259. if (!IsBool && Result == llvm::APFloat::opInvalidOp)
  9260. return DiagnoseImpCast(
  9261. S, E, T, CContext,
  9262. IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
  9263. : diag::warn_impcast_float_to_integer_out_of_range,
  9264. PruneWarnings);
  9265. unsigned DiagID = 0;
  9266. if (IsLiteral) {
  9267. // Warn on floating point literal to integer.
  9268. DiagID = diag::warn_impcast_literal_float_to_integer;
  9269. } else if (IntegerValue == 0) {
  9270. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  9271. return DiagnoseImpCast(S, E, T, CContext,
  9272. diag::warn_impcast_float_integer, PruneWarnings);
  9273. }
  9274. // Warn on non-zero to zero conversion.
  9275. DiagID = diag::warn_impcast_float_to_integer_zero;
  9276. } else {
  9277. if (IntegerValue.isUnsigned()) {
  9278. if (!IntegerValue.isMaxValue()) {
  9279. return DiagnoseImpCast(S, E, T, CContext,
  9280. diag::warn_impcast_float_integer, PruneWarnings);
  9281. }
  9282. } else { // IntegerValue.isSigned()
  9283. if (!IntegerValue.isMaxSignedValue() &&
  9284. !IntegerValue.isMinSignedValue()) {
  9285. return DiagnoseImpCast(S, E, T, CContext,
  9286. diag::warn_impcast_float_integer, PruneWarnings);
  9287. }
  9288. }
  9289. // Warn on evaluatable floating point expression to integer conversion.
  9290. DiagID = diag::warn_impcast_float_to_integer;
  9291. }
  9292. // FIXME: Force the precision of the source value down so we don't print
  9293. // digits which are usually useless (we don't really care here if we
  9294. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  9295. // would automatically print the shortest representation, but it's a bit
  9296. // tricky to implement.
  9297. SmallString<16> PrettySourceValue;
  9298. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  9299. precision = (precision * 59 + 195) / 196;
  9300. Value.toString(PrettySourceValue, precision);
  9301. SmallString<16> PrettyTargetValue;
  9302. if (IsBool)
  9303. PrettyTargetValue = Value.isZero() ? "false" : "true";
  9304. else
  9305. IntegerValue.toString(PrettyTargetValue);
  9306. if (PruneWarnings) {
  9307. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9308. S.PDiag(DiagID)
  9309. << E->getType() << T.getUnqualifiedType()
  9310. << PrettySourceValue << PrettyTargetValue
  9311. << E->getSourceRange() << SourceRange(CContext));
  9312. } else {
  9313. S.Diag(E->getExprLoc(), DiagID)
  9314. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  9315. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  9316. }
  9317. }
  9318. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  9319. IntRange Range) {
  9320. if (!Range.Width) return "0";
  9321. llvm::APSInt ValueInRange = Value;
  9322. ValueInRange.setIsSigned(!Range.NonNegative);
  9323. ValueInRange = ValueInRange.trunc(Range.Width);
  9324. return ValueInRange.toString(10);
  9325. }
  9326. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  9327. if (!isa<ImplicitCastExpr>(Ex))
  9328. return false;
  9329. Expr *InnerE = Ex->IgnoreParenImpCasts();
  9330. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  9331. const Type *Source =
  9332. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  9333. if (Target->isDependentType())
  9334. return false;
  9335. const BuiltinType *FloatCandidateBT =
  9336. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  9337. const Type *BoolCandidateType = ToBool ? Target : Source;
  9338. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  9339. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  9340. }
  9341. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  9342. SourceLocation CC) {
  9343. unsigned NumArgs = TheCall->getNumArgs();
  9344. for (unsigned i = 0; i < NumArgs; ++i) {
  9345. Expr *CurrA = TheCall->getArg(i);
  9346. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  9347. continue;
  9348. bool IsSwapped = ((i > 0) &&
  9349. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  9350. IsSwapped |= ((i < (NumArgs - 1)) &&
  9351. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  9352. if (IsSwapped) {
  9353. // Warn on this floating-point to bool conversion.
  9354. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  9355. CurrA->getType(), CC,
  9356. diag::warn_impcast_floating_point_to_bool);
  9357. }
  9358. }
  9359. }
  9360. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  9361. SourceLocation CC) {
  9362. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  9363. E->getExprLoc()))
  9364. return;
  9365. // Don't warn on functions which have return type nullptr_t.
  9366. if (isa<CallExpr>(E))
  9367. return;
  9368. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  9369. const Expr::NullPointerConstantKind NullKind =
  9370. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  9371. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  9372. return;
  9373. // Return if target type is a safe conversion.
  9374. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  9375. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  9376. return;
  9377. SourceLocation Loc = E->getSourceRange().getBegin();
  9378. // Venture through the macro stacks to get to the source of macro arguments.
  9379. // The new location is a better location than the complete location that was
  9380. // passed in.
  9381. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  9382. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  9383. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  9384. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  9385. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  9386. Loc, S.SourceMgr, S.getLangOpts());
  9387. if (MacroName == "NULL")
  9388. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
  9389. }
  9390. // Only warn if the null and context location are in the same macro expansion.
  9391. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  9392. return;
  9393. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  9394. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  9395. << FixItHint::CreateReplacement(Loc,
  9396. S.getFixItZeroLiteralForType(T, Loc));
  9397. }
  9398. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9399. ObjCArrayLiteral *ArrayLiteral);
  9400. static void
  9401. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9402. ObjCDictionaryLiteral *DictionaryLiteral);
  9403. /// Check a single element within a collection literal against the
  9404. /// target element type.
  9405. static void checkObjCCollectionLiteralElement(Sema &S,
  9406. QualType TargetElementType,
  9407. Expr *Element,
  9408. unsigned ElementKind) {
  9409. // Skip a bitcast to 'id' or qualified 'id'.
  9410. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  9411. if (ICE->getCastKind() == CK_BitCast &&
  9412. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  9413. Element = ICE->getSubExpr();
  9414. }
  9415. QualType ElementType = Element->getType();
  9416. ExprResult ElementResult(Element);
  9417. if (ElementType->getAs<ObjCObjectPointerType>() &&
  9418. S.CheckSingleAssignmentConstraints(TargetElementType,
  9419. ElementResult,
  9420. false, false)
  9421. != Sema::Compatible) {
  9422. S.Diag(Element->getLocStart(),
  9423. diag::warn_objc_collection_literal_element)
  9424. << ElementType << ElementKind << TargetElementType
  9425. << Element->getSourceRange();
  9426. }
  9427. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  9428. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  9429. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  9430. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  9431. }
  9432. /// Check an Objective-C array literal being converted to the given
  9433. /// target type.
  9434. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9435. ObjCArrayLiteral *ArrayLiteral) {
  9436. if (!S.NSArrayDecl)
  9437. return;
  9438. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9439. if (!TargetObjCPtr)
  9440. return;
  9441. if (TargetObjCPtr->isUnspecialized() ||
  9442. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9443. != S.NSArrayDecl->getCanonicalDecl())
  9444. return;
  9445. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9446. if (TypeArgs.size() != 1)
  9447. return;
  9448. QualType TargetElementType = TypeArgs[0];
  9449. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  9450. checkObjCCollectionLiteralElement(S, TargetElementType,
  9451. ArrayLiteral->getElement(I),
  9452. 0);
  9453. }
  9454. }
  9455. /// Check an Objective-C dictionary literal being converted to the given
  9456. /// target type.
  9457. static void
  9458. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9459. ObjCDictionaryLiteral *DictionaryLiteral) {
  9460. if (!S.NSDictionaryDecl)
  9461. return;
  9462. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9463. if (!TargetObjCPtr)
  9464. return;
  9465. if (TargetObjCPtr->isUnspecialized() ||
  9466. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9467. != S.NSDictionaryDecl->getCanonicalDecl())
  9468. return;
  9469. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9470. if (TypeArgs.size() != 2)
  9471. return;
  9472. QualType TargetKeyType = TypeArgs[0];
  9473. QualType TargetObjectType = TypeArgs[1];
  9474. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  9475. auto Element = DictionaryLiteral->getKeyValueElement(I);
  9476. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  9477. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  9478. }
  9479. }
  9480. // Helper function to filter out cases for constant width constant conversion.
  9481. // Don't warn on char array initialization or for non-decimal values.
  9482. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  9483. SourceLocation CC) {
  9484. // If initializing from a constant, and the constant starts with '0',
  9485. // then it is a binary, octal, or hexadecimal. Allow these constants
  9486. // to fill all the bits, even if there is a sign change.
  9487. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  9488. const char FirstLiteralCharacter =
  9489. S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
  9490. if (FirstLiteralCharacter == '0')
  9491. return false;
  9492. }
  9493. // If the CC location points to a '{', and the type is char, then assume
  9494. // assume it is an array initialization.
  9495. if (CC.isValid() && T->isCharType()) {
  9496. const char FirstContextCharacter =
  9497. S.getSourceManager().getCharacterData(CC)[0];
  9498. if (FirstContextCharacter == '{')
  9499. return false;
  9500. }
  9501. return true;
  9502. }
  9503. static void
  9504. CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
  9505. bool *ICContext = nullptr) {
  9506. if (E->isTypeDependent() || E->isValueDependent()) return;
  9507. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  9508. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  9509. if (Source == Target) return;
  9510. if (Target->isDependentType()) return;
  9511. // If the conversion context location is invalid don't complain. We also
  9512. // don't want to emit a warning if the issue occurs from the expansion of
  9513. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  9514. // delay this check as long as possible. Once we detect we are in that
  9515. // scenario, we just return.
  9516. if (CC.isInvalid())
  9517. return;
  9518. // Diagnose implicit casts to bool.
  9519. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  9520. if (isa<StringLiteral>(E))
  9521. // Warn on string literal to bool. Checks for string literals in logical
  9522. // and expressions, for instance, assert(0 && "error here"), are
  9523. // prevented by a check in AnalyzeImplicitConversions().
  9524. return DiagnoseImpCast(S, E, T, CC,
  9525. diag::warn_impcast_string_literal_to_bool);
  9526. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  9527. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  9528. // This covers the literal expressions that evaluate to Objective-C
  9529. // objects.
  9530. return DiagnoseImpCast(S, E, T, CC,
  9531. diag::warn_impcast_objective_c_literal_to_bool);
  9532. }
  9533. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  9534. // Warn on pointer to bool conversion that is always true.
  9535. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  9536. SourceRange(CC));
  9537. }
  9538. }
  9539. // Check implicit casts from Objective-C collection literals to specialized
  9540. // collection types, e.g., NSArray<NSString *> *.
  9541. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  9542. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  9543. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  9544. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  9545. // Strip vector types.
  9546. if (isa<VectorType>(Source)) {
  9547. if (!isa<VectorType>(Target)) {
  9548. if (S.SourceMgr.isInSystemMacro(CC))
  9549. return;
  9550. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  9551. }
  9552. // If the vector cast is cast between two vectors of the same size, it is
  9553. // a bitcast, not a conversion.
  9554. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  9555. return;
  9556. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  9557. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  9558. }
  9559. if (auto VecTy = dyn_cast<VectorType>(Target))
  9560. Target = VecTy->getElementType().getTypePtr();
  9561. // Strip complex types.
  9562. if (isa<ComplexType>(Source)) {
  9563. if (!isa<ComplexType>(Target)) {
  9564. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  9565. return;
  9566. return DiagnoseImpCast(S, E, T, CC,
  9567. S.getLangOpts().CPlusPlus
  9568. ? diag::err_impcast_complex_scalar
  9569. : diag::warn_impcast_complex_scalar);
  9570. }
  9571. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  9572. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  9573. }
  9574. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  9575. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  9576. // If the source is floating point...
  9577. if (SourceBT && SourceBT->isFloatingPoint()) {
  9578. // ...and the target is floating point...
  9579. if (TargetBT && TargetBT->isFloatingPoint()) {
  9580. // ...then warn if we're dropping FP rank.
  9581. // Builtin FP kinds are ordered by increasing FP rank.
  9582. if (SourceBT->getKind() > TargetBT->getKind()) {
  9583. // Don't warn about float constants that are precisely
  9584. // representable in the target type.
  9585. Expr::EvalResult result;
  9586. if (E->EvaluateAsRValue(result, S.Context)) {
  9587. // Value might be a float, a float vector, or a float complex.
  9588. if (IsSameFloatAfterCast(result.Val,
  9589. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  9590. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  9591. return;
  9592. }
  9593. if (S.SourceMgr.isInSystemMacro(CC))
  9594. return;
  9595. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  9596. }
  9597. // ... or possibly if we're increasing rank, too
  9598. else if (TargetBT->getKind() > SourceBT->getKind()) {
  9599. if (S.SourceMgr.isInSystemMacro(CC))
  9600. return;
  9601. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  9602. }
  9603. return;
  9604. }
  9605. // If the target is integral, always warn.
  9606. if (TargetBT && TargetBT->isInteger()) {
  9607. if (S.SourceMgr.isInSystemMacro(CC))
  9608. return;
  9609. DiagnoseFloatingImpCast(S, E, T, CC);
  9610. }
  9611. // Detect the case where a call result is converted from floating-point to
  9612. // to bool, and the final argument to the call is converted from bool, to
  9613. // discover this typo:
  9614. //
  9615. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  9616. //
  9617. // FIXME: This is an incredibly special case; is there some more general
  9618. // way to detect this class of misplaced-parentheses bug?
  9619. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  9620. // Check last argument of function call to see if it is an
  9621. // implicit cast from a type matching the type the result
  9622. // is being cast to.
  9623. CallExpr *CEx = cast<CallExpr>(E);
  9624. if (unsigned NumArgs = CEx->getNumArgs()) {
  9625. Expr *LastA = CEx->getArg(NumArgs - 1);
  9626. Expr *InnerE = LastA->IgnoreParenImpCasts();
  9627. if (isa<ImplicitCastExpr>(LastA) &&
  9628. InnerE->getType()->isBooleanType()) {
  9629. // Warn on this floating-point to bool conversion
  9630. DiagnoseImpCast(S, E, T, CC,
  9631. diag::warn_impcast_floating_point_to_bool);
  9632. }
  9633. }
  9634. }
  9635. return;
  9636. }
  9637. DiagnoseNullConversion(S, E, T, CC);
  9638. S.DiscardMisalignedMemberAddress(Target, E);
  9639. if (!Source->isIntegerType() || !Target->isIntegerType())
  9640. return;
  9641. // TODO: remove this early return once the false positives for constant->bool
  9642. // in templates, macros, etc, are reduced or removed.
  9643. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  9644. return;
  9645. IntRange SourceRange = GetExprRange(S.Context, E);
  9646. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  9647. if (SourceRange.Width > TargetRange.Width) {
  9648. // If the source is a constant, use a default-on diagnostic.
  9649. // TODO: this should happen for bitfield stores, too.
  9650. llvm::APSInt Value(32);
  9651. if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
  9652. if (S.SourceMgr.isInSystemMacro(CC))
  9653. return;
  9654. std::string PrettySourceValue = Value.toString(10);
  9655. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  9656. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9657. S.PDiag(diag::warn_impcast_integer_precision_constant)
  9658. << PrettySourceValue << PrettyTargetValue
  9659. << E->getType() << T << E->getSourceRange()
  9660. << clang::SourceRange(CC));
  9661. return;
  9662. }
  9663. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  9664. if (S.SourceMgr.isInSystemMacro(CC))
  9665. return;
  9666. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  9667. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  9668. /* pruneControlFlow */ true);
  9669. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  9670. }
  9671. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  9672. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  9673. // Warn when doing a signed to signed conversion, warn if the positive
  9674. // source value is exactly the width of the target type, which will
  9675. // cause a negative value to be stored.
  9676. llvm::APSInt Value;
  9677. if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
  9678. !S.SourceMgr.isInSystemMacro(CC)) {
  9679. if (isSameWidthConstantConversion(S, E, T, CC)) {
  9680. std::string PrettySourceValue = Value.toString(10);
  9681. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  9682. S.DiagRuntimeBehavior(
  9683. E->getExprLoc(), E,
  9684. S.PDiag(diag::warn_impcast_integer_precision_constant)
  9685. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  9686. << E->getSourceRange() << clang::SourceRange(CC));
  9687. return;
  9688. }
  9689. }
  9690. // Fall through for non-constants to give a sign conversion warning.
  9691. }
  9692. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  9693. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  9694. SourceRange.Width == TargetRange.Width)) {
  9695. if (S.SourceMgr.isInSystemMacro(CC))
  9696. return;
  9697. unsigned DiagID = diag::warn_impcast_integer_sign;
  9698. // Traditionally, gcc has warned about this under -Wsign-compare.
  9699. // We also want to warn about it in -Wconversion.
  9700. // So if -Wconversion is off, use a completely identical diagnostic
  9701. // in the sign-compare group.
  9702. // The conditional-checking code will
  9703. if (ICContext) {
  9704. DiagID = diag::warn_impcast_integer_sign_conditional;
  9705. *ICContext = true;
  9706. }
  9707. return DiagnoseImpCast(S, E, T, CC, DiagID);
  9708. }
  9709. // Diagnose conversions between different enumeration types.
  9710. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  9711. // type, to give us better diagnostics.
  9712. QualType SourceType = E->getType();
  9713. if (!S.getLangOpts().CPlusPlus) {
  9714. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  9715. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  9716. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  9717. SourceType = S.Context.getTypeDeclType(Enum);
  9718. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  9719. }
  9720. }
  9721. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  9722. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  9723. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  9724. TargetEnum->getDecl()->hasNameForLinkage() &&
  9725. SourceEnum != TargetEnum) {
  9726. if (S.SourceMgr.isInSystemMacro(CC))
  9727. return;
  9728. return DiagnoseImpCast(S, E, SourceType, T, CC,
  9729. diag::warn_impcast_different_enum_types);
  9730. }
  9731. }
  9732. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  9733. SourceLocation CC, QualType T);
  9734. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  9735. SourceLocation CC, bool &ICContext) {
  9736. E = E->IgnoreParenImpCasts();
  9737. if (isa<ConditionalOperator>(E))
  9738. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  9739. AnalyzeImplicitConversions(S, E, CC);
  9740. if (E->getType() != T)
  9741. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  9742. }
  9743. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  9744. SourceLocation CC, QualType T) {
  9745. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  9746. bool Suspicious = false;
  9747. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  9748. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  9749. // If -Wconversion would have warned about either of the candidates
  9750. // for a signedness conversion to the context type...
  9751. if (!Suspicious) return;
  9752. // ...but it's currently ignored...
  9753. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  9754. return;
  9755. // ...then check whether it would have warned about either of the
  9756. // candidates for a signedness conversion to the condition type.
  9757. if (E->getType() == T) return;
  9758. Suspicious = false;
  9759. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  9760. E->getType(), CC, &Suspicious);
  9761. if (!Suspicious)
  9762. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  9763. E->getType(), CC, &Suspicious);
  9764. }
  9765. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  9766. /// Input argument E is a logical expression.
  9767. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  9768. if (S.getLangOpts().Bool)
  9769. return;
  9770. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  9771. }
  9772. /// AnalyzeImplicitConversions - Find and report any interesting
  9773. /// implicit conversions in the given expression. There are a couple
  9774. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  9775. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
  9776. SourceLocation CC) {
  9777. QualType T = OrigE->getType();
  9778. Expr *E = OrigE->IgnoreParenImpCasts();
  9779. if (E->isTypeDependent() || E->isValueDependent())
  9780. return;
  9781. // For conditional operators, we analyze the arguments as if they
  9782. // were being fed directly into the output.
  9783. if (isa<ConditionalOperator>(E)) {
  9784. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  9785. CheckConditionalOperator(S, CO, CC, T);
  9786. return;
  9787. }
  9788. // Check implicit argument conversions for function calls.
  9789. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  9790. CheckImplicitArgumentConversions(S, Call, CC);
  9791. // Go ahead and check any implicit conversions we might have skipped.
  9792. // The non-canonical typecheck is just an optimization;
  9793. // CheckImplicitConversion will filter out dead implicit conversions.
  9794. if (E->getType() != T)
  9795. CheckImplicitConversion(S, E, T, CC);
  9796. // Now continue drilling into this expression.
  9797. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  9798. // The bound subexpressions in a PseudoObjectExpr are not reachable
  9799. // as transitive children.
  9800. // FIXME: Use a more uniform representation for this.
  9801. for (auto *SE : POE->semantics())
  9802. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  9803. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  9804. }
  9805. // Skip past explicit casts.
  9806. if (isa<ExplicitCastExpr>(E)) {
  9807. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  9808. return AnalyzeImplicitConversions(S, E, CC);
  9809. }
  9810. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9811. // Do a somewhat different check with comparison operators.
  9812. if (BO->isComparisonOp())
  9813. return AnalyzeComparison(S, BO);
  9814. // And with simple assignments.
  9815. if (BO->getOpcode() == BO_Assign)
  9816. return AnalyzeAssignment(S, BO);
  9817. // And with compound assignments.
  9818. if (BO->isAssignmentOp())
  9819. return AnalyzeCompoundAssignment(S, BO);
  9820. }
  9821. // These break the otherwise-useful invariant below. Fortunately,
  9822. // we don't really need to recurse into them, because any internal
  9823. // expressions should have been analyzed already when they were
  9824. // built into statements.
  9825. if (isa<StmtExpr>(E)) return;
  9826. // Don't descend into unevaluated contexts.
  9827. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  9828. // Now just recurse over the expression's children.
  9829. CC = E->getExprLoc();
  9830. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  9831. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  9832. for (Stmt *SubStmt : E->children()) {
  9833. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  9834. if (!ChildExpr)
  9835. continue;
  9836. if (IsLogicalAndOperator &&
  9837. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  9838. // Ignore checking string literals that are in logical and operators.
  9839. // This is a common pattern for asserts.
  9840. continue;
  9841. AnalyzeImplicitConversions(S, ChildExpr, CC);
  9842. }
  9843. if (BO && BO->isLogicalOp()) {
  9844. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  9845. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  9846. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  9847. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  9848. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  9849. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  9850. }
  9851. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
  9852. if (U->getOpcode() == UO_LNot)
  9853. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  9854. }
  9855. /// Diagnose integer type and any valid implicit conversion to it.
  9856. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  9857. // Taking into account implicit conversions,
  9858. // allow any integer.
  9859. if (!E->getType()->isIntegerType()) {
  9860. S.Diag(E->getLocStart(),
  9861. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  9862. return true;
  9863. }
  9864. // Potentially emit standard warnings for implicit conversions if enabled
  9865. // using -Wconversion.
  9866. CheckImplicitConversion(S, E, IntT, E->getLocStart());
  9867. return false;
  9868. }
  9869. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  9870. // Returns true when emitting a warning about taking the address of a reference.
  9871. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  9872. const PartialDiagnostic &PD) {
  9873. E = E->IgnoreParenImpCasts();
  9874. const FunctionDecl *FD = nullptr;
  9875. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9876. if (!DRE->getDecl()->getType()->isReferenceType())
  9877. return false;
  9878. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  9879. if (!M->getMemberDecl()->getType()->isReferenceType())
  9880. return false;
  9881. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  9882. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  9883. return false;
  9884. FD = Call->getDirectCallee();
  9885. } else {
  9886. return false;
  9887. }
  9888. SemaRef.Diag(E->getExprLoc(), PD);
  9889. // If possible, point to location of function.
  9890. if (FD) {
  9891. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  9892. }
  9893. return true;
  9894. }
  9895. // Returns true if the SourceLocation is expanded from any macro body.
  9896. // Returns false if the SourceLocation is invalid, is from not in a macro
  9897. // expansion, or is from expanded from a top-level macro argument.
  9898. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  9899. if (Loc.isInvalid())
  9900. return false;
  9901. while (Loc.isMacroID()) {
  9902. if (SM.isMacroBodyExpansion(Loc))
  9903. return true;
  9904. Loc = SM.getImmediateMacroCallerLoc(Loc);
  9905. }
  9906. return false;
  9907. }
  9908. /// Diagnose pointers that are always non-null.
  9909. /// \param E the expression containing the pointer
  9910. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  9911. /// compared to a null pointer
  9912. /// \param IsEqual True when the comparison is equal to a null pointer
  9913. /// \param Range Extra SourceRange to highlight in the diagnostic
  9914. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  9915. Expr::NullPointerConstantKind NullKind,
  9916. bool IsEqual, SourceRange Range) {
  9917. if (!E)
  9918. return;
  9919. // Don't warn inside macros.
  9920. if (E->getExprLoc().isMacroID()) {
  9921. const SourceManager &SM = getSourceManager();
  9922. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  9923. IsInAnyMacroBody(SM, Range.getBegin()))
  9924. return;
  9925. }
  9926. E = E->IgnoreImpCasts();
  9927. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  9928. if (isa<CXXThisExpr>(E)) {
  9929. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  9930. : diag::warn_this_bool_conversion;
  9931. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  9932. return;
  9933. }
  9934. bool IsAddressOf = false;
  9935. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  9936. if (UO->getOpcode() != UO_AddrOf)
  9937. return;
  9938. IsAddressOf = true;
  9939. E = UO->getSubExpr();
  9940. }
  9941. if (IsAddressOf) {
  9942. unsigned DiagID = IsCompare
  9943. ? diag::warn_address_of_reference_null_compare
  9944. : diag::warn_address_of_reference_bool_conversion;
  9945. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  9946. << IsEqual;
  9947. if (CheckForReference(*this, E, PD)) {
  9948. return;
  9949. }
  9950. }
  9951. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  9952. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  9953. std::string Str;
  9954. llvm::raw_string_ostream S(Str);
  9955. E->printPretty(S, nullptr, getPrintingPolicy());
  9956. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  9957. : diag::warn_cast_nonnull_to_bool;
  9958. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  9959. << E->getSourceRange() << Range << IsEqual;
  9960. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  9961. };
  9962. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  9963. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  9964. if (auto *Callee = Call->getDirectCallee()) {
  9965. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  9966. ComplainAboutNonnullParamOrCall(A);
  9967. return;
  9968. }
  9969. }
  9970. }
  9971. // Expect to find a single Decl. Skip anything more complicated.
  9972. ValueDecl *D = nullptr;
  9973. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  9974. D = R->getDecl();
  9975. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  9976. D = M->getMemberDecl();
  9977. }
  9978. // Weak Decls can be null.
  9979. if (!D || D->isWeak())
  9980. return;
  9981. // Check for parameter decl with nonnull attribute
  9982. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  9983. if (getCurFunction() &&
  9984. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  9985. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  9986. ComplainAboutNonnullParamOrCall(A);
  9987. return;
  9988. }
  9989. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  9990. auto ParamIter = llvm::find(FD->parameters(), PV);
  9991. assert(ParamIter != FD->param_end());
  9992. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  9993. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  9994. if (!NonNull->args_size()) {
  9995. ComplainAboutNonnullParamOrCall(NonNull);
  9996. return;
  9997. }
  9998. for (const ParamIdx &ArgNo : NonNull->args()) {
  9999. if (ArgNo.getASTIndex() == ParamNo) {
  10000. ComplainAboutNonnullParamOrCall(NonNull);
  10001. return;
  10002. }
  10003. }
  10004. }
  10005. }
  10006. }
  10007. }
  10008. QualType T = D->getType();
  10009. const bool IsArray = T->isArrayType();
  10010. const bool IsFunction = T->isFunctionType();
  10011. // Address of function is used to silence the function warning.
  10012. if (IsAddressOf && IsFunction) {
  10013. return;
  10014. }
  10015. // Found nothing.
  10016. if (!IsAddressOf && !IsFunction && !IsArray)
  10017. return;
  10018. // Pretty print the expression for the diagnostic.
  10019. std::string Str;
  10020. llvm::raw_string_ostream S(Str);
  10021. E->printPretty(S, nullptr, getPrintingPolicy());
  10022. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  10023. : diag::warn_impcast_pointer_to_bool;
  10024. enum {
  10025. AddressOf,
  10026. FunctionPointer,
  10027. ArrayPointer
  10028. } DiagType;
  10029. if (IsAddressOf)
  10030. DiagType = AddressOf;
  10031. else if (IsFunction)
  10032. DiagType = FunctionPointer;
  10033. else if (IsArray)
  10034. DiagType = ArrayPointer;
  10035. else
  10036. llvm_unreachable("Could not determine diagnostic.");
  10037. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  10038. << Range << IsEqual;
  10039. if (!IsFunction)
  10040. return;
  10041. // Suggest '&' to silence the function warning.
  10042. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  10043. << FixItHint::CreateInsertion(E->getLocStart(), "&");
  10044. // Check to see if '()' fixit should be emitted.
  10045. QualType ReturnType;
  10046. UnresolvedSet<4> NonTemplateOverloads;
  10047. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  10048. if (ReturnType.isNull())
  10049. return;
  10050. if (IsCompare) {
  10051. // There are two cases here. If there is null constant, the only suggest
  10052. // for a pointer return type. If the null is 0, then suggest if the return
  10053. // type is a pointer or an integer type.
  10054. if (!ReturnType->isPointerType()) {
  10055. if (NullKind == Expr::NPCK_ZeroExpression ||
  10056. NullKind == Expr::NPCK_ZeroLiteral) {
  10057. if (!ReturnType->isIntegerType())
  10058. return;
  10059. } else {
  10060. return;
  10061. }
  10062. }
  10063. } else { // !IsCompare
  10064. // For function to bool, only suggest if the function pointer has bool
  10065. // return type.
  10066. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  10067. return;
  10068. }
  10069. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  10070. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
  10071. }
  10072. /// Diagnoses "dangerous" implicit conversions within the given
  10073. /// expression (which is a full expression). Implements -Wconversion
  10074. /// and -Wsign-compare.
  10075. ///
  10076. /// \param CC the "context" location of the implicit conversion, i.e.
  10077. /// the most location of the syntactic entity requiring the implicit
  10078. /// conversion
  10079. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  10080. // Don't diagnose in unevaluated contexts.
  10081. if (isUnevaluatedContext())
  10082. return;
  10083. // Don't diagnose for value- or type-dependent expressions.
  10084. if (E->isTypeDependent() || E->isValueDependent())
  10085. return;
  10086. // Check for array bounds violations in cases where the check isn't triggered
  10087. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  10088. // ArraySubscriptExpr is on the RHS of a variable initialization.
  10089. CheckArrayAccess(E);
  10090. // This is not the right CC for (e.g.) a variable initialization.
  10091. AnalyzeImplicitConversions(*this, E, CC);
  10092. }
  10093. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  10094. /// Input argument E is a logical expression.
  10095. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  10096. ::CheckBoolLikeConversion(*this, E, CC);
  10097. }
  10098. /// Diagnose when expression is an integer constant expression and its evaluation
  10099. /// results in integer overflow
  10100. void Sema::CheckForIntOverflow (Expr *E) {
  10101. // Use a work list to deal with nested struct initializers.
  10102. SmallVector<Expr *, 2> Exprs(1, E);
  10103. do {
  10104. Expr *OriginalE = Exprs.pop_back_val();
  10105. Expr *E = OriginalE->IgnoreParenCasts();
  10106. if (isa<BinaryOperator>(E)) {
  10107. E->EvaluateForOverflow(Context);
  10108. continue;
  10109. }
  10110. if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
  10111. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  10112. else if (isa<ObjCBoxedExpr>(OriginalE))
  10113. E->EvaluateForOverflow(Context);
  10114. else if (auto Call = dyn_cast<CallExpr>(E))
  10115. Exprs.append(Call->arg_begin(), Call->arg_end());
  10116. else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
  10117. Exprs.append(Message->arg_begin(), Message->arg_end());
  10118. } while (!Exprs.empty());
  10119. }
  10120. namespace {
  10121. /// Visitor for expressions which looks for unsequenced operations on the
  10122. /// same object.
  10123. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  10124. using Base = EvaluatedExprVisitor<SequenceChecker>;
  10125. /// A tree of sequenced regions within an expression. Two regions are
  10126. /// unsequenced if one is an ancestor or a descendent of the other. When we
  10127. /// finish processing an expression with sequencing, such as a comma
  10128. /// expression, we fold its tree nodes into its parent, since they are
  10129. /// unsequenced with respect to nodes we will visit later.
  10130. class SequenceTree {
  10131. struct Value {
  10132. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  10133. unsigned Parent : 31;
  10134. unsigned Merged : 1;
  10135. };
  10136. SmallVector<Value, 8> Values;
  10137. public:
  10138. /// A region within an expression which may be sequenced with respect
  10139. /// to some other region.
  10140. class Seq {
  10141. friend class SequenceTree;
  10142. unsigned Index = 0;
  10143. explicit Seq(unsigned N) : Index(N) {}
  10144. public:
  10145. Seq() = default;
  10146. };
  10147. SequenceTree() { Values.push_back(Value(0)); }
  10148. Seq root() const { return Seq(0); }
  10149. /// Create a new sequence of operations, which is an unsequenced
  10150. /// subset of \p Parent. This sequence of operations is sequenced with
  10151. /// respect to other children of \p Parent.
  10152. Seq allocate(Seq Parent) {
  10153. Values.push_back(Value(Parent.Index));
  10154. return Seq(Values.size() - 1);
  10155. }
  10156. /// Merge a sequence of operations into its parent.
  10157. void merge(Seq S) {
  10158. Values[S.Index].Merged = true;
  10159. }
  10160. /// Determine whether two operations are unsequenced. This operation
  10161. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  10162. /// should have been merged into its parent as appropriate.
  10163. bool isUnsequenced(Seq Cur, Seq Old) {
  10164. unsigned C = representative(Cur.Index);
  10165. unsigned Target = representative(Old.Index);
  10166. while (C >= Target) {
  10167. if (C == Target)
  10168. return true;
  10169. C = Values[C].Parent;
  10170. }
  10171. return false;
  10172. }
  10173. private:
  10174. /// Pick a representative for a sequence.
  10175. unsigned representative(unsigned K) {
  10176. if (Values[K].Merged)
  10177. // Perform path compression as we go.
  10178. return Values[K].Parent = representative(Values[K].Parent);
  10179. return K;
  10180. }
  10181. };
  10182. /// An object for which we can track unsequenced uses.
  10183. using Object = NamedDecl *;
  10184. /// Different flavors of object usage which we track. We only track the
  10185. /// least-sequenced usage of each kind.
  10186. enum UsageKind {
  10187. /// A read of an object. Multiple unsequenced reads are OK.
  10188. UK_Use,
  10189. /// A modification of an object which is sequenced before the value
  10190. /// computation of the expression, such as ++n in C++.
  10191. UK_ModAsValue,
  10192. /// A modification of an object which is not sequenced before the value
  10193. /// computation of the expression, such as n++.
  10194. UK_ModAsSideEffect,
  10195. UK_Count = UK_ModAsSideEffect + 1
  10196. };
  10197. struct Usage {
  10198. Expr *Use = nullptr;
  10199. SequenceTree::Seq Seq;
  10200. Usage() = default;
  10201. };
  10202. struct UsageInfo {
  10203. Usage Uses[UK_Count];
  10204. /// Have we issued a diagnostic for this variable already?
  10205. bool Diagnosed = false;
  10206. UsageInfo() = default;
  10207. };
  10208. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  10209. Sema &SemaRef;
  10210. /// Sequenced regions within the expression.
  10211. SequenceTree Tree;
  10212. /// Declaration modifications and references which we have seen.
  10213. UsageInfoMap UsageMap;
  10214. /// The region we are currently within.
  10215. SequenceTree::Seq Region;
  10216. /// Filled in with declarations which were modified as a side-effect
  10217. /// (that is, post-increment operations).
  10218. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  10219. /// Expressions to check later. We defer checking these to reduce
  10220. /// stack usage.
  10221. SmallVectorImpl<Expr *> &WorkList;
  10222. /// RAII object wrapping the visitation of a sequenced subexpression of an
  10223. /// expression. At the end of this process, the side-effects of the evaluation
  10224. /// become sequenced with respect to the value computation of the result, so
  10225. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  10226. /// UK_ModAsValue.
  10227. struct SequencedSubexpression {
  10228. SequencedSubexpression(SequenceChecker &Self)
  10229. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  10230. Self.ModAsSideEffect = &ModAsSideEffect;
  10231. }
  10232. ~SequencedSubexpression() {
  10233. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  10234. UsageInfo &U = Self.UsageMap[M.first];
  10235. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  10236. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  10237. SideEffectUsage = M.second;
  10238. }
  10239. Self.ModAsSideEffect = OldModAsSideEffect;
  10240. }
  10241. SequenceChecker &Self;
  10242. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  10243. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  10244. };
  10245. /// RAII object wrapping the visitation of a subexpression which we might
  10246. /// choose to evaluate as a constant. If any subexpression is evaluated and
  10247. /// found to be non-constant, this allows us to suppress the evaluation of
  10248. /// the outer expression.
  10249. class EvaluationTracker {
  10250. public:
  10251. EvaluationTracker(SequenceChecker &Self)
  10252. : Self(Self), Prev(Self.EvalTracker) {
  10253. Self.EvalTracker = this;
  10254. }
  10255. ~EvaluationTracker() {
  10256. Self.EvalTracker = Prev;
  10257. if (Prev)
  10258. Prev->EvalOK &= EvalOK;
  10259. }
  10260. bool evaluate(const Expr *E, bool &Result) {
  10261. if (!EvalOK || E->isValueDependent())
  10262. return false;
  10263. EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
  10264. return EvalOK;
  10265. }
  10266. private:
  10267. SequenceChecker &Self;
  10268. EvaluationTracker *Prev;
  10269. bool EvalOK = true;
  10270. } *EvalTracker = nullptr;
  10271. /// Find the object which is produced by the specified expression,
  10272. /// if any.
  10273. Object getObject(Expr *E, bool Mod) const {
  10274. E = E->IgnoreParenCasts();
  10275. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10276. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  10277. return getObject(UO->getSubExpr(), Mod);
  10278. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10279. if (BO->getOpcode() == BO_Comma)
  10280. return getObject(BO->getRHS(), Mod);
  10281. if (Mod && BO->isAssignmentOp())
  10282. return getObject(BO->getLHS(), Mod);
  10283. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  10284. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  10285. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  10286. return ME->getMemberDecl();
  10287. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10288. // FIXME: If this is a reference, map through to its value.
  10289. return DRE->getDecl();
  10290. return nullptr;
  10291. }
  10292. /// Note that an object was modified or used by an expression.
  10293. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  10294. Usage &U = UI.Uses[UK];
  10295. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  10296. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  10297. ModAsSideEffect->push_back(std::make_pair(O, U));
  10298. U.Use = Ref;
  10299. U.Seq = Region;
  10300. }
  10301. }
  10302. /// Check whether a modification or use conflicts with a prior usage.
  10303. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  10304. bool IsModMod) {
  10305. if (UI.Diagnosed)
  10306. return;
  10307. const Usage &U = UI.Uses[OtherKind];
  10308. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  10309. return;
  10310. Expr *Mod = U.Use;
  10311. Expr *ModOrUse = Ref;
  10312. if (OtherKind == UK_Use)
  10313. std::swap(Mod, ModOrUse);
  10314. SemaRef.Diag(Mod->getExprLoc(),
  10315. IsModMod ? diag::warn_unsequenced_mod_mod
  10316. : diag::warn_unsequenced_mod_use)
  10317. << O << SourceRange(ModOrUse->getExprLoc());
  10318. UI.Diagnosed = true;
  10319. }
  10320. void notePreUse(Object O, Expr *Use) {
  10321. UsageInfo &U = UsageMap[O];
  10322. // Uses conflict with other modifications.
  10323. checkUsage(O, U, Use, UK_ModAsValue, false);
  10324. }
  10325. void notePostUse(Object O, Expr *Use) {
  10326. UsageInfo &U = UsageMap[O];
  10327. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  10328. addUsage(U, O, Use, UK_Use);
  10329. }
  10330. void notePreMod(Object O, Expr *Mod) {
  10331. UsageInfo &U = UsageMap[O];
  10332. // Modifications conflict with other modifications and with uses.
  10333. checkUsage(O, U, Mod, UK_ModAsValue, true);
  10334. checkUsage(O, U, Mod, UK_Use, false);
  10335. }
  10336. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  10337. UsageInfo &U = UsageMap[O];
  10338. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  10339. addUsage(U, O, Use, UK);
  10340. }
  10341. public:
  10342. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  10343. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  10344. Visit(E);
  10345. }
  10346. void VisitStmt(Stmt *S) {
  10347. // Skip all statements which aren't expressions for now.
  10348. }
  10349. void VisitExpr(Expr *E) {
  10350. // By default, just recurse to evaluated subexpressions.
  10351. Base::VisitStmt(E);
  10352. }
  10353. void VisitCastExpr(CastExpr *E) {
  10354. Object O = Object();
  10355. if (E->getCastKind() == CK_LValueToRValue)
  10356. O = getObject(E->getSubExpr(), false);
  10357. if (O)
  10358. notePreUse(O, E);
  10359. VisitExpr(E);
  10360. if (O)
  10361. notePostUse(O, E);
  10362. }
  10363. void VisitBinComma(BinaryOperator *BO) {
  10364. // C++11 [expr.comma]p1:
  10365. // Every value computation and side effect associated with the left
  10366. // expression is sequenced before every value computation and side
  10367. // effect associated with the right expression.
  10368. SequenceTree::Seq LHS = Tree.allocate(Region);
  10369. SequenceTree::Seq RHS = Tree.allocate(Region);
  10370. SequenceTree::Seq OldRegion = Region;
  10371. {
  10372. SequencedSubexpression SeqLHS(*this);
  10373. Region = LHS;
  10374. Visit(BO->getLHS());
  10375. }
  10376. Region = RHS;
  10377. Visit(BO->getRHS());
  10378. Region = OldRegion;
  10379. // Forget that LHS and RHS are sequenced. They are both unsequenced
  10380. // with respect to other stuff.
  10381. Tree.merge(LHS);
  10382. Tree.merge(RHS);
  10383. }
  10384. void VisitBinAssign(BinaryOperator *BO) {
  10385. // The modification is sequenced after the value computation of the LHS
  10386. // and RHS, so check it before inspecting the operands and update the
  10387. // map afterwards.
  10388. Object O = getObject(BO->getLHS(), true);
  10389. if (!O)
  10390. return VisitExpr(BO);
  10391. notePreMod(O, BO);
  10392. // C++11 [expr.ass]p7:
  10393. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  10394. // only once.
  10395. //
  10396. // Therefore, for a compound assignment operator, O is considered used
  10397. // everywhere except within the evaluation of E1 itself.
  10398. if (isa<CompoundAssignOperator>(BO))
  10399. notePreUse(O, BO);
  10400. Visit(BO->getLHS());
  10401. if (isa<CompoundAssignOperator>(BO))
  10402. notePostUse(O, BO);
  10403. Visit(BO->getRHS());
  10404. // C++11 [expr.ass]p1:
  10405. // the assignment is sequenced [...] before the value computation of the
  10406. // assignment expression.
  10407. // C11 6.5.16/3 has no such rule.
  10408. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  10409. : UK_ModAsSideEffect);
  10410. }
  10411. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  10412. VisitBinAssign(CAO);
  10413. }
  10414. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10415. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10416. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  10417. Object O = getObject(UO->getSubExpr(), true);
  10418. if (!O)
  10419. return VisitExpr(UO);
  10420. notePreMod(O, UO);
  10421. Visit(UO->getSubExpr());
  10422. // C++11 [expr.pre.incr]p1:
  10423. // the expression ++x is equivalent to x+=1
  10424. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  10425. : UK_ModAsSideEffect);
  10426. }
  10427. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  10428. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  10429. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  10430. Object O = getObject(UO->getSubExpr(), true);
  10431. if (!O)
  10432. return VisitExpr(UO);
  10433. notePreMod(O, UO);
  10434. Visit(UO->getSubExpr());
  10435. notePostMod(O, UO, UK_ModAsSideEffect);
  10436. }
  10437. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  10438. void VisitBinLOr(BinaryOperator *BO) {
  10439. // The side-effects of the LHS of an '&&' are sequenced before the
  10440. // value computation of the RHS, and hence before the value computation
  10441. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  10442. // as if they were unconditionally sequenced.
  10443. EvaluationTracker Eval(*this);
  10444. {
  10445. SequencedSubexpression Sequenced(*this);
  10446. Visit(BO->getLHS());
  10447. }
  10448. bool Result;
  10449. if (Eval.evaluate(BO->getLHS(), Result)) {
  10450. if (!Result)
  10451. Visit(BO->getRHS());
  10452. } else {
  10453. // Check for unsequenced operations in the RHS, treating it as an
  10454. // entirely separate evaluation.
  10455. //
  10456. // FIXME: If there are operations in the RHS which are unsequenced
  10457. // with respect to operations outside the RHS, and those operations
  10458. // are unconditionally evaluated, diagnose them.
  10459. WorkList.push_back(BO->getRHS());
  10460. }
  10461. }
  10462. void VisitBinLAnd(BinaryOperator *BO) {
  10463. EvaluationTracker Eval(*this);
  10464. {
  10465. SequencedSubexpression Sequenced(*this);
  10466. Visit(BO->getLHS());
  10467. }
  10468. bool Result;
  10469. if (Eval.evaluate(BO->getLHS(), Result)) {
  10470. if (Result)
  10471. Visit(BO->getRHS());
  10472. } else {
  10473. WorkList.push_back(BO->getRHS());
  10474. }
  10475. }
  10476. // Only visit the condition, unless we can be sure which subexpression will
  10477. // be chosen.
  10478. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  10479. EvaluationTracker Eval(*this);
  10480. {
  10481. SequencedSubexpression Sequenced(*this);
  10482. Visit(CO->getCond());
  10483. }
  10484. bool Result;
  10485. if (Eval.evaluate(CO->getCond(), Result))
  10486. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  10487. else {
  10488. WorkList.push_back(CO->getTrueExpr());
  10489. WorkList.push_back(CO->getFalseExpr());
  10490. }
  10491. }
  10492. void VisitCallExpr(CallExpr *CE) {
  10493. // C++11 [intro.execution]p15:
  10494. // When calling a function [...], every value computation and side effect
  10495. // associated with any argument expression, or with the postfix expression
  10496. // designating the called function, is sequenced before execution of every
  10497. // expression or statement in the body of the function [and thus before
  10498. // the value computation of its result].
  10499. SequencedSubexpression Sequenced(*this);
  10500. Base::VisitCallExpr(CE);
  10501. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  10502. }
  10503. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  10504. // This is a call, so all subexpressions are sequenced before the result.
  10505. SequencedSubexpression Sequenced(*this);
  10506. if (!CCE->isListInitialization())
  10507. return VisitExpr(CCE);
  10508. // In C++11, list initializations are sequenced.
  10509. SmallVector<SequenceTree::Seq, 32> Elts;
  10510. SequenceTree::Seq Parent = Region;
  10511. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  10512. E = CCE->arg_end();
  10513. I != E; ++I) {
  10514. Region = Tree.allocate(Parent);
  10515. Elts.push_back(Region);
  10516. Visit(*I);
  10517. }
  10518. // Forget that the initializers are sequenced.
  10519. Region = Parent;
  10520. for (unsigned I = 0; I < Elts.size(); ++I)
  10521. Tree.merge(Elts[I]);
  10522. }
  10523. void VisitInitListExpr(InitListExpr *ILE) {
  10524. if (!SemaRef.getLangOpts().CPlusPlus11)
  10525. return VisitExpr(ILE);
  10526. // In C++11, list initializations are sequenced.
  10527. SmallVector<SequenceTree::Seq, 32> Elts;
  10528. SequenceTree::Seq Parent = Region;
  10529. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  10530. Expr *E = ILE->getInit(I);
  10531. if (!E) continue;
  10532. Region = Tree.allocate(Parent);
  10533. Elts.push_back(Region);
  10534. Visit(E);
  10535. }
  10536. // Forget that the initializers are sequenced.
  10537. Region = Parent;
  10538. for (unsigned I = 0; I < Elts.size(); ++I)
  10539. Tree.merge(Elts[I]);
  10540. }
  10541. };
  10542. } // namespace
  10543. void Sema::CheckUnsequencedOperations(Expr *E) {
  10544. SmallVector<Expr *, 8> WorkList;
  10545. WorkList.push_back(E);
  10546. while (!WorkList.empty()) {
  10547. Expr *Item = WorkList.pop_back_val();
  10548. SequenceChecker(*this, Item, WorkList);
  10549. }
  10550. }
  10551. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  10552. bool IsConstexpr) {
  10553. CheckImplicitConversions(E, CheckLoc);
  10554. if (!E->isInstantiationDependent())
  10555. CheckUnsequencedOperations(E);
  10556. if (!IsConstexpr && !E->isValueDependent())
  10557. CheckForIntOverflow(E);
  10558. DiagnoseMisalignedMembers();
  10559. }
  10560. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  10561. FieldDecl *BitField,
  10562. Expr *Init) {
  10563. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  10564. }
  10565. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  10566. SourceLocation Loc) {
  10567. if (!PType->isVariablyModifiedType())
  10568. return;
  10569. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  10570. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  10571. return;
  10572. }
  10573. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  10574. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  10575. return;
  10576. }
  10577. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  10578. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  10579. return;
  10580. }
  10581. const ArrayType *AT = S.Context.getAsArrayType(PType);
  10582. if (!AT)
  10583. return;
  10584. if (AT->getSizeModifier() != ArrayType::Star) {
  10585. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  10586. return;
  10587. }
  10588. S.Diag(Loc, diag::err_array_star_in_function_definition);
  10589. }
  10590. /// CheckParmsForFunctionDef - Check that the parameters of the given
  10591. /// function are appropriate for the definition of a function. This
  10592. /// takes care of any checks that cannot be performed on the
  10593. /// declaration itself, e.g., that the types of each of the function
  10594. /// parameters are complete.
  10595. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  10596. bool CheckParameterNames) {
  10597. bool HasInvalidParm = false;
  10598. for (ParmVarDecl *Param : Parameters) {
  10599. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  10600. // function declarator that is part of a function definition of
  10601. // that function shall not have incomplete type.
  10602. //
  10603. // This is also C++ [dcl.fct]p6.
  10604. if (!Param->isInvalidDecl() &&
  10605. RequireCompleteType(Param->getLocation(), Param->getType(),
  10606. diag::err_typecheck_decl_incomplete_type)) {
  10607. Param->setInvalidDecl();
  10608. HasInvalidParm = true;
  10609. }
  10610. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  10611. // declaration of each parameter shall include an identifier.
  10612. if (CheckParameterNames &&
  10613. Param->getIdentifier() == nullptr &&
  10614. !Param->isImplicit() &&
  10615. !getLangOpts().CPlusPlus)
  10616. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  10617. // C99 6.7.5.3p12:
  10618. // If the function declarator is not part of a definition of that
  10619. // function, parameters may have incomplete type and may use the [*]
  10620. // notation in their sequences of declarator specifiers to specify
  10621. // variable length array types.
  10622. QualType PType = Param->getOriginalType();
  10623. // FIXME: This diagnostic should point the '[*]' if source-location
  10624. // information is added for it.
  10625. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  10626. // If the parameter is a c++ class type and it has to be destructed in the
  10627. // callee function, declare the destructor so that it can be called by the
  10628. // callee function. Do not perform any direct access check on the dtor here.
  10629. if (!Param->isInvalidDecl()) {
  10630. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  10631. if (!ClassDecl->isInvalidDecl() &&
  10632. !ClassDecl->hasIrrelevantDestructor() &&
  10633. !ClassDecl->isDependentContext() &&
  10634. ClassDecl->isParamDestroyedInCallee()) {
  10635. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  10636. MarkFunctionReferenced(Param->getLocation(), Destructor);
  10637. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  10638. }
  10639. }
  10640. }
  10641. // Parameters with the pass_object_size attribute only need to be marked
  10642. // constant at function definitions. Because we lack information about
  10643. // whether we're on a declaration or definition when we're instantiating the
  10644. // attribute, we need to check for constness here.
  10645. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  10646. if (!Param->getType().isConstQualified())
  10647. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  10648. << Attr->getSpelling() << 1;
  10649. }
  10650. return HasInvalidParm;
  10651. }
  10652. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  10653. /// or MemberExpr.
  10654. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  10655. ASTContext &Context) {
  10656. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  10657. return Context.getDeclAlign(DRE->getDecl());
  10658. if (const auto *ME = dyn_cast<MemberExpr>(E))
  10659. return Context.getDeclAlign(ME->getMemberDecl());
  10660. return TypeAlign;
  10661. }
  10662. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  10663. /// pointer cast increases the alignment requirements.
  10664. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  10665. // This is actually a lot of work to potentially be doing on every
  10666. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  10667. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  10668. return;
  10669. // Ignore dependent types.
  10670. if (T->isDependentType() || Op->getType()->isDependentType())
  10671. return;
  10672. // Require that the destination be a pointer type.
  10673. const PointerType *DestPtr = T->getAs<PointerType>();
  10674. if (!DestPtr) return;
  10675. // If the destination has alignment 1, we're done.
  10676. QualType DestPointee = DestPtr->getPointeeType();
  10677. if (DestPointee->isIncompleteType()) return;
  10678. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  10679. if (DestAlign.isOne()) return;
  10680. // Require that the source be a pointer type.
  10681. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  10682. if (!SrcPtr) return;
  10683. QualType SrcPointee = SrcPtr->getPointeeType();
  10684. // Whitelist casts from cv void*. We already implicitly
  10685. // whitelisted casts to cv void*, since they have alignment 1.
  10686. // Also whitelist casts involving incomplete types, which implicitly
  10687. // includes 'void'.
  10688. if (SrcPointee->isIncompleteType()) return;
  10689. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  10690. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  10691. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  10692. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  10693. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  10694. if (UO->getOpcode() == UO_AddrOf)
  10695. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  10696. }
  10697. if (SrcAlign >= DestAlign) return;
  10698. Diag(TRange.getBegin(), diag::warn_cast_align)
  10699. << Op->getType() << T
  10700. << static_cast<unsigned>(SrcAlign.getQuantity())
  10701. << static_cast<unsigned>(DestAlign.getQuantity())
  10702. << TRange << Op->getSourceRange();
  10703. }
  10704. /// Check whether this array fits the idiom of a size-one tail padded
  10705. /// array member of a struct.
  10706. ///
  10707. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  10708. /// commonly used to emulate flexible arrays in C89 code.
  10709. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  10710. const NamedDecl *ND) {
  10711. if (Size != 1 || !ND) return false;
  10712. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  10713. if (!FD) return false;
  10714. // Don't consider sizes resulting from macro expansions or template argument
  10715. // substitution to form C89 tail-padded arrays.
  10716. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  10717. while (TInfo) {
  10718. TypeLoc TL = TInfo->getTypeLoc();
  10719. // Look through typedefs.
  10720. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  10721. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  10722. TInfo = TDL->getTypeSourceInfo();
  10723. continue;
  10724. }
  10725. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  10726. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  10727. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  10728. return false;
  10729. }
  10730. break;
  10731. }
  10732. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  10733. if (!RD) return false;
  10734. if (RD->isUnion()) return false;
  10735. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  10736. if (!CRD->isStandardLayout()) return false;
  10737. }
  10738. // See if this is the last field decl in the record.
  10739. const Decl *D = FD;
  10740. while ((D = D->getNextDeclInContext()))
  10741. if (isa<FieldDecl>(D))
  10742. return false;
  10743. return true;
  10744. }
  10745. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  10746. const ArraySubscriptExpr *ASE,
  10747. bool AllowOnePastEnd, bool IndexNegated) {
  10748. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  10749. if (IndexExpr->isValueDependent())
  10750. return;
  10751. const Type *EffectiveType =
  10752. BaseExpr->getType()->getPointeeOrArrayElementType();
  10753. BaseExpr = BaseExpr->IgnoreParenCasts();
  10754. const ConstantArrayType *ArrayTy =
  10755. Context.getAsConstantArrayType(BaseExpr->getType());
  10756. if (!ArrayTy)
  10757. return;
  10758. llvm::APSInt index;
  10759. if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
  10760. return;
  10761. if (IndexNegated)
  10762. index = -index;
  10763. const NamedDecl *ND = nullptr;
  10764. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  10765. ND = DRE->getDecl();
  10766. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  10767. ND = ME->getMemberDecl();
  10768. if (index.isUnsigned() || !index.isNegative()) {
  10769. llvm::APInt size = ArrayTy->getSize();
  10770. if (!size.isStrictlyPositive())
  10771. return;
  10772. const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
  10773. if (BaseType != EffectiveType) {
  10774. // Make sure we're comparing apples to apples when comparing index to size
  10775. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  10776. uint64_t array_typesize = Context.getTypeSize(BaseType);
  10777. // Handle ptrarith_typesize being zero, such as when casting to void*
  10778. if (!ptrarith_typesize) ptrarith_typesize = 1;
  10779. if (ptrarith_typesize != array_typesize) {
  10780. // There's a cast to a different size type involved
  10781. uint64_t ratio = array_typesize / ptrarith_typesize;
  10782. // TODO: Be smarter about handling cases where array_typesize is not a
  10783. // multiple of ptrarith_typesize
  10784. if (ptrarith_typesize * ratio == array_typesize)
  10785. size *= llvm::APInt(size.getBitWidth(), ratio);
  10786. }
  10787. }
  10788. if (size.getBitWidth() > index.getBitWidth())
  10789. index = index.zext(size.getBitWidth());
  10790. else if (size.getBitWidth() < index.getBitWidth())
  10791. size = size.zext(index.getBitWidth());
  10792. // For array subscripting the index must be less than size, but for pointer
  10793. // arithmetic also allow the index (offset) to be equal to size since
  10794. // computing the next address after the end of the array is legal and
  10795. // commonly done e.g. in C++ iterators and range-based for loops.
  10796. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  10797. return;
  10798. // Also don't warn for arrays of size 1 which are members of some
  10799. // structure. These are often used to approximate flexible arrays in C89
  10800. // code.
  10801. if (IsTailPaddedMemberArray(*this, size, ND))
  10802. return;
  10803. // Suppress the warning if the subscript expression (as identified by the
  10804. // ']' location) and the index expression are both from macro expansions
  10805. // within a system header.
  10806. if (ASE) {
  10807. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  10808. ASE->getRBracketLoc());
  10809. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  10810. SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
  10811. IndexExpr->getLocStart());
  10812. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  10813. return;
  10814. }
  10815. }
  10816. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  10817. if (ASE)
  10818. DiagID = diag::warn_array_index_exceeds_bounds;
  10819. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  10820. PDiag(DiagID) << index.toString(10, true)
  10821. << size.toString(10, true)
  10822. << (unsigned)size.getLimitedValue(~0U)
  10823. << IndexExpr->getSourceRange());
  10824. } else {
  10825. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  10826. if (!ASE) {
  10827. DiagID = diag::warn_ptr_arith_precedes_bounds;
  10828. if (index.isNegative()) index = -index;
  10829. }
  10830. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  10831. PDiag(DiagID) << index.toString(10, true)
  10832. << IndexExpr->getSourceRange());
  10833. }
  10834. if (!ND) {
  10835. // Try harder to find a NamedDecl to point at in the note.
  10836. while (const ArraySubscriptExpr *ASE =
  10837. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  10838. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  10839. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  10840. ND = DRE->getDecl();
  10841. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  10842. ND = ME->getMemberDecl();
  10843. }
  10844. if (ND)
  10845. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  10846. PDiag(diag::note_array_index_out_of_bounds)
  10847. << ND->getDeclName());
  10848. }
  10849. void Sema::CheckArrayAccess(const Expr *expr) {
  10850. int AllowOnePastEnd = 0;
  10851. while (expr) {
  10852. expr = expr->IgnoreParenImpCasts();
  10853. switch (expr->getStmtClass()) {
  10854. case Stmt::ArraySubscriptExprClass: {
  10855. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  10856. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  10857. AllowOnePastEnd > 0);
  10858. expr = ASE->getBase();
  10859. break;
  10860. }
  10861. case Stmt::MemberExprClass: {
  10862. expr = cast<MemberExpr>(expr)->getBase();
  10863. break;
  10864. }
  10865. case Stmt::OMPArraySectionExprClass: {
  10866. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  10867. if (ASE->getLowerBound())
  10868. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  10869. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  10870. return;
  10871. }
  10872. case Stmt::UnaryOperatorClass: {
  10873. // Only unwrap the * and & unary operators
  10874. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  10875. expr = UO->getSubExpr();
  10876. switch (UO->getOpcode()) {
  10877. case UO_AddrOf:
  10878. AllowOnePastEnd++;
  10879. break;
  10880. case UO_Deref:
  10881. AllowOnePastEnd--;
  10882. break;
  10883. default:
  10884. return;
  10885. }
  10886. break;
  10887. }
  10888. case Stmt::ConditionalOperatorClass: {
  10889. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  10890. if (const Expr *lhs = cond->getLHS())
  10891. CheckArrayAccess(lhs);
  10892. if (const Expr *rhs = cond->getRHS())
  10893. CheckArrayAccess(rhs);
  10894. return;
  10895. }
  10896. case Stmt::CXXOperatorCallExprClass: {
  10897. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  10898. for (const auto *Arg : OCE->arguments())
  10899. CheckArrayAccess(Arg);
  10900. return;
  10901. }
  10902. default:
  10903. return;
  10904. }
  10905. }
  10906. }
  10907. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  10908. namespace {
  10909. struct RetainCycleOwner {
  10910. VarDecl *Variable = nullptr;
  10911. SourceRange Range;
  10912. SourceLocation Loc;
  10913. bool Indirect = false;
  10914. RetainCycleOwner() = default;
  10915. void setLocsFrom(Expr *e) {
  10916. Loc = e->getExprLoc();
  10917. Range = e->getSourceRange();
  10918. }
  10919. };
  10920. } // namespace
  10921. /// Consider whether capturing the given variable can possibly lead to
  10922. /// a retain cycle.
  10923. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  10924. // In ARC, it's captured strongly iff the variable has __strong
  10925. // lifetime. In MRR, it's captured strongly if the variable is
  10926. // __block and has an appropriate type.
  10927. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  10928. return false;
  10929. owner.Variable = var;
  10930. if (ref)
  10931. owner.setLocsFrom(ref);
  10932. return true;
  10933. }
  10934. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  10935. while (true) {
  10936. e = e->IgnoreParens();
  10937. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  10938. switch (cast->getCastKind()) {
  10939. case CK_BitCast:
  10940. case CK_LValueBitCast:
  10941. case CK_LValueToRValue:
  10942. case CK_ARCReclaimReturnedObject:
  10943. e = cast->getSubExpr();
  10944. continue;
  10945. default:
  10946. return false;
  10947. }
  10948. }
  10949. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  10950. ObjCIvarDecl *ivar = ref->getDecl();
  10951. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  10952. return false;
  10953. // Try to find a retain cycle in the base.
  10954. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  10955. return false;
  10956. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  10957. owner.Indirect = true;
  10958. return true;
  10959. }
  10960. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  10961. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  10962. if (!var) return false;
  10963. return considerVariable(var, ref, owner);
  10964. }
  10965. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  10966. if (member->isArrow()) return false;
  10967. // Don't count this as an indirect ownership.
  10968. e = member->getBase();
  10969. continue;
  10970. }
  10971. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  10972. // Only pay attention to pseudo-objects on property references.
  10973. ObjCPropertyRefExpr *pre
  10974. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  10975. ->IgnoreParens());
  10976. if (!pre) return false;
  10977. if (pre->isImplicitProperty()) return false;
  10978. ObjCPropertyDecl *property = pre->getExplicitProperty();
  10979. if (!property->isRetaining() &&
  10980. !(property->getPropertyIvarDecl() &&
  10981. property->getPropertyIvarDecl()->getType()
  10982. .getObjCLifetime() == Qualifiers::OCL_Strong))
  10983. return false;
  10984. owner.Indirect = true;
  10985. if (pre->isSuperReceiver()) {
  10986. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  10987. if (!owner.Variable)
  10988. return false;
  10989. owner.Loc = pre->getLocation();
  10990. owner.Range = pre->getSourceRange();
  10991. return true;
  10992. }
  10993. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  10994. ->getSourceExpr());
  10995. continue;
  10996. }
  10997. // Array ivars?
  10998. return false;
  10999. }
  11000. }
  11001. namespace {
  11002. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  11003. ASTContext &Context;
  11004. VarDecl *Variable;
  11005. Expr *Capturer = nullptr;
  11006. bool VarWillBeReased = false;
  11007. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  11008. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  11009. Context(Context), Variable(variable) {}
  11010. void VisitDeclRefExpr(DeclRefExpr *ref) {
  11011. if (ref->getDecl() == Variable && !Capturer)
  11012. Capturer = ref;
  11013. }
  11014. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  11015. if (Capturer) return;
  11016. Visit(ref->getBase());
  11017. if (Capturer && ref->isFreeIvar())
  11018. Capturer = ref;
  11019. }
  11020. void VisitBlockExpr(BlockExpr *block) {
  11021. // Look inside nested blocks
  11022. if (block->getBlockDecl()->capturesVariable(Variable))
  11023. Visit(block->getBlockDecl()->getBody());
  11024. }
  11025. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  11026. if (Capturer) return;
  11027. if (OVE->getSourceExpr())
  11028. Visit(OVE->getSourceExpr());
  11029. }
  11030. void VisitBinaryOperator(BinaryOperator *BinOp) {
  11031. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  11032. return;
  11033. Expr *LHS = BinOp->getLHS();
  11034. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  11035. if (DRE->getDecl() != Variable)
  11036. return;
  11037. if (Expr *RHS = BinOp->getRHS()) {
  11038. RHS = RHS->IgnoreParenCasts();
  11039. llvm::APSInt Value;
  11040. VarWillBeReased =
  11041. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  11042. }
  11043. }
  11044. }
  11045. };
  11046. } // namespace
  11047. /// Check whether the given argument is a block which captures a
  11048. /// variable.
  11049. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11050. assert(owner.Variable && owner.Loc.isValid());
  11051. e = e->IgnoreParenCasts();
  11052. // Look through [^{...} copy] and Block_copy(^{...}).
  11053. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  11054. Selector Cmd = ME->getSelector();
  11055. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  11056. e = ME->getInstanceReceiver();
  11057. if (!e)
  11058. return nullptr;
  11059. e = e->IgnoreParenCasts();
  11060. }
  11061. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  11062. if (CE->getNumArgs() == 1) {
  11063. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  11064. if (Fn) {
  11065. const IdentifierInfo *FnI = Fn->getIdentifier();
  11066. if (FnI && FnI->isStr("_Block_copy")) {
  11067. e = CE->getArg(0)->IgnoreParenCasts();
  11068. }
  11069. }
  11070. }
  11071. }
  11072. BlockExpr *block = dyn_cast<BlockExpr>(e);
  11073. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  11074. return nullptr;
  11075. FindCaptureVisitor visitor(S.Context, owner.Variable);
  11076. visitor.Visit(block->getBlockDecl()->getBody());
  11077. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  11078. }
  11079. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  11080. RetainCycleOwner &owner) {
  11081. assert(capturer);
  11082. assert(owner.Variable && owner.Loc.isValid());
  11083. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  11084. << owner.Variable << capturer->getSourceRange();
  11085. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  11086. << owner.Indirect << owner.Range;
  11087. }
  11088. /// Check for a keyword selector that starts with the word 'add' or
  11089. /// 'set'.
  11090. static bool isSetterLikeSelector(Selector sel) {
  11091. if (sel.isUnarySelector()) return false;
  11092. StringRef str = sel.getNameForSlot(0);
  11093. while (!str.empty() && str.front() == '_') str = str.substr(1);
  11094. if (str.startswith("set"))
  11095. str = str.substr(3);
  11096. else if (str.startswith("add")) {
  11097. // Specially whitelist 'addOperationWithBlock:'.
  11098. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  11099. return false;
  11100. str = str.substr(3);
  11101. }
  11102. else
  11103. return false;
  11104. if (str.empty()) return true;
  11105. return !isLowercase(str.front());
  11106. }
  11107. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  11108. ObjCMessageExpr *Message) {
  11109. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  11110. Message->getReceiverInterface(),
  11111. NSAPI::ClassId_NSMutableArray);
  11112. if (!IsMutableArray) {
  11113. return None;
  11114. }
  11115. Selector Sel = Message->getSelector();
  11116. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  11117. S.NSAPIObj->getNSArrayMethodKind(Sel);
  11118. if (!MKOpt) {
  11119. return None;
  11120. }
  11121. NSAPI::NSArrayMethodKind MK = *MKOpt;
  11122. switch (MK) {
  11123. case NSAPI::NSMutableArr_addObject:
  11124. case NSAPI::NSMutableArr_insertObjectAtIndex:
  11125. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  11126. return 0;
  11127. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  11128. return 1;
  11129. default:
  11130. return None;
  11131. }
  11132. return None;
  11133. }
  11134. static
  11135. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  11136. ObjCMessageExpr *Message) {
  11137. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  11138. Message->getReceiverInterface(),
  11139. NSAPI::ClassId_NSMutableDictionary);
  11140. if (!IsMutableDictionary) {
  11141. return None;
  11142. }
  11143. Selector Sel = Message->getSelector();
  11144. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  11145. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  11146. if (!MKOpt) {
  11147. return None;
  11148. }
  11149. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  11150. switch (MK) {
  11151. case NSAPI::NSMutableDict_setObjectForKey:
  11152. case NSAPI::NSMutableDict_setValueForKey:
  11153. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  11154. return 0;
  11155. default:
  11156. return None;
  11157. }
  11158. return None;
  11159. }
  11160. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  11161. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  11162. Message->getReceiverInterface(),
  11163. NSAPI::ClassId_NSMutableSet);
  11164. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  11165. Message->getReceiverInterface(),
  11166. NSAPI::ClassId_NSMutableOrderedSet);
  11167. if (!IsMutableSet && !IsMutableOrderedSet) {
  11168. return None;
  11169. }
  11170. Selector Sel = Message->getSelector();
  11171. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  11172. if (!MKOpt) {
  11173. return None;
  11174. }
  11175. NSAPI::NSSetMethodKind MK = *MKOpt;
  11176. switch (MK) {
  11177. case NSAPI::NSMutableSet_addObject:
  11178. case NSAPI::NSOrderedSet_setObjectAtIndex:
  11179. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  11180. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  11181. return 0;
  11182. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  11183. return 1;
  11184. }
  11185. return None;
  11186. }
  11187. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  11188. if (!Message->isInstanceMessage()) {
  11189. return;
  11190. }
  11191. Optional<int> ArgOpt;
  11192. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  11193. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  11194. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  11195. return;
  11196. }
  11197. int ArgIndex = *ArgOpt;
  11198. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  11199. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  11200. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  11201. }
  11202. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  11203. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11204. if (ArgRE->isObjCSelfExpr()) {
  11205. Diag(Message->getSourceRange().getBegin(),
  11206. diag::warn_objc_circular_container)
  11207. << ArgRE->getDecl() << StringRef("'super'");
  11208. }
  11209. }
  11210. } else {
  11211. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  11212. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  11213. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  11214. }
  11215. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  11216. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11217. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  11218. ValueDecl *Decl = ReceiverRE->getDecl();
  11219. Diag(Message->getSourceRange().getBegin(),
  11220. diag::warn_objc_circular_container)
  11221. << Decl << Decl;
  11222. if (!ArgRE->isObjCSelfExpr()) {
  11223. Diag(Decl->getLocation(),
  11224. diag::note_objc_circular_container_declared_here)
  11225. << Decl;
  11226. }
  11227. }
  11228. }
  11229. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  11230. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  11231. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  11232. ObjCIvarDecl *Decl = IvarRE->getDecl();
  11233. Diag(Message->getSourceRange().getBegin(),
  11234. diag::warn_objc_circular_container)
  11235. << Decl << Decl;
  11236. Diag(Decl->getLocation(),
  11237. diag::note_objc_circular_container_declared_here)
  11238. << Decl;
  11239. }
  11240. }
  11241. }
  11242. }
  11243. }
  11244. /// Check a message send to see if it's likely to cause a retain cycle.
  11245. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  11246. // Only check instance methods whose selector looks like a setter.
  11247. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  11248. return;
  11249. // Try to find a variable that the receiver is strongly owned by.
  11250. RetainCycleOwner owner;
  11251. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  11252. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  11253. return;
  11254. } else {
  11255. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  11256. owner.Variable = getCurMethodDecl()->getSelfDecl();
  11257. owner.Loc = msg->getSuperLoc();
  11258. owner.Range = msg->getSuperLoc();
  11259. }
  11260. // Check whether the receiver is captured by any of the arguments.
  11261. const ObjCMethodDecl *MD = msg->getMethodDecl();
  11262. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  11263. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  11264. // noescape blocks should not be retained by the method.
  11265. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  11266. continue;
  11267. return diagnoseRetainCycle(*this, capturer, owner);
  11268. }
  11269. }
  11270. }
  11271. /// Check a property assign to see if it's likely to cause a retain cycle.
  11272. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  11273. RetainCycleOwner owner;
  11274. if (!findRetainCycleOwner(*this, receiver, owner))
  11275. return;
  11276. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  11277. diagnoseRetainCycle(*this, capturer, owner);
  11278. }
  11279. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  11280. RetainCycleOwner Owner;
  11281. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  11282. return;
  11283. // Because we don't have an expression for the variable, we have to set the
  11284. // location explicitly here.
  11285. Owner.Loc = Var->getLocation();
  11286. Owner.Range = Var->getSourceRange();
  11287. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  11288. diagnoseRetainCycle(*this, Capturer, Owner);
  11289. }
  11290. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  11291. Expr *RHS, bool isProperty) {
  11292. // Check if RHS is an Objective-C object literal, which also can get
  11293. // immediately zapped in a weak reference. Note that we explicitly
  11294. // allow ObjCStringLiterals, since those are designed to never really die.
  11295. RHS = RHS->IgnoreParenImpCasts();
  11296. // This enum needs to match with the 'select' in
  11297. // warn_objc_arc_literal_assign (off-by-1).
  11298. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  11299. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  11300. return false;
  11301. S.Diag(Loc, diag::warn_arc_literal_assign)
  11302. << (unsigned) Kind
  11303. << (isProperty ? 0 : 1)
  11304. << RHS->getSourceRange();
  11305. return true;
  11306. }
  11307. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  11308. Qualifiers::ObjCLifetime LT,
  11309. Expr *RHS, bool isProperty) {
  11310. // Strip off any implicit cast added to get to the one ARC-specific.
  11311. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11312. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11313. S.Diag(Loc, diag::warn_arc_retained_assign)
  11314. << (LT == Qualifiers::OCL_ExplicitNone)
  11315. << (isProperty ? 0 : 1)
  11316. << RHS->getSourceRange();
  11317. return true;
  11318. }
  11319. RHS = cast->getSubExpr();
  11320. }
  11321. if (LT == Qualifiers::OCL_Weak &&
  11322. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  11323. return true;
  11324. return false;
  11325. }
  11326. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  11327. QualType LHS, Expr *RHS) {
  11328. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  11329. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  11330. return false;
  11331. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  11332. return true;
  11333. return false;
  11334. }
  11335. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  11336. Expr *LHS, Expr *RHS) {
  11337. QualType LHSType;
  11338. // PropertyRef on LHS type need be directly obtained from
  11339. // its declaration as it has a PseudoType.
  11340. ObjCPropertyRefExpr *PRE
  11341. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  11342. if (PRE && !PRE->isImplicitProperty()) {
  11343. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11344. if (PD)
  11345. LHSType = PD->getType();
  11346. }
  11347. if (LHSType.isNull())
  11348. LHSType = LHS->getType();
  11349. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  11350. if (LT == Qualifiers::OCL_Weak) {
  11351. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  11352. getCurFunction()->markSafeWeakUse(LHS);
  11353. }
  11354. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  11355. return;
  11356. // FIXME. Check for other life times.
  11357. if (LT != Qualifiers::OCL_None)
  11358. return;
  11359. if (PRE) {
  11360. if (PRE->isImplicitProperty())
  11361. return;
  11362. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11363. if (!PD)
  11364. return;
  11365. unsigned Attributes = PD->getPropertyAttributes();
  11366. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  11367. // when 'assign' attribute was not explicitly specified
  11368. // by user, ignore it and rely on property type itself
  11369. // for lifetime info.
  11370. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  11371. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  11372. LHSType->isObjCRetainableType())
  11373. return;
  11374. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11375. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11376. Diag(Loc, diag::warn_arc_retained_property_assign)
  11377. << RHS->getSourceRange();
  11378. return;
  11379. }
  11380. RHS = cast->getSubExpr();
  11381. }
  11382. }
  11383. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  11384. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  11385. return;
  11386. }
  11387. }
  11388. }
  11389. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  11390. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  11391. SourceLocation StmtLoc,
  11392. const NullStmt *Body) {
  11393. // Do not warn if the body is a macro that expands to nothing, e.g:
  11394. //
  11395. // #define CALL(x)
  11396. // if (condition)
  11397. // CALL(0);
  11398. if (Body->hasLeadingEmptyMacro())
  11399. return false;
  11400. // Get line numbers of statement and body.
  11401. bool StmtLineInvalid;
  11402. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  11403. &StmtLineInvalid);
  11404. if (StmtLineInvalid)
  11405. return false;
  11406. bool BodyLineInvalid;
  11407. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  11408. &BodyLineInvalid);
  11409. if (BodyLineInvalid)
  11410. return false;
  11411. // Warn if null statement and body are on the same line.
  11412. if (StmtLine != BodyLine)
  11413. return false;
  11414. return true;
  11415. }
  11416. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  11417. const Stmt *Body,
  11418. unsigned DiagID) {
  11419. // Since this is a syntactic check, don't emit diagnostic for template
  11420. // instantiations, this just adds noise.
  11421. if (CurrentInstantiationScope)
  11422. return;
  11423. // The body should be a null statement.
  11424. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  11425. if (!NBody)
  11426. return;
  11427. // Do the usual checks.
  11428. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  11429. return;
  11430. Diag(NBody->getSemiLoc(), DiagID);
  11431. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  11432. }
  11433. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  11434. const Stmt *PossibleBody) {
  11435. assert(!CurrentInstantiationScope); // Ensured by caller
  11436. SourceLocation StmtLoc;
  11437. const Stmt *Body;
  11438. unsigned DiagID;
  11439. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  11440. StmtLoc = FS->getRParenLoc();
  11441. Body = FS->getBody();
  11442. DiagID = diag::warn_empty_for_body;
  11443. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  11444. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  11445. Body = WS->getBody();
  11446. DiagID = diag::warn_empty_while_body;
  11447. } else
  11448. return; // Neither `for' nor `while'.
  11449. // The body should be a null statement.
  11450. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  11451. if (!NBody)
  11452. return;
  11453. // Skip expensive checks if diagnostic is disabled.
  11454. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  11455. return;
  11456. // Do the usual checks.
  11457. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  11458. return;
  11459. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  11460. // noise level low, emit diagnostics only if for/while is followed by a
  11461. // CompoundStmt, e.g.:
  11462. // for (int i = 0; i < n; i++);
  11463. // {
  11464. // a(i);
  11465. // }
  11466. // or if for/while is followed by a statement with more indentation
  11467. // than for/while itself:
  11468. // for (int i = 0; i < n; i++);
  11469. // a(i);
  11470. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  11471. if (!ProbableTypo) {
  11472. bool BodyColInvalid;
  11473. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  11474. PossibleBody->getLocStart(),
  11475. &BodyColInvalid);
  11476. if (BodyColInvalid)
  11477. return;
  11478. bool StmtColInvalid;
  11479. unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
  11480. S->getLocStart(),
  11481. &StmtColInvalid);
  11482. if (StmtColInvalid)
  11483. return;
  11484. if (BodyCol > StmtCol)
  11485. ProbableTypo = true;
  11486. }
  11487. if (ProbableTypo) {
  11488. Diag(NBody->getSemiLoc(), DiagID);
  11489. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  11490. }
  11491. }
  11492. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  11493. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  11494. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  11495. SourceLocation OpLoc) {
  11496. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  11497. return;
  11498. if (inTemplateInstantiation())
  11499. return;
  11500. // Strip parens and casts away.
  11501. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  11502. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  11503. // Check for a call expression
  11504. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  11505. if (!CE || CE->getNumArgs() != 1)
  11506. return;
  11507. // Check for a call to std::move
  11508. if (!CE->isCallToStdMove())
  11509. return;
  11510. // Get argument from std::move
  11511. RHSExpr = CE->getArg(0);
  11512. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  11513. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  11514. // Two DeclRefExpr's, check that the decls are the same.
  11515. if (LHSDeclRef && RHSDeclRef) {
  11516. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  11517. return;
  11518. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  11519. RHSDeclRef->getDecl()->getCanonicalDecl())
  11520. return;
  11521. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  11522. << LHSExpr->getSourceRange()
  11523. << RHSExpr->getSourceRange();
  11524. return;
  11525. }
  11526. // Member variables require a different approach to check for self moves.
  11527. // MemberExpr's are the same if every nested MemberExpr refers to the same
  11528. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  11529. // the base Expr's are CXXThisExpr's.
  11530. const Expr *LHSBase = LHSExpr;
  11531. const Expr *RHSBase = RHSExpr;
  11532. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  11533. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  11534. if (!LHSME || !RHSME)
  11535. return;
  11536. while (LHSME && RHSME) {
  11537. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  11538. RHSME->getMemberDecl()->getCanonicalDecl())
  11539. return;
  11540. LHSBase = LHSME->getBase();
  11541. RHSBase = RHSME->getBase();
  11542. LHSME = dyn_cast<MemberExpr>(LHSBase);
  11543. RHSME = dyn_cast<MemberExpr>(RHSBase);
  11544. }
  11545. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  11546. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  11547. if (LHSDeclRef && RHSDeclRef) {
  11548. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  11549. return;
  11550. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  11551. RHSDeclRef->getDecl()->getCanonicalDecl())
  11552. return;
  11553. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  11554. << LHSExpr->getSourceRange()
  11555. << RHSExpr->getSourceRange();
  11556. return;
  11557. }
  11558. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  11559. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  11560. << LHSExpr->getSourceRange()
  11561. << RHSExpr->getSourceRange();
  11562. }
  11563. //===--- Layout compatibility ----------------------------------------------//
  11564. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  11565. /// Check if two enumeration types are layout-compatible.
  11566. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  11567. // C++11 [dcl.enum] p8:
  11568. // Two enumeration types are layout-compatible if they have the same
  11569. // underlying type.
  11570. return ED1->isComplete() && ED2->isComplete() &&
  11571. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  11572. }
  11573. /// Check if two fields are layout-compatible.
  11574. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  11575. FieldDecl *Field2) {
  11576. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  11577. return false;
  11578. if (Field1->isBitField() != Field2->isBitField())
  11579. return false;
  11580. if (Field1->isBitField()) {
  11581. // Make sure that the bit-fields are the same length.
  11582. unsigned Bits1 = Field1->getBitWidthValue(C);
  11583. unsigned Bits2 = Field2->getBitWidthValue(C);
  11584. if (Bits1 != Bits2)
  11585. return false;
  11586. }
  11587. return true;
  11588. }
  11589. /// Check if two standard-layout structs are layout-compatible.
  11590. /// (C++11 [class.mem] p17)
  11591. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  11592. RecordDecl *RD2) {
  11593. // If both records are C++ classes, check that base classes match.
  11594. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  11595. // If one of records is a CXXRecordDecl we are in C++ mode,
  11596. // thus the other one is a CXXRecordDecl, too.
  11597. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  11598. // Check number of base classes.
  11599. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  11600. return false;
  11601. // Check the base classes.
  11602. for (CXXRecordDecl::base_class_const_iterator
  11603. Base1 = D1CXX->bases_begin(),
  11604. BaseEnd1 = D1CXX->bases_end(),
  11605. Base2 = D2CXX->bases_begin();
  11606. Base1 != BaseEnd1;
  11607. ++Base1, ++Base2) {
  11608. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  11609. return false;
  11610. }
  11611. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  11612. // If only RD2 is a C++ class, it should have zero base classes.
  11613. if (D2CXX->getNumBases() > 0)
  11614. return false;
  11615. }
  11616. // Check the fields.
  11617. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  11618. Field2End = RD2->field_end(),
  11619. Field1 = RD1->field_begin(),
  11620. Field1End = RD1->field_end();
  11621. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  11622. if (!isLayoutCompatible(C, *Field1, *Field2))
  11623. return false;
  11624. }
  11625. if (Field1 != Field1End || Field2 != Field2End)
  11626. return false;
  11627. return true;
  11628. }
  11629. /// Check if two standard-layout unions are layout-compatible.
  11630. /// (C++11 [class.mem] p18)
  11631. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  11632. RecordDecl *RD2) {
  11633. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  11634. for (auto *Field2 : RD2->fields())
  11635. UnmatchedFields.insert(Field2);
  11636. for (auto *Field1 : RD1->fields()) {
  11637. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  11638. I = UnmatchedFields.begin(),
  11639. E = UnmatchedFields.end();
  11640. for ( ; I != E; ++I) {
  11641. if (isLayoutCompatible(C, Field1, *I)) {
  11642. bool Result = UnmatchedFields.erase(*I);
  11643. (void) Result;
  11644. assert(Result);
  11645. break;
  11646. }
  11647. }
  11648. if (I == E)
  11649. return false;
  11650. }
  11651. return UnmatchedFields.empty();
  11652. }
  11653. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  11654. RecordDecl *RD2) {
  11655. if (RD1->isUnion() != RD2->isUnion())
  11656. return false;
  11657. if (RD1->isUnion())
  11658. return isLayoutCompatibleUnion(C, RD1, RD2);
  11659. else
  11660. return isLayoutCompatibleStruct(C, RD1, RD2);
  11661. }
  11662. /// Check if two types are layout-compatible in C++11 sense.
  11663. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  11664. if (T1.isNull() || T2.isNull())
  11665. return false;
  11666. // C++11 [basic.types] p11:
  11667. // If two types T1 and T2 are the same type, then T1 and T2 are
  11668. // layout-compatible types.
  11669. if (C.hasSameType(T1, T2))
  11670. return true;
  11671. T1 = T1.getCanonicalType().getUnqualifiedType();
  11672. T2 = T2.getCanonicalType().getUnqualifiedType();
  11673. const Type::TypeClass TC1 = T1->getTypeClass();
  11674. const Type::TypeClass TC2 = T2->getTypeClass();
  11675. if (TC1 != TC2)
  11676. return false;
  11677. if (TC1 == Type::Enum) {
  11678. return isLayoutCompatible(C,
  11679. cast<EnumType>(T1)->getDecl(),
  11680. cast<EnumType>(T2)->getDecl());
  11681. } else if (TC1 == Type::Record) {
  11682. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  11683. return false;
  11684. return isLayoutCompatible(C,
  11685. cast<RecordType>(T1)->getDecl(),
  11686. cast<RecordType>(T2)->getDecl());
  11687. }
  11688. return false;
  11689. }
  11690. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  11691. /// Given a type tag expression find the type tag itself.
  11692. ///
  11693. /// \param TypeExpr Type tag expression, as it appears in user's code.
  11694. ///
  11695. /// \param VD Declaration of an identifier that appears in a type tag.
  11696. ///
  11697. /// \param MagicValue Type tag magic value.
  11698. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  11699. const ValueDecl **VD, uint64_t *MagicValue) {
  11700. while(true) {
  11701. if (!TypeExpr)
  11702. return false;
  11703. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  11704. switch (TypeExpr->getStmtClass()) {
  11705. case Stmt::UnaryOperatorClass: {
  11706. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  11707. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  11708. TypeExpr = UO->getSubExpr();
  11709. continue;
  11710. }
  11711. return false;
  11712. }
  11713. case Stmt::DeclRefExprClass: {
  11714. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  11715. *VD = DRE->getDecl();
  11716. return true;
  11717. }
  11718. case Stmt::IntegerLiteralClass: {
  11719. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  11720. llvm::APInt MagicValueAPInt = IL->getValue();
  11721. if (MagicValueAPInt.getActiveBits() <= 64) {
  11722. *MagicValue = MagicValueAPInt.getZExtValue();
  11723. return true;
  11724. } else
  11725. return false;
  11726. }
  11727. case Stmt::BinaryConditionalOperatorClass:
  11728. case Stmt::ConditionalOperatorClass: {
  11729. const AbstractConditionalOperator *ACO =
  11730. cast<AbstractConditionalOperator>(TypeExpr);
  11731. bool Result;
  11732. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  11733. if (Result)
  11734. TypeExpr = ACO->getTrueExpr();
  11735. else
  11736. TypeExpr = ACO->getFalseExpr();
  11737. continue;
  11738. }
  11739. return false;
  11740. }
  11741. case Stmt::BinaryOperatorClass: {
  11742. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  11743. if (BO->getOpcode() == BO_Comma) {
  11744. TypeExpr = BO->getRHS();
  11745. continue;
  11746. }
  11747. return false;
  11748. }
  11749. default:
  11750. return false;
  11751. }
  11752. }
  11753. }
  11754. /// Retrieve the C type corresponding to type tag TypeExpr.
  11755. ///
  11756. /// \param TypeExpr Expression that specifies a type tag.
  11757. ///
  11758. /// \param MagicValues Registered magic values.
  11759. ///
  11760. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  11761. /// kind.
  11762. ///
  11763. /// \param TypeInfo Information about the corresponding C type.
  11764. ///
  11765. /// \returns true if the corresponding C type was found.
  11766. static bool GetMatchingCType(
  11767. const IdentifierInfo *ArgumentKind,
  11768. const Expr *TypeExpr, const ASTContext &Ctx,
  11769. const llvm::DenseMap<Sema::TypeTagMagicValue,
  11770. Sema::TypeTagData> *MagicValues,
  11771. bool &FoundWrongKind,
  11772. Sema::TypeTagData &TypeInfo) {
  11773. FoundWrongKind = false;
  11774. // Variable declaration that has type_tag_for_datatype attribute.
  11775. const ValueDecl *VD = nullptr;
  11776. uint64_t MagicValue;
  11777. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  11778. return false;
  11779. if (VD) {
  11780. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  11781. if (I->getArgumentKind() != ArgumentKind) {
  11782. FoundWrongKind = true;
  11783. return false;
  11784. }
  11785. TypeInfo.Type = I->getMatchingCType();
  11786. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  11787. TypeInfo.MustBeNull = I->getMustBeNull();
  11788. return true;
  11789. }
  11790. return false;
  11791. }
  11792. if (!MagicValues)
  11793. return false;
  11794. llvm::DenseMap<Sema::TypeTagMagicValue,
  11795. Sema::TypeTagData>::const_iterator I =
  11796. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  11797. if (I == MagicValues->end())
  11798. return false;
  11799. TypeInfo = I->second;
  11800. return true;
  11801. }
  11802. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  11803. uint64_t MagicValue, QualType Type,
  11804. bool LayoutCompatible,
  11805. bool MustBeNull) {
  11806. if (!TypeTagForDatatypeMagicValues)
  11807. TypeTagForDatatypeMagicValues.reset(
  11808. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  11809. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  11810. (*TypeTagForDatatypeMagicValues)[Magic] =
  11811. TypeTagData(Type, LayoutCompatible, MustBeNull);
  11812. }
  11813. static bool IsSameCharType(QualType T1, QualType T2) {
  11814. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  11815. if (!BT1)
  11816. return false;
  11817. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  11818. if (!BT2)
  11819. return false;
  11820. BuiltinType::Kind T1Kind = BT1->getKind();
  11821. BuiltinType::Kind T2Kind = BT2->getKind();
  11822. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  11823. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  11824. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  11825. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  11826. }
  11827. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  11828. const ArrayRef<const Expr *> ExprArgs,
  11829. SourceLocation CallSiteLoc) {
  11830. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  11831. bool IsPointerAttr = Attr->getIsPointer();
  11832. // Retrieve the argument representing the 'type_tag'.
  11833. unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
  11834. if (TypeTagIdxAST >= ExprArgs.size()) {
  11835. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  11836. << 0 << Attr->getTypeTagIdx().getSourceIndex();
  11837. return;
  11838. }
  11839. const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
  11840. bool FoundWrongKind;
  11841. TypeTagData TypeInfo;
  11842. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  11843. TypeTagForDatatypeMagicValues.get(),
  11844. FoundWrongKind, TypeInfo)) {
  11845. if (FoundWrongKind)
  11846. Diag(TypeTagExpr->getExprLoc(),
  11847. diag::warn_type_tag_for_datatype_wrong_kind)
  11848. << TypeTagExpr->getSourceRange();
  11849. return;
  11850. }
  11851. // Retrieve the argument representing the 'arg_idx'.
  11852. unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
  11853. if (ArgumentIdxAST >= ExprArgs.size()) {
  11854. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  11855. << 1 << Attr->getArgumentIdx().getSourceIndex();
  11856. return;
  11857. }
  11858. const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
  11859. if (IsPointerAttr) {
  11860. // Skip implicit cast of pointer to `void *' (as a function argument).
  11861. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  11862. if (ICE->getType()->isVoidPointerType() &&
  11863. ICE->getCastKind() == CK_BitCast)
  11864. ArgumentExpr = ICE->getSubExpr();
  11865. }
  11866. QualType ArgumentType = ArgumentExpr->getType();
  11867. // Passing a `void*' pointer shouldn't trigger a warning.
  11868. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  11869. return;
  11870. if (TypeInfo.MustBeNull) {
  11871. // Type tag with matching void type requires a null pointer.
  11872. if (!ArgumentExpr->isNullPointerConstant(Context,
  11873. Expr::NPC_ValueDependentIsNotNull)) {
  11874. Diag(ArgumentExpr->getExprLoc(),
  11875. diag::warn_type_safety_null_pointer_required)
  11876. << ArgumentKind->getName()
  11877. << ArgumentExpr->getSourceRange()
  11878. << TypeTagExpr->getSourceRange();
  11879. }
  11880. return;
  11881. }
  11882. QualType RequiredType = TypeInfo.Type;
  11883. if (IsPointerAttr)
  11884. RequiredType = Context.getPointerType(RequiredType);
  11885. bool mismatch = false;
  11886. if (!TypeInfo.LayoutCompatible) {
  11887. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  11888. // C++11 [basic.fundamental] p1:
  11889. // Plain char, signed char, and unsigned char are three distinct types.
  11890. //
  11891. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  11892. // char' depending on the current char signedness mode.
  11893. if (mismatch)
  11894. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  11895. RequiredType->getPointeeType())) ||
  11896. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  11897. mismatch = false;
  11898. } else
  11899. if (IsPointerAttr)
  11900. mismatch = !isLayoutCompatible(Context,
  11901. ArgumentType->getPointeeType(),
  11902. RequiredType->getPointeeType());
  11903. else
  11904. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  11905. if (mismatch)
  11906. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  11907. << ArgumentType << ArgumentKind
  11908. << TypeInfo.LayoutCompatible << RequiredType
  11909. << ArgumentExpr->getSourceRange()
  11910. << TypeTagExpr->getSourceRange();
  11911. }
  11912. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  11913. CharUnits Alignment) {
  11914. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  11915. }
  11916. void Sema::DiagnoseMisalignedMembers() {
  11917. for (MisalignedMember &m : MisalignedMembers) {
  11918. const NamedDecl *ND = m.RD;
  11919. if (ND->getName().empty()) {
  11920. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  11921. ND = TD;
  11922. }
  11923. Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
  11924. << m.MD << ND << m.E->getSourceRange();
  11925. }
  11926. MisalignedMembers.clear();
  11927. }
  11928. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  11929. E = E->IgnoreParens();
  11930. if (!T->isPointerType() && !T->isIntegerType())
  11931. return;
  11932. if (isa<UnaryOperator>(E) &&
  11933. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  11934. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  11935. if (isa<MemberExpr>(Op)) {
  11936. auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
  11937. MisalignedMember(Op));
  11938. if (MA != MisalignedMembers.end() &&
  11939. (T->isIntegerType() ||
  11940. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  11941. Context.getTypeAlignInChars(
  11942. T->getPointeeType()) <= MA->Alignment))))
  11943. MisalignedMembers.erase(MA);
  11944. }
  11945. }
  11946. }
  11947. void Sema::RefersToMemberWithReducedAlignment(
  11948. Expr *E,
  11949. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  11950. Action) {
  11951. const auto *ME = dyn_cast<MemberExpr>(E);
  11952. if (!ME)
  11953. return;
  11954. // No need to check expressions with an __unaligned-qualified type.
  11955. if (E->getType().getQualifiers().hasUnaligned())
  11956. return;
  11957. // For a chain of MemberExpr like "a.b.c.d" this list
  11958. // will keep FieldDecl's like [d, c, b].
  11959. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  11960. const MemberExpr *TopME = nullptr;
  11961. bool AnyIsPacked = false;
  11962. do {
  11963. QualType BaseType = ME->getBase()->getType();
  11964. if (ME->isArrow())
  11965. BaseType = BaseType->getPointeeType();
  11966. RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
  11967. if (RD->isInvalidDecl())
  11968. return;
  11969. ValueDecl *MD = ME->getMemberDecl();
  11970. auto *FD = dyn_cast<FieldDecl>(MD);
  11971. // We do not care about non-data members.
  11972. if (!FD || FD->isInvalidDecl())
  11973. return;
  11974. AnyIsPacked =
  11975. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  11976. ReverseMemberChain.push_back(FD);
  11977. TopME = ME;
  11978. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  11979. } while (ME);
  11980. assert(TopME && "We did not compute a topmost MemberExpr!");
  11981. // Not the scope of this diagnostic.
  11982. if (!AnyIsPacked)
  11983. return;
  11984. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  11985. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  11986. // TODO: The innermost base of the member expression may be too complicated.
  11987. // For now, just disregard these cases. This is left for future
  11988. // improvement.
  11989. if (!DRE && !isa<CXXThisExpr>(TopBase))
  11990. return;
  11991. // Alignment expected by the whole expression.
  11992. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  11993. // No need to do anything else with this case.
  11994. if (ExpectedAlignment.isOne())
  11995. return;
  11996. // Synthesize offset of the whole access.
  11997. CharUnits Offset;
  11998. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  11999. I++) {
  12000. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  12001. }
  12002. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  12003. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  12004. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  12005. // The base expression of the innermost MemberExpr may give
  12006. // stronger guarantees than the class containing the member.
  12007. if (DRE && !TopME->isArrow()) {
  12008. const ValueDecl *VD = DRE->getDecl();
  12009. if (!VD->getType()->isReferenceType())
  12010. CompleteObjectAlignment =
  12011. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  12012. }
  12013. // Check if the synthesized offset fulfills the alignment.
  12014. if (Offset % ExpectedAlignment != 0 ||
  12015. // It may fulfill the offset it but the effective alignment may still be
  12016. // lower than the expected expression alignment.
  12017. CompleteObjectAlignment < ExpectedAlignment) {
  12018. // If this happens, we want to determine a sensible culprit of this.
  12019. // Intuitively, watching the chain of member expressions from right to
  12020. // left, we start with the required alignment (as required by the field
  12021. // type) but some packed attribute in that chain has reduced the alignment.
  12022. // It may happen that another packed structure increases it again. But if
  12023. // we are here such increase has not been enough. So pointing the first
  12024. // FieldDecl that either is packed or else its RecordDecl is,
  12025. // seems reasonable.
  12026. FieldDecl *FD = nullptr;
  12027. CharUnits Alignment;
  12028. for (FieldDecl *FDI : ReverseMemberChain) {
  12029. if (FDI->hasAttr<PackedAttr>() ||
  12030. FDI->getParent()->hasAttr<PackedAttr>()) {
  12031. FD = FDI;
  12032. Alignment = std::min(
  12033. Context.getTypeAlignInChars(FD->getType()),
  12034. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  12035. break;
  12036. }
  12037. }
  12038. assert(FD && "We did not find a packed FieldDecl!");
  12039. Action(E, FD->getParent(), FD, Alignment);
  12040. }
  12041. }
  12042. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  12043. using namespace std::placeholders;
  12044. RefersToMemberWithReducedAlignment(
  12045. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  12046. _2, _3, _4));
  12047. }