SemaChecking.cpp 534 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775
  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/FormatString.h"
  30. #include "clang/AST/NSAPI.h"
  31. #include "clang/AST/NonTrivialTypeVisitor.h"
  32. #include "clang/AST/OperationKinds.h"
  33. #include "clang/AST/Stmt.h"
  34. #include "clang/AST/TemplateBase.h"
  35. #include "clang/AST/Type.h"
  36. #include "clang/AST/TypeLoc.h"
  37. #include "clang/AST/UnresolvedSet.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->getEndLoc(), diag::err_typecheck_call_too_few_args)
  111. << 0 /*function call*/ << desiredArgCount << argCount
  112. << call->getSourceRange();
  113. // Highlight all the excess arguments.
  114. SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
  115. call->getArg(argCount - 1)->getEndLoc());
  116. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  117. << 0 /*function call*/ << desiredArgCount << argCount
  118. << call->getArg(1)->getSourceRange();
  119. }
  120. /// Check that the first argument to __builtin_annotation is an integer
  121. /// and the second argument is a non-wide string literal.
  122. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  123. if (checkArgCount(S, TheCall, 2))
  124. return true;
  125. // First argument should be an integer.
  126. Expr *ValArg = TheCall->getArg(0);
  127. QualType Ty = ValArg->getType();
  128. if (!Ty->isIntegerType()) {
  129. S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
  130. << ValArg->getSourceRange();
  131. return true;
  132. }
  133. // Second argument should be a constant string.
  134. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  135. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  136. if (!Literal || !Literal->isAscii()) {
  137. S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
  138. << StrArg->getSourceRange();
  139. return true;
  140. }
  141. TheCall->setType(Ty);
  142. return false;
  143. }
  144. static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
  145. // We need at least one argument.
  146. if (TheCall->getNumArgs() < 1) {
  147. S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  148. << 0 << 1 << TheCall->getNumArgs()
  149. << TheCall->getCallee()->getSourceRange();
  150. return true;
  151. }
  152. // All arguments should be wide string literals.
  153. for (Expr *Arg : TheCall->arguments()) {
  154. auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  155. if (!Literal || !Literal->isWide()) {
  156. S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
  157. << Arg->getSourceRange();
  158. return true;
  159. }
  160. }
  161. return false;
  162. }
  163. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  164. /// result type to the corresponding pointer type.
  165. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  166. if (checkArgCount(S, TheCall, 1))
  167. return true;
  168. ExprResult Arg(TheCall->getArg(0));
  169. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
  170. if (ResultType.isNull())
  171. return true;
  172. TheCall->setArg(0, Arg.get());
  173. TheCall->setType(ResultType);
  174. return false;
  175. }
  176. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
  177. if (checkArgCount(S, TheCall, 3))
  178. return true;
  179. // First two arguments should be integers.
  180. for (unsigned I = 0; I < 2; ++I) {
  181. ExprResult Arg = TheCall->getArg(I);
  182. QualType Ty = Arg.get()->getType();
  183. if (!Ty->isIntegerType()) {
  184. S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
  185. << Ty << Arg.get()->getSourceRange();
  186. return true;
  187. }
  188. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  189. S.getASTContext(), Ty, /*consume*/ false);
  190. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  191. if (Arg.isInvalid())
  192. return true;
  193. TheCall->setArg(I, Arg.get());
  194. }
  195. // Third argument should be a pointer to a non-const integer.
  196. // IRGen correctly handles volatile, restrict, and address spaces, and
  197. // the other qualifiers aren't possible.
  198. {
  199. ExprResult Arg = TheCall->getArg(2);
  200. QualType Ty = Arg.get()->getType();
  201. const auto *PtrTy = Ty->getAs<PointerType>();
  202. if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
  203. !PtrTy->getPointeeType().isConstQualified())) {
  204. S.Diag(Arg.get()->getBeginLoc(),
  205. diag::err_overflow_builtin_must_be_ptr_int)
  206. << Ty << Arg.get()->getSourceRange();
  207. return true;
  208. }
  209. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  210. S.getASTContext(), Ty, /*consume*/ false);
  211. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  212. if (Arg.isInvalid())
  213. return true;
  214. TheCall->setArg(2, Arg.get());
  215. }
  216. return false;
  217. }
  218. static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
  219. CallExpr *TheCall, unsigned SizeIdx,
  220. unsigned DstSizeIdx,
  221. StringRef LikelyMacroName) {
  222. if (TheCall->getNumArgs() <= SizeIdx ||
  223. TheCall->getNumArgs() <= DstSizeIdx)
  224. return;
  225. const Expr *SizeArg = TheCall->getArg(SizeIdx);
  226. const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
  227. llvm::APSInt Size, DstSize;
  228. // find out if both sizes are known at compile time
  229. if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
  230. !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
  231. return;
  232. if (Size.ule(DstSize))
  233. return;
  234. // Confirmed overflow, so generate the diagnostic.
  235. StringRef FunctionName = FDecl->getName();
  236. SourceLocation SL = TheCall->getBeginLoc();
  237. SourceManager &SM = S.getSourceManager();
  238. // If we're in an expansion of a macro whose name corresponds to this builtin,
  239. // use the simple macro name and location.
  240. if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) ==
  241. LikelyMacroName) {
  242. FunctionName = LikelyMacroName;
  243. SL = SM.getImmediateMacroCallerLoc(SL);
  244. }
  245. S.Diag(SL, diag::warn_memcpy_chk_overflow)
  246. << FunctionName << DstSize.toString(/*Radix=*/10)
  247. << Size.toString(/*Radix=*/10);
  248. }
  249. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  250. if (checkArgCount(S, BuiltinCall, 2))
  251. return true;
  252. SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
  253. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  254. Expr *Call = BuiltinCall->getArg(0);
  255. Expr *Chain = BuiltinCall->getArg(1);
  256. if (Call->getStmtClass() != Stmt::CallExprClass) {
  257. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  258. << Call->getSourceRange();
  259. return true;
  260. }
  261. auto CE = cast<CallExpr>(Call);
  262. if (CE->getCallee()->getType()->isBlockPointerType()) {
  263. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  264. << Call->getSourceRange();
  265. return true;
  266. }
  267. const Decl *TargetDecl = CE->getCalleeDecl();
  268. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  269. if (FD->getBuiltinID()) {
  270. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  271. << Call->getSourceRange();
  272. return true;
  273. }
  274. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  275. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  276. << Call->getSourceRange();
  277. return true;
  278. }
  279. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  280. if (ChainResult.isInvalid())
  281. return true;
  282. if (!ChainResult.get()->getType()->isPointerType()) {
  283. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  284. << Chain->getSourceRange();
  285. return true;
  286. }
  287. QualType ReturnTy = CE->getCallReturnType(S.Context);
  288. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  289. QualType BuiltinTy = S.Context.getFunctionType(
  290. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  291. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  292. Builtin =
  293. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  294. BuiltinCall->setType(CE->getType());
  295. BuiltinCall->setValueKind(CE->getValueKind());
  296. BuiltinCall->setObjectKind(CE->getObjectKind());
  297. BuiltinCall->setCallee(Builtin);
  298. BuiltinCall->setArg(1, ChainResult.get());
  299. return false;
  300. }
  301. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  302. Scope::ScopeFlags NeededScopeFlags,
  303. unsigned DiagID) {
  304. // Scopes aren't available during instantiation. Fortunately, builtin
  305. // functions cannot be template args so they cannot be formed through template
  306. // instantiation. Therefore checking once during the parse is sufficient.
  307. if (SemaRef.inTemplateInstantiation())
  308. return false;
  309. Scope *S = SemaRef.getCurScope();
  310. while (S && !S->isSEHExceptScope())
  311. S = S->getParent();
  312. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  313. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  314. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  315. << DRE->getDecl()->getIdentifier();
  316. return true;
  317. }
  318. return false;
  319. }
  320. static inline bool isBlockPointer(Expr *Arg) {
  321. return Arg->getType()->isBlockPointerType();
  322. }
  323. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  324. /// void*, which is a requirement of device side enqueue.
  325. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  326. const BlockPointerType *BPT =
  327. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  328. ArrayRef<QualType> Params =
  329. BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
  330. unsigned ArgCounter = 0;
  331. bool IllegalParams = false;
  332. // Iterate through the block parameters until either one is found that is not
  333. // a local void*, or the block is valid.
  334. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  335. I != E; ++I, ++ArgCounter) {
  336. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  337. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  338. LangAS::opencl_local) {
  339. // Get the location of the error. If a block literal has been passed
  340. // (BlockExpr) then we can point straight to the offending argument,
  341. // else we just point to the variable reference.
  342. SourceLocation ErrorLoc;
  343. if (isa<BlockExpr>(BlockArg)) {
  344. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  345. ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
  346. } else if (isa<DeclRefExpr>(BlockArg)) {
  347. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
  348. }
  349. S.Diag(ErrorLoc,
  350. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  351. IllegalParams = true;
  352. }
  353. }
  354. return IllegalParams;
  355. }
  356. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  357. if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
  358. S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
  359. << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
  360. return true;
  361. }
  362. return false;
  363. }
  364. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  365. if (checkArgCount(S, TheCall, 2))
  366. return true;
  367. if (checkOpenCLSubgroupExt(S, TheCall))
  368. return true;
  369. // First argument is an ndrange_t type.
  370. Expr *NDRangeArg = TheCall->getArg(0);
  371. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  372. S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  373. << TheCall->getDirectCallee() << "'ndrange_t'";
  374. return true;
  375. }
  376. Expr *BlockArg = TheCall->getArg(1);
  377. if (!isBlockPointer(BlockArg)) {
  378. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  379. << TheCall->getDirectCallee() << "block";
  380. return true;
  381. }
  382. return checkOpenCLBlockArgs(S, BlockArg);
  383. }
  384. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  385. /// get_kernel_work_group_size
  386. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  387. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  388. if (checkArgCount(S, TheCall, 1))
  389. return true;
  390. Expr *BlockArg = TheCall->getArg(0);
  391. if (!isBlockPointer(BlockArg)) {
  392. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  393. << TheCall->getDirectCallee() << "block";
  394. return true;
  395. }
  396. return checkOpenCLBlockArgs(S, BlockArg);
  397. }
  398. /// Diagnose integer type and any valid implicit conversion to it.
  399. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  400. const QualType &IntType);
  401. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  402. unsigned Start, unsigned End) {
  403. bool IllegalParams = false;
  404. for (unsigned I = Start; I <= End; ++I)
  405. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  406. S.Context.getSizeType());
  407. return IllegalParams;
  408. }
  409. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  410. /// 'local void*' parameter of passed block.
  411. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  412. Expr *BlockArg,
  413. unsigned NumNonVarArgs) {
  414. const BlockPointerType *BPT =
  415. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  416. unsigned NumBlockParams =
  417. BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
  418. unsigned TotalNumArgs = TheCall->getNumArgs();
  419. // For each argument passed to the block, a corresponding uint needs to
  420. // be passed to describe the size of the local memory.
  421. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  422. S.Diag(TheCall->getBeginLoc(),
  423. diag::err_opencl_enqueue_kernel_local_size_args);
  424. return true;
  425. }
  426. // Check that the sizes of the local memory are specified by integers.
  427. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  428. TotalNumArgs - 1);
  429. }
  430. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  431. /// overload formats specified in Table 6.13.17.1.
  432. /// int enqueue_kernel(queue_t queue,
  433. /// kernel_enqueue_flags_t flags,
  434. /// const ndrange_t ndrange,
  435. /// void (^block)(void))
  436. /// int enqueue_kernel(queue_t queue,
  437. /// kernel_enqueue_flags_t flags,
  438. /// const ndrange_t ndrange,
  439. /// uint num_events_in_wait_list,
  440. /// clk_event_t *event_wait_list,
  441. /// clk_event_t *event_ret,
  442. /// void (^block)(void))
  443. /// int enqueue_kernel(queue_t queue,
  444. /// kernel_enqueue_flags_t flags,
  445. /// const ndrange_t ndrange,
  446. /// void (^block)(local void*, ...),
  447. /// uint size0, ...)
  448. /// int enqueue_kernel(queue_t queue,
  449. /// kernel_enqueue_flags_t flags,
  450. /// const ndrange_t ndrange,
  451. /// uint num_events_in_wait_list,
  452. /// clk_event_t *event_wait_list,
  453. /// clk_event_t *event_ret,
  454. /// void (^block)(local void*, ...),
  455. /// uint size0, ...)
  456. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  457. unsigned NumArgs = TheCall->getNumArgs();
  458. if (NumArgs < 4) {
  459. S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
  460. return true;
  461. }
  462. Expr *Arg0 = TheCall->getArg(0);
  463. Expr *Arg1 = TheCall->getArg(1);
  464. Expr *Arg2 = TheCall->getArg(2);
  465. Expr *Arg3 = TheCall->getArg(3);
  466. // First argument always needs to be a queue_t type.
  467. if (!Arg0->getType()->isQueueT()) {
  468. S.Diag(TheCall->getArg(0)->getBeginLoc(),
  469. diag::err_opencl_builtin_expected_type)
  470. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  471. return true;
  472. }
  473. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  474. if (!Arg1->getType()->isIntegerType()) {
  475. S.Diag(TheCall->getArg(1)->getBeginLoc(),
  476. diag::err_opencl_builtin_expected_type)
  477. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  478. return true;
  479. }
  480. // Third argument is always an ndrange_t type.
  481. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  482. S.Diag(TheCall->getArg(2)->getBeginLoc(),
  483. diag::err_opencl_builtin_expected_type)
  484. << TheCall->getDirectCallee() << "'ndrange_t'";
  485. return true;
  486. }
  487. // With four arguments, there is only one form that the function could be
  488. // called in: no events and no variable arguments.
  489. if (NumArgs == 4) {
  490. // check that the last argument is the right block type.
  491. if (!isBlockPointer(Arg3)) {
  492. S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  493. << TheCall->getDirectCallee() << "block";
  494. return true;
  495. }
  496. // we have a block type, check the prototype
  497. const BlockPointerType *BPT =
  498. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  499. if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
  500. S.Diag(Arg3->getBeginLoc(),
  501. diag::err_opencl_enqueue_kernel_blocks_no_args);
  502. return true;
  503. }
  504. return false;
  505. }
  506. // we can have block + varargs.
  507. if (isBlockPointer(Arg3))
  508. return (checkOpenCLBlockArgs(S, Arg3) ||
  509. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  510. // last two cases with either exactly 7 args or 7 args and varargs.
  511. if (NumArgs >= 7) {
  512. // check common block argument.
  513. Expr *Arg6 = TheCall->getArg(6);
  514. if (!isBlockPointer(Arg6)) {
  515. S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  516. << TheCall->getDirectCallee() << "block";
  517. return true;
  518. }
  519. if (checkOpenCLBlockArgs(S, Arg6))
  520. return true;
  521. // Forth argument has to be any integer type.
  522. if (!Arg3->getType()->isIntegerType()) {
  523. S.Diag(TheCall->getArg(3)->getBeginLoc(),
  524. diag::err_opencl_builtin_expected_type)
  525. << TheCall->getDirectCallee() << "integer";
  526. return true;
  527. }
  528. // check remaining common arguments.
  529. Expr *Arg4 = TheCall->getArg(4);
  530. Expr *Arg5 = TheCall->getArg(5);
  531. // Fifth argument is always passed as a pointer to clk_event_t.
  532. if (!Arg4->isNullPointerConstant(S.Context,
  533. Expr::NPC_ValueDependentIsNotNull) &&
  534. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  535. S.Diag(TheCall->getArg(4)->getBeginLoc(),
  536. diag::err_opencl_builtin_expected_type)
  537. << TheCall->getDirectCallee()
  538. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  539. return true;
  540. }
  541. // Sixth argument is always passed as a pointer to clk_event_t.
  542. if (!Arg5->isNullPointerConstant(S.Context,
  543. Expr::NPC_ValueDependentIsNotNull) &&
  544. !(Arg5->getType()->isPointerType() &&
  545. Arg5->getType()->getPointeeType()->isClkEventT())) {
  546. S.Diag(TheCall->getArg(5)->getBeginLoc(),
  547. diag::err_opencl_builtin_expected_type)
  548. << TheCall->getDirectCallee()
  549. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  550. return true;
  551. }
  552. if (NumArgs == 7)
  553. return false;
  554. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  555. }
  556. // None of the specific case has been detected, give generic error
  557. S.Diag(TheCall->getBeginLoc(),
  558. diag::err_opencl_enqueue_kernel_incorrect_args);
  559. return true;
  560. }
  561. /// Returns OpenCL access qual.
  562. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  563. return D->getAttr<OpenCLAccessAttr>();
  564. }
  565. /// Returns true if pipe element type is different from the pointer.
  566. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  567. const Expr *Arg0 = Call->getArg(0);
  568. // First argument type should always be pipe.
  569. if (!Arg0->getType()->isPipeType()) {
  570. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  571. << Call->getDirectCallee() << Arg0->getSourceRange();
  572. return true;
  573. }
  574. OpenCLAccessAttr *AccessQual =
  575. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  576. // Validates the access qualifier is compatible with the call.
  577. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  578. // read_only and write_only, and assumed to be read_only if no qualifier is
  579. // specified.
  580. switch (Call->getDirectCallee()->getBuiltinID()) {
  581. case Builtin::BIread_pipe:
  582. case Builtin::BIreserve_read_pipe:
  583. case Builtin::BIcommit_read_pipe:
  584. case Builtin::BIwork_group_reserve_read_pipe:
  585. case Builtin::BIsub_group_reserve_read_pipe:
  586. case Builtin::BIwork_group_commit_read_pipe:
  587. case Builtin::BIsub_group_commit_read_pipe:
  588. if (!(!AccessQual || AccessQual->isReadOnly())) {
  589. S.Diag(Arg0->getBeginLoc(),
  590. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  591. << "read_only" << Arg0->getSourceRange();
  592. return true;
  593. }
  594. break;
  595. case Builtin::BIwrite_pipe:
  596. case Builtin::BIreserve_write_pipe:
  597. case Builtin::BIcommit_write_pipe:
  598. case Builtin::BIwork_group_reserve_write_pipe:
  599. case Builtin::BIsub_group_reserve_write_pipe:
  600. case Builtin::BIwork_group_commit_write_pipe:
  601. case Builtin::BIsub_group_commit_write_pipe:
  602. if (!(AccessQual && AccessQual->isWriteOnly())) {
  603. S.Diag(Arg0->getBeginLoc(),
  604. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  605. << "write_only" << Arg0->getSourceRange();
  606. return true;
  607. }
  608. break;
  609. default:
  610. break;
  611. }
  612. return false;
  613. }
  614. /// Returns true if pipe element type is different from the pointer.
  615. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  616. const Expr *Arg0 = Call->getArg(0);
  617. const Expr *ArgIdx = Call->getArg(Idx);
  618. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  619. const QualType EltTy = PipeTy->getElementType();
  620. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  621. // The Idx argument should be a pointer and the type of the pointer and
  622. // the type of pipe element should also be the same.
  623. if (!ArgTy ||
  624. !S.Context.hasSameType(
  625. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  626. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  627. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  628. << ArgIdx->getType() << ArgIdx->getSourceRange();
  629. return true;
  630. }
  631. return false;
  632. }
  633. // Performs semantic analysis for the read/write_pipe call.
  634. // \param S Reference to the semantic analyzer.
  635. // \param Call A pointer to the builtin call.
  636. // \return True if a semantic error has been found, false otherwise.
  637. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  638. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  639. // functions have two forms.
  640. switch (Call->getNumArgs()) {
  641. case 2:
  642. if (checkOpenCLPipeArg(S, Call))
  643. return true;
  644. // The call with 2 arguments should be
  645. // read/write_pipe(pipe T, T*).
  646. // Check packet type T.
  647. if (checkOpenCLPipePacketType(S, Call, 1))
  648. return true;
  649. break;
  650. case 4: {
  651. if (checkOpenCLPipeArg(S, Call))
  652. return true;
  653. // The call with 4 arguments should be
  654. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  655. // Check reserve_id_t.
  656. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  657. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  658. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  659. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  660. return true;
  661. }
  662. // Check the index.
  663. const Expr *Arg2 = Call->getArg(2);
  664. if (!Arg2->getType()->isIntegerType() &&
  665. !Arg2->getType()->isUnsignedIntegerType()) {
  666. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  667. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  668. << Arg2->getType() << Arg2->getSourceRange();
  669. return true;
  670. }
  671. // Check packet type T.
  672. if (checkOpenCLPipePacketType(S, Call, 3))
  673. return true;
  674. } break;
  675. default:
  676. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
  677. << Call->getDirectCallee() << Call->getSourceRange();
  678. return true;
  679. }
  680. return false;
  681. }
  682. // Performs a semantic analysis on the {work_group_/sub_group_
  683. // /_}reserve_{read/write}_pipe
  684. // \param S Reference to the semantic analyzer.
  685. // \param Call The call to the builtin function to be analyzed.
  686. // \return True if a semantic error was found, false otherwise.
  687. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  688. if (checkArgCount(S, Call, 2))
  689. return true;
  690. if (checkOpenCLPipeArg(S, Call))
  691. return true;
  692. // Check the reserve size.
  693. if (!Call->getArg(1)->getType()->isIntegerType() &&
  694. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  695. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  696. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  697. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  698. return true;
  699. }
  700. // Since return type of reserve_read/write_pipe built-in function is
  701. // reserve_id_t, which is not defined in the builtin def file , we used int
  702. // as return type and need to override the return type of these functions.
  703. Call->setType(S.Context.OCLReserveIDTy);
  704. return false;
  705. }
  706. // Performs a semantic analysis on {work_group_/sub_group_
  707. // /_}commit_{read/write}_pipe
  708. // \param S Reference to the semantic analyzer.
  709. // \param Call The call to the builtin function to be analyzed.
  710. // \return True if a semantic error was found, false otherwise.
  711. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  712. if (checkArgCount(S, Call, 2))
  713. return true;
  714. if (checkOpenCLPipeArg(S, Call))
  715. return true;
  716. // Check reserve_id_t.
  717. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  718. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  719. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  720. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  721. return true;
  722. }
  723. return false;
  724. }
  725. // Performs a semantic analysis on the call to built-in Pipe
  726. // Query Functions.
  727. // \param S Reference to the semantic analyzer.
  728. // \param Call The call to the builtin function to be analyzed.
  729. // \return True if a semantic error was found, false otherwise.
  730. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  731. if (checkArgCount(S, Call, 1))
  732. return true;
  733. if (!Call->getArg(0)->getType()->isPipeType()) {
  734. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  735. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  736. return true;
  737. }
  738. return false;
  739. }
  740. // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  741. // Performs semantic analysis for the to_global/local/private call.
  742. // \param S Reference to the semantic analyzer.
  743. // \param BuiltinID ID of the builtin function.
  744. // \param Call A pointer to the builtin call.
  745. // \return True if a semantic error has been found, false otherwise.
  746. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  747. CallExpr *Call) {
  748. if (Call->getNumArgs() != 1) {
  749. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
  750. << Call->getDirectCallee() << Call->getSourceRange();
  751. return true;
  752. }
  753. auto RT = Call->getArg(0)->getType();
  754. if (!RT->isPointerType() || RT->getPointeeType()
  755. .getAddressSpace() == LangAS::opencl_constant) {
  756. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
  757. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  758. return true;
  759. }
  760. if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
  761. S.Diag(Call->getArg(0)->getBeginLoc(),
  762. diag::warn_opencl_generic_address_space_arg)
  763. << Call->getDirectCallee()->getNameInfo().getAsString()
  764. << Call->getArg(0)->getSourceRange();
  765. }
  766. RT = RT->getPointeeType();
  767. auto Qual = RT.getQualifiers();
  768. switch (BuiltinID) {
  769. case Builtin::BIto_global:
  770. Qual.setAddressSpace(LangAS::opencl_global);
  771. break;
  772. case Builtin::BIto_local:
  773. Qual.setAddressSpace(LangAS::opencl_local);
  774. break;
  775. case Builtin::BIto_private:
  776. Qual.setAddressSpace(LangAS::opencl_private);
  777. break;
  778. default:
  779. llvm_unreachable("Invalid builtin function");
  780. }
  781. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  782. RT.getUnqualifiedType(), Qual)));
  783. return false;
  784. }
  785. // Emit an error and return true if the current architecture is not in the list
  786. // of supported architectures.
  787. static bool
  788. CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
  789. ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
  790. llvm::Triple::ArchType CurArch =
  791. S.getASTContext().getTargetInfo().getTriple().getArch();
  792. if (llvm::is_contained(SupportedArchs, CurArch))
  793. return false;
  794. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  795. << TheCall->getSourceRange();
  796. return true;
  797. }
  798. ExprResult
  799. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  800. CallExpr *TheCall) {
  801. ExprResult TheCallResult(TheCall);
  802. // Find out if any arguments are required to be integer constant expressions.
  803. unsigned ICEArguments = 0;
  804. ASTContext::GetBuiltinTypeError Error;
  805. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  806. if (Error != ASTContext::GE_None)
  807. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  808. // If any arguments are required to be ICE's, check and diagnose.
  809. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  810. // Skip arguments not required to be ICE's.
  811. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  812. llvm::APSInt Result;
  813. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  814. return true;
  815. ICEArguments &= ~(1 << ArgNo);
  816. }
  817. switch (BuiltinID) {
  818. case Builtin::BI__builtin___CFStringMakeConstantString:
  819. assert(TheCall->getNumArgs() == 1 &&
  820. "Wrong # arguments to builtin CFStringMakeConstantString");
  821. if (CheckObjCString(TheCall->getArg(0)))
  822. return ExprError();
  823. break;
  824. case Builtin::BI__builtin_ms_va_start:
  825. case Builtin::BI__builtin_stdarg_start:
  826. case Builtin::BI__builtin_va_start:
  827. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  828. return ExprError();
  829. break;
  830. case Builtin::BI__va_start: {
  831. switch (Context.getTargetInfo().getTriple().getArch()) {
  832. case llvm::Triple::aarch64:
  833. case llvm::Triple::arm:
  834. case llvm::Triple::thumb:
  835. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  836. return ExprError();
  837. break;
  838. default:
  839. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  840. return ExprError();
  841. break;
  842. }
  843. break;
  844. }
  845. // The acquire, release, and no fence variants are ARM and AArch64 only.
  846. case Builtin::BI_interlockedbittestandset_acq:
  847. case Builtin::BI_interlockedbittestandset_rel:
  848. case Builtin::BI_interlockedbittestandset_nf:
  849. case Builtin::BI_interlockedbittestandreset_acq:
  850. case Builtin::BI_interlockedbittestandreset_rel:
  851. case Builtin::BI_interlockedbittestandreset_nf:
  852. if (CheckBuiltinTargetSupport(
  853. *this, BuiltinID, TheCall,
  854. {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
  855. return ExprError();
  856. break;
  857. // The 64-bit bittest variants are x64, ARM, and AArch64 only.
  858. case Builtin::BI_bittest64:
  859. case Builtin::BI_bittestandcomplement64:
  860. case Builtin::BI_bittestandreset64:
  861. case Builtin::BI_bittestandset64:
  862. case Builtin::BI_interlockedbittestandreset64:
  863. case Builtin::BI_interlockedbittestandset64:
  864. if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
  865. {llvm::Triple::x86_64, llvm::Triple::arm,
  866. llvm::Triple::thumb, llvm::Triple::aarch64}))
  867. return ExprError();
  868. break;
  869. case Builtin::BI__builtin_isgreater:
  870. case Builtin::BI__builtin_isgreaterequal:
  871. case Builtin::BI__builtin_isless:
  872. case Builtin::BI__builtin_islessequal:
  873. case Builtin::BI__builtin_islessgreater:
  874. case Builtin::BI__builtin_isunordered:
  875. if (SemaBuiltinUnorderedCompare(TheCall))
  876. return ExprError();
  877. break;
  878. case Builtin::BI__builtin_fpclassify:
  879. if (SemaBuiltinFPClassification(TheCall, 6))
  880. return ExprError();
  881. break;
  882. case Builtin::BI__builtin_isfinite:
  883. case Builtin::BI__builtin_isinf:
  884. case Builtin::BI__builtin_isinf_sign:
  885. case Builtin::BI__builtin_isnan:
  886. case Builtin::BI__builtin_isnormal:
  887. case Builtin::BI__builtin_signbit:
  888. case Builtin::BI__builtin_signbitf:
  889. case Builtin::BI__builtin_signbitl:
  890. if (SemaBuiltinFPClassification(TheCall, 1))
  891. return ExprError();
  892. break;
  893. case Builtin::BI__builtin_shufflevector:
  894. return SemaBuiltinShuffleVector(TheCall);
  895. // TheCall will be freed by the smart pointer here, but that's fine, since
  896. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  897. case Builtin::BI__builtin_prefetch:
  898. if (SemaBuiltinPrefetch(TheCall))
  899. return ExprError();
  900. break;
  901. case Builtin::BI__builtin_alloca_with_align:
  902. if (SemaBuiltinAllocaWithAlign(TheCall))
  903. return ExprError();
  904. break;
  905. case Builtin::BI__assume:
  906. case Builtin::BI__builtin_assume:
  907. if (SemaBuiltinAssume(TheCall))
  908. return ExprError();
  909. break;
  910. case Builtin::BI__builtin_assume_aligned:
  911. if (SemaBuiltinAssumeAligned(TheCall))
  912. return ExprError();
  913. break;
  914. case Builtin::BI__builtin_object_size:
  915. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  916. return ExprError();
  917. break;
  918. case Builtin::BI__builtin_longjmp:
  919. if (SemaBuiltinLongjmp(TheCall))
  920. return ExprError();
  921. break;
  922. case Builtin::BI__builtin_setjmp:
  923. if (SemaBuiltinSetjmp(TheCall))
  924. return ExprError();
  925. break;
  926. case Builtin::BI_setjmp:
  927. case Builtin::BI_setjmpex:
  928. if (checkArgCount(*this, TheCall, 1))
  929. return true;
  930. break;
  931. case Builtin::BI__builtin_classify_type:
  932. if (checkArgCount(*this, TheCall, 1)) return true;
  933. TheCall->setType(Context.IntTy);
  934. break;
  935. case Builtin::BI__builtin_constant_p:
  936. if (checkArgCount(*this, TheCall, 1)) return true;
  937. TheCall->setType(Context.IntTy);
  938. break;
  939. case Builtin::BI__sync_fetch_and_add:
  940. case Builtin::BI__sync_fetch_and_add_1:
  941. case Builtin::BI__sync_fetch_and_add_2:
  942. case Builtin::BI__sync_fetch_and_add_4:
  943. case Builtin::BI__sync_fetch_and_add_8:
  944. case Builtin::BI__sync_fetch_and_add_16:
  945. case Builtin::BI__sync_fetch_and_sub:
  946. case Builtin::BI__sync_fetch_and_sub_1:
  947. case Builtin::BI__sync_fetch_and_sub_2:
  948. case Builtin::BI__sync_fetch_and_sub_4:
  949. case Builtin::BI__sync_fetch_and_sub_8:
  950. case Builtin::BI__sync_fetch_and_sub_16:
  951. case Builtin::BI__sync_fetch_and_or:
  952. case Builtin::BI__sync_fetch_and_or_1:
  953. case Builtin::BI__sync_fetch_and_or_2:
  954. case Builtin::BI__sync_fetch_and_or_4:
  955. case Builtin::BI__sync_fetch_and_or_8:
  956. case Builtin::BI__sync_fetch_and_or_16:
  957. case Builtin::BI__sync_fetch_and_and:
  958. case Builtin::BI__sync_fetch_and_and_1:
  959. case Builtin::BI__sync_fetch_and_and_2:
  960. case Builtin::BI__sync_fetch_and_and_4:
  961. case Builtin::BI__sync_fetch_and_and_8:
  962. case Builtin::BI__sync_fetch_and_and_16:
  963. case Builtin::BI__sync_fetch_and_xor:
  964. case Builtin::BI__sync_fetch_and_xor_1:
  965. case Builtin::BI__sync_fetch_and_xor_2:
  966. case Builtin::BI__sync_fetch_and_xor_4:
  967. case Builtin::BI__sync_fetch_and_xor_8:
  968. case Builtin::BI__sync_fetch_and_xor_16:
  969. case Builtin::BI__sync_fetch_and_nand:
  970. case Builtin::BI__sync_fetch_and_nand_1:
  971. case Builtin::BI__sync_fetch_and_nand_2:
  972. case Builtin::BI__sync_fetch_and_nand_4:
  973. case Builtin::BI__sync_fetch_and_nand_8:
  974. case Builtin::BI__sync_fetch_and_nand_16:
  975. case Builtin::BI__sync_add_and_fetch:
  976. case Builtin::BI__sync_add_and_fetch_1:
  977. case Builtin::BI__sync_add_and_fetch_2:
  978. case Builtin::BI__sync_add_and_fetch_4:
  979. case Builtin::BI__sync_add_and_fetch_8:
  980. case Builtin::BI__sync_add_and_fetch_16:
  981. case Builtin::BI__sync_sub_and_fetch:
  982. case Builtin::BI__sync_sub_and_fetch_1:
  983. case Builtin::BI__sync_sub_and_fetch_2:
  984. case Builtin::BI__sync_sub_and_fetch_4:
  985. case Builtin::BI__sync_sub_and_fetch_8:
  986. case Builtin::BI__sync_sub_and_fetch_16:
  987. case Builtin::BI__sync_and_and_fetch:
  988. case Builtin::BI__sync_and_and_fetch_1:
  989. case Builtin::BI__sync_and_and_fetch_2:
  990. case Builtin::BI__sync_and_and_fetch_4:
  991. case Builtin::BI__sync_and_and_fetch_8:
  992. case Builtin::BI__sync_and_and_fetch_16:
  993. case Builtin::BI__sync_or_and_fetch:
  994. case Builtin::BI__sync_or_and_fetch_1:
  995. case Builtin::BI__sync_or_and_fetch_2:
  996. case Builtin::BI__sync_or_and_fetch_4:
  997. case Builtin::BI__sync_or_and_fetch_8:
  998. case Builtin::BI__sync_or_and_fetch_16:
  999. case Builtin::BI__sync_xor_and_fetch:
  1000. case Builtin::BI__sync_xor_and_fetch_1:
  1001. case Builtin::BI__sync_xor_and_fetch_2:
  1002. case Builtin::BI__sync_xor_and_fetch_4:
  1003. case Builtin::BI__sync_xor_and_fetch_8:
  1004. case Builtin::BI__sync_xor_and_fetch_16:
  1005. case Builtin::BI__sync_nand_and_fetch:
  1006. case Builtin::BI__sync_nand_and_fetch_1:
  1007. case Builtin::BI__sync_nand_and_fetch_2:
  1008. case Builtin::BI__sync_nand_and_fetch_4:
  1009. case Builtin::BI__sync_nand_and_fetch_8:
  1010. case Builtin::BI__sync_nand_and_fetch_16:
  1011. case Builtin::BI__sync_val_compare_and_swap:
  1012. case Builtin::BI__sync_val_compare_and_swap_1:
  1013. case Builtin::BI__sync_val_compare_and_swap_2:
  1014. case Builtin::BI__sync_val_compare_and_swap_4:
  1015. case Builtin::BI__sync_val_compare_and_swap_8:
  1016. case Builtin::BI__sync_val_compare_and_swap_16:
  1017. case Builtin::BI__sync_bool_compare_and_swap:
  1018. case Builtin::BI__sync_bool_compare_and_swap_1:
  1019. case Builtin::BI__sync_bool_compare_and_swap_2:
  1020. case Builtin::BI__sync_bool_compare_and_swap_4:
  1021. case Builtin::BI__sync_bool_compare_and_swap_8:
  1022. case Builtin::BI__sync_bool_compare_and_swap_16:
  1023. case Builtin::BI__sync_lock_test_and_set:
  1024. case Builtin::BI__sync_lock_test_and_set_1:
  1025. case Builtin::BI__sync_lock_test_and_set_2:
  1026. case Builtin::BI__sync_lock_test_and_set_4:
  1027. case Builtin::BI__sync_lock_test_and_set_8:
  1028. case Builtin::BI__sync_lock_test_and_set_16:
  1029. case Builtin::BI__sync_lock_release:
  1030. case Builtin::BI__sync_lock_release_1:
  1031. case Builtin::BI__sync_lock_release_2:
  1032. case Builtin::BI__sync_lock_release_4:
  1033. case Builtin::BI__sync_lock_release_8:
  1034. case Builtin::BI__sync_lock_release_16:
  1035. case Builtin::BI__sync_swap:
  1036. case Builtin::BI__sync_swap_1:
  1037. case Builtin::BI__sync_swap_2:
  1038. case Builtin::BI__sync_swap_4:
  1039. case Builtin::BI__sync_swap_8:
  1040. case Builtin::BI__sync_swap_16:
  1041. return SemaBuiltinAtomicOverloaded(TheCallResult);
  1042. case Builtin::BI__sync_synchronize:
  1043. Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
  1044. << TheCall->getCallee()->getSourceRange();
  1045. break;
  1046. case Builtin::BI__builtin_nontemporal_load:
  1047. case Builtin::BI__builtin_nontemporal_store:
  1048. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  1049. #define BUILTIN(ID, TYPE, ATTRS)
  1050. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  1051. case Builtin::BI##ID: \
  1052. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  1053. #include "clang/Basic/Builtins.def"
  1054. case Builtin::BI__annotation:
  1055. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  1056. return ExprError();
  1057. break;
  1058. case Builtin::BI__builtin_annotation:
  1059. if (SemaBuiltinAnnotation(*this, TheCall))
  1060. return ExprError();
  1061. break;
  1062. case Builtin::BI__builtin_addressof:
  1063. if (SemaBuiltinAddressof(*this, TheCall))
  1064. return ExprError();
  1065. break;
  1066. case Builtin::BI__builtin_add_overflow:
  1067. case Builtin::BI__builtin_sub_overflow:
  1068. case Builtin::BI__builtin_mul_overflow:
  1069. if (SemaBuiltinOverflow(*this, TheCall))
  1070. return ExprError();
  1071. break;
  1072. case Builtin::BI__builtin_operator_new:
  1073. case Builtin::BI__builtin_operator_delete: {
  1074. bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
  1075. ExprResult Res =
  1076. SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
  1077. if (Res.isInvalid())
  1078. CorrectDelayedTyposInExpr(TheCallResult.get());
  1079. return Res;
  1080. }
  1081. case Builtin::BI__builtin_dump_struct: {
  1082. // We first want to ensure we are called with 2 arguments
  1083. if (checkArgCount(*this, TheCall, 2))
  1084. return ExprError();
  1085. // Ensure that the first argument is of type 'struct XX *'
  1086. const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
  1087. const QualType PtrArgType = PtrArg->getType();
  1088. if (!PtrArgType->isPointerType() ||
  1089. !PtrArgType->getPointeeType()->isRecordType()) {
  1090. Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1091. << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
  1092. << "structure pointer";
  1093. return ExprError();
  1094. }
  1095. // Ensure that the second argument is of type 'FunctionType'
  1096. const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
  1097. const QualType FnPtrArgType = FnPtrArg->getType();
  1098. if (!FnPtrArgType->isPointerType()) {
  1099. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1100. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1101. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1102. return ExprError();
  1103. }
  1104. const auto *FuncType =
  1105. FnPtrArgType->getPointeeType()->getAs<FunctionType>();
  1106. if (!FuncType) {
  1107. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1108. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1109. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1110. return ExprError();
  1111. }
  1112. if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
  1113. if (!FT->getNumParams()) {
  1114. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1115. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1116. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1117. return ExprError();
  1118. }
  1119. QualType PT = FT->getParamType(0);
  1120. if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
  1121. !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
  1122. !PT->getPointeeType().isConstQualified()) {
  1123. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1124. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1125. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1126. return ExprError();
  1127. }
  1128. }
  1129. TheCall->setType(Context.IntTy);
  1130. break;
  1131. }
  1132. // check secure string manipulation functions where overflows
  1133. // are detectable at compile time
  1134. case Builtin::BI__builtin___memcpy_chk:
  1135. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy");
  1136. break;
  1137. case Builtin::BI__builtin___memmove_chk:
  1138. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove");
  1139. break;
  1140. case Builtin::BI__builtin___memset_chk:
  1141. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset");
  1142. break;
  1143. case Builtin::BI__builtin___strlcat_chk:
  1144. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat");
  1145. break;
  1146. case Builtin::BI__builtin___strlcpy_chk:
  1147. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy");
  1148. break;
  1149. case Builtin::BI__builtin___strncat_chk:
  1150. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat");
  1151. break;
  1152. case Builtin::BI__builtin___strncpy_chk:
  1153. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy");
  1154. break;
  1155. case Builtin::BI__builtin___stpncpy_chk:
  1156. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy");
  1157. break;
  1158. case Builtin::BI__builtin___memccpy_chk:
  1159. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy");
  1160. break;
  1161. case Builtin::BI__builtin___snprintf_chk:
  1162. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf");
  1163. break;
  1164. case Builtin::BI__builtin___vsnprintf_chk:
  1165. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf");
  1166. break;
  1167. case Builtin::BI__builtin_call_with_static_chain:
  1168. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  1169. return ExprError();
  1170. break;
  1171. case Builtin::BI__exception_code:
  1172. case Builtin::BI_exception_code:
  1173. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  1174. diag::err_seh___except_block))
  1175. return ExprError();
  1176. break;
  1177. case Builtin::BI__exception_info:
  1178. case Builtin::BI_exception_info:
  1179. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  1180. diag::err_seh___except_filter))
  1181. return ExprError();
  1182. break;
  1183. case Builtin::BI__GetExceptionInfo:
  1184. if (checkArgCount(*this, TheCall, 1))
  1185. return ExprError();
  1186. if (CheckCXXThrowOperand(
  1187. TheCall->getBeginLoc(),
  1188. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1189. TheCall))
  1190. return ExprError();
  1191. TheCall->setType(Context.VoidPtrTy);
  1192. break;
  1193. // OpenCL v2.0, s6.13.16 - Pipe functions
  1194. case Builtin::BIread_pipe:
  1195. case Builtin::BIwrite_pipe:
  1196. // Since those two functions are declared with var args, we need a semantic
  1197. // check for the argument.
  1198. if (SemaBuiltinRWPipe(*this, TheCall))
  1199. return ExprError();
  1200. break;
  1201. case Builtin::BIreserve_read_pipe:
  1202. case Builtin::BIreserve_write_pipe:
  1203. case Builtin::BIwork_group_reserve_read_pipe:
  1204. case Builtin::BIwork_group_reserve_write_pipe:
  1205. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1206. return ExprError();
  1207. break;
  1208. case Builtin::BIsub_group_reserve_read_pipe:
  1209. case Builtin::BIsub_group_reserve_write_pipe:
  1210. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1211. SemaBuiltinReserveRWPipe(*this, TheCall))
  1212. return ExprError();
  1213. break;
  1214. case Builtin::BIcommit_read_pipe:
  1215. case Builtin::BIcommit_write_pipe:
  1216. case Builtin::BIwork_group_commit_read_pipe:
  1217. case Builtin::BIwork_group_commit_write_pipe:
  1218. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1219. return ExprError();
  1220. break;
  1221. case Builtin::BIsub_group_commit_read_pipe:
  1222. case Builtin::BIsub_group_commit_write_pipe:
  1223. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1224. SemaBuiltinCommitRWPipe(*this, TheCall))
  1225. return ExprError();
  1226. break;
  1227. case Builtin::BIget_pipe_num_packets:
  1228. case Builtin::BIget_pipe_max_packets:
  1229. if (SemaBuiltinPipePackets(*this, TheCall))
  1230. return ExprError();
  1231. break;
  1232. case Builtin::BIto_global:
  1233. case Builtin::BIto_local:
  1234. case Builtin::BIto_private:
  1235. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1236. return ExprError();
  1237. break;
  1238. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1239. case Builtin::BIenqueue_kernel:
  1240. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1241. return ExprError();
  1242. break;
  1243. case Builtin::BIget_kernel_work_group_size:
  1244. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1245. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1246. return ExprError();
  1247. break;
  1248. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1249. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1250. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1251. return ExprError();
  1252. break;
  1253. case Builtin::BI__builtin_os_log_format:
  1254. case Builtin::BI__builtin_os_log_format_buffer_size:
  1255. if (SemaBuiltinOSLogFormat(TheCall))
  1256. return ExprError();
  1257. break;
  1258. }
  1259. // Since the target specific builtins for each arch overlap, only check those
  1260. // of the arch we are compiling for.
  1261. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  1262. switch (Context.getTargetInfo().getTriple().getArch()) {
  1263. case llvm::Triple::arm:
  1264. case llvm::Triple::armeb:
  1265. case llvm::Triple::thumb:
  1266. case llvm::Triple::thumbeb:
  1267. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  1268. return ExprError();
  1269. break;
  1270. case llvm::Triple::aarch64:
  1271. case llvm::Triple::aarch64_be:
  1272. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  1273. return ExprError();
  1274. break;
  1275. case llvm::Triple::hexagon:
  1276. if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
  1277. return ExprError();
  1278. break;
  1279. case llvm::Triple::mips:
  1280. case llvm::Triple::mipsel:
  1281. case llvm::Triple::mips64:
  1282. case llvm::Triple::mips64el:
  1283. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  1284. return ExprError();
  1285. break;
  1286. case llvm::Triple::systemz:
  1287. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  1288. return ExprError();
  1289. break;
  1290. case llvm::Triple::x86:
  1291. case llvm::Triple::x86_64:
  1292. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  1293. return ExprError();
  1294. break;
  1295. case llvm::Triple::ppc:
  1296. case llvm::Triple::ppc64:
  1297. case llvm::Triple::ppc64le:
  1298. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  1299. return ExprError();
  1300. break;
  1301. default:
  1302. break;
  1303. }
  1304. }
  1305. return TheCallResult;
  1306. }
  1307. // Get the valid immediate range for the specified NEON type code.
  1308. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  1309. NeonTypeFlags Type(t);
  1310. int IsQuad = ForceQuad ? true : Type.isQuad();
  1311. switch (Type.getEltType()) {
  1312. case NeonTypeFlags::Int8:
  1313. case NeonTypeFlags::Poly8:
  1314. return shift ? 7 : (8 << IsQuad) - 1;
  1315. case NeonTypeFlags::Int16:
  1316. case NeonTypeFlags::Poly16:
  1317. return shift ? 15 : (4 << IsQuad) - 1;
  1318. case NeonTypeFlags::Int32:
  1319. return shift ? 31 : (2 << IsQuad) - 1;
  1320. case NeonTypeFlags::Int64:
  1321. case NeonTypeFlags::Poly64:
  1322. return shift ? 63 : (1 << IsQuad) - 1;
  1323. case NeonTypeFlags::Poly128:
  1324. return shift ? 127 : (1 << IsQuad) - 1;
  1325. case NeonTypeFlags::Float16:
  1326. assert(!shift && "cannot shift float types!");
  1327. return (4 << IsQuad) - 1;
  1328. case NeonTypeFlags::Float32:
  1329. assert(!shift && "cannot shift float types!");
  1330. return (2 << IsQuad) - 1;
  1331. case NeonTypeFlags::Float64:
  1332. assert(!shift && "cannot shift float types!");
  1333. return (1 << IsQuad) - 1;
  1334. }
  1335. llvm_unreachable("Invalid NeonTypeFlag!");
  1336. }
  1337. /// getNeonEltType - Return the QualType corresponding to the elements of
  1338. /// the vector type specified by the NeonTypeFlags. This is used to check
  1339. /// the pointer arguments for Neon load/store intrinsics.
  1340. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  1341. bool IsPolyUnsigned, bool IsInt64Long) {
  1342. switch (Flags.getEltType()) {
  1343. case NeonTypeFlags::Int8:
  1344. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  1345. case NeonTypeFlags::Int16:
  1346. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  1347. case NeonTypeFlags::Int32:
  1348. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  1349. case NeonTypeFlags::Int64:
  1350. if (IsInt64Long)
  1351. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  1352. else
  1353. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  1354. : Context.LongLongTy;
  1355. case NeonTypeFlags::Poly8:
  1356. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  1357. case NeonTypeFlags::Poly16:
  1358. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  1359. case NeonTypeFlags::Poly64:
  1360. if (IsInt64Long)
  1361. return Context.UnsignedLongTy;
  1362. else
  1363. return Context.UnsignedLongLongTy;
  1364. case NeonTypeFlags::Poly128:
  1365. break;
  1366. case NeonTypeFlags::Float16:
  1367. return Context.HalfTy;
  1368. case NeonTypeFlags::Float32:
  1369. return Context.FloatTy;
  1370. case NeonTypeFlags::Float64:
  1371. return Context.DoubleTy;
  1372. }
  1373. llvm_unreachable("Invalid NeonTypeFlag!");
  1374. }
  1375. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1376. llvm::APSInt Result;
  1377. uint64_t mask = 0;
  1378. unsigned TV = 0;
  1379. int PtrArgNum = -1;
  1380. bool HasConstPtr = false;
  1381. switch (BuiltinID) {
  1382. #define GET_NEON_OVERLOAD_CHECK
  1383. #include "clang/Basic/arm_neon.inc"
  1384. #include "clang/Basic/arm_fp16.inc"
  1385. #undef GET_NEON_OVERLOAD_CHECK
  1386. }
  1387. // For NEON intrinsics which are overloaded on vector element type, validate
  1388. // the immediate which specifies which variant to emit.
  1389. unsigned ImmArg = TheCall->getNumArgs()-1;
  1390. if (mask) {
  1391. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  1392. return true;
  1393. TV = Result.getLimitedValue(64);
  1394. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  1395. return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
  1396. << TheCall->getArg(ImmArg)->getSourceRange();
  1397. }
  1398. if (PtrArgNum >= 0) {
  1399. // Check that pointer arguments have the specified type.
  1400. Expr *Arg = TheCall->getArg(PtrArgNum);
  1401. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  1402. Arg = ICE->getSubExpr();
  1403. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  1404. QualType RHSTy = RHS.get()->getType();
  1405. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  1406. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  1407. Arch == llvm::Triple::aarch64_be;
  1408. bool IsInt64Long =
  1409. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  1410. QualType EltTy =
  1411. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  1412. if (HasConstPtr)
  1413. EltTy = EltTy.withConst();
  1414. QualType LHSTy = Context.getPointerType(EltTy);
  1415. AssignConvertType ConvTy;
  1416. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  1417. if (RHS.isInvalid())
  1418. return true;
  1419. if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
  1420. RHS.get(), AA_Assigning))
  1421. return true;
  1422. }
  1423. // For NEON intrinsics which take an immediate value as part of the
  1424. // instruction, range check them here.
  1425. unsigned i = 0, l = 0, u = 0;
  1426. switch (BuiltinID) {
  1427. default:
  1428. return false;
  1429. #define GET_NEON_IMMEDIATE_CHECK
  1430. #include "clang/Basic/arm_neon.inc"
  1431. #include "clang/Basic/arm_fp16.inc"
  1432. #undef GET_NEON_IMMEDIATE_CHECK
  1433. }
  1434. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1435. }
  1436. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  1437. unsigned MaxWidth) {
  1438. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1439. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1440. BuiltinID == ARM::BI__builtin_arm_strex ||
  1441. BuiltinID == ARM::BI__builtin_arm_stlex ||
  1442. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1443. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1444. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1445. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  1446. "unexpected ARM builtin");
  1447. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1448. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1449. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1450. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  1451. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1452. // Ensure that we have the proper number of arguments.
  1453. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  1454. return true;
  1455. // Inspect the pointer argument of the atomic builtin. This should always be
  1456. // a pointer type, whose element is an integral scalar or pointer type.
  1457. // Because it is a pointer type, we don't have to worry about any implicit
  1458. // casts here.
  1459. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  1460. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  1461. if (PointerArgRes.isInvalid())
  1462. return true;
  1463. PointerArg = PointerArgRes.get();
  1464. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  1465. if (!pointerType) {
  1466. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  1467. << PointerArg->getType() << PointerArg->getSourceRange();
  1468. return true;
  1469. }
  1470. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  1471. // task is to insert the appropriate casts into the AST. First work out just
  1472. // what the appropriate type is.
  1473. QualType ValType = pointerType->getPointeeType();
  1474. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  1475. if (IsLdrex)
  1476. AddrType.addConst();
  1477. // Issue a warning if the cast is dodgy.
  1478. CastKind CastNeeded = CK_NoOp;
  1479. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  1480. CastNeeded = CK_BitCast;
  1481. Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
  1482. << PointerArg->getType() << Context.getPointerType(AddrType)
  1483. << AA_Passing << PointerArg->getSourceRange();
  1484. }
  1485. // Finally, do the cast and replace the argument with the corrected version.
  1486. AddrType = Context.getPointerType(AddrType);
  1487. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  1488. if (PointerArgRes.isInvalid())
  1489. return true;
  1490. PointerArg = PointerArgRes.get();
  1491. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  1492. // In general, we allow ints, floats and pointers to be loaded and stored.
  1493. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1494. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  1495. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  1496. << PointerArg->getType() << PointerArg->getSourceRange();
  1497. return true;
  1498. }
  1499. // But ARM doesn't have instructions to deal with 128-bit versions.
  1500. if (Context.getTypeSize(ValType) > MaxWidth) {
  1501. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  1502. Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
  1503. << PointerArg->getType() << PointerArg->getSourceRange();
  1504. return true;
  1505. }
  1506. switch (ValType.getObjCLifetime()) {
  1507. case Qualifiers::OCL_None:
  1508. case Qualifiers::OCL_ExplicitNone:
  1509. // okay
  1510. break;
  1511. case Qualifiers::OCL_Weak:
  1512. case Qualifiers::OCL_Strong:
  1513. case Qualifiers::OCL_Autoreleasing:
  1514. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  1515. << ValType << PointerArg->getSourceRange();
  1516. return true;
  1517. }
  1518. if (IsLdrex) {
  1519. TheCall->setType(ValType);
  1520. return false;
  1521. }
  1522. // Initialize the argument to be stored.
  1523. ExprResult ValArg = TheCall->getArg(0);
  1524. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  1525. Context, ValType, /*consume*/ false);
  1526. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  1527. if (ValArg.isInvalid())
  1528. return true;
  1529. TheCall->setArg(0, ValArg.get());
  1530. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  1531. // but the custom checker bypasses all default analysis.
  1532. TheCall->setType(Context.IntTy);
  1533. return false;
  1534. }
  1535. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1536. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1537. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1538. BuiltinID == ARM::BI__builtin_arm_strex ||
  1539. BuiltinID == ARM::BI__builtin_arm_stlex) {
  1540. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  1541. }
  1542. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  1543. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1544. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  1545. }
  1546. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  1547. BuiltinID == ARM::BI__builtin_arm_wsr64)
  1548. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  1549. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  1550. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  1551. BuiltinID == ARM::BI__builtin_arm_wsr ||
  1552. BuiltinID == ARM::BI__builtin_arm_wsrp)
  1553. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1554. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1555. return true;
  1556. // For intrinsics which take an immediate value as part of the instruction,
  1557. // range check them here.
  1558. // FIXME: VFP Intrinsics should error if VFP not present.
  1559. switch (BuiltinID) {
  1560. default: return false;
  1561. case ARM::BI__builtin_arm_ssat:
  1562. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  1563. case ARM::BI__builtin_arm_usat:
  1564. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  1565. case ARM::BI__builtin_arm_ssat16:
  1566. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  1567. case ARM::BI__builtin_arm_usat16:
  1568. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  1569. case ARM::BI__builtin_arm_vcvtr_f:
  1570. case ARM::BI__builtin_arm_vcvtr_d:
  1571. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  1572. case ARM::BI__builtin_arm_dmb:
  1573. case ARM::BI__builtin_arm_dsb:
  1574. case ARM::BI__builtin_arm_isb:
  1575. case ARM::BI__builtin_arm_dbg:
  1576. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  1577. }
  1578. }
  1579. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  1580. CallExpr *TheCall) {
  1581. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1582. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1583. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1584. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  1585. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  1586. }
  1587. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  1588. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1589. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  1590. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  1591. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  1592. }
  1593. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  1594. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  1595. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1596. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  1597. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  1598. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  1599. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  1600. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1601. // Only check the valid encoding range. Any constant in this range would be
  1602. // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
  1603. // an exception for incorrect registers. This matches MSVC behavior.
  1604. if (BuiltinID == AArch64::BI_ReadStatusReg ||
  1605. BuiltinID == AArch64::BI_WriteStatusReg)
  1606. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
  1607. if (BuiltinID == AArch64::BI__getReg)
  1608. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
  1609. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1610. return true;
  1611. // For intrinsics which take an immediate value as part of the instruction,
  1612. // range check them here.
  1613. unsigned i = 0, l = 0, u = 0;
  1614. switch (BuiltinID) {
  1615. default: return false;
  1616. case AArch64::BI__builtin_arm_dmb:
  1617. case AArch64::BI__builtin_arm_dsb:
  1618. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  1619. }
  1620. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1621. }
  1622. bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
  1623. struct BuiltinAndString {
  1624. unsigned BuiltinID;
  1625. const char *Str;
  1626. };
  1627. static BuiltinAndString ValidCPU[] = {
  1628. { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65" },
  1629. { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65" },
  1630. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65" },
  1631. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65" },
  1632. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65" },
  1633. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65" },
  1634. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65" },
  1635. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65" },
  1636. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65" },
  1637. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65" },
  1638. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65" },
  1639. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65" },
  1640. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65" },
  1641. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65" },
  1642. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65" },
  1643. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65" },
  1644. { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65" },
  1645. { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65" },
  1646. { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65" },
  1647. };
  1648. static BuiltinAndString ValidHVX[] = {
  1649. { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65" },
  1650. { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65" },
  1651. { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65" },
  1652. { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65" },
  1653. { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65" },
  1654. { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65" },
  1655. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65" },
  1656. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65" },
  1657. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65" },
  1658. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65" },
  1659. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65" },
  1660. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65" },
  1661. { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65" },
  1662. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65" },
  1663. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65" },
  1664. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65" },
  1665. { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65" },
  1666. { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65" },
  1667. { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65" },
  1668. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65" },
  1669. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65" },
  1670. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65" },
  1671. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65" },
  1672. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65" },
  1673. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65" },
  1674. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65" },
  1675. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65" },
  1676. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65" },
  1677. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65" },
  1678. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65" },
  1679. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65" },
  1680. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65" },
  1681. { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65" },
  1682. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65" },
  1683. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65" },
  1684. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65" },
  1685. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65" },
  1686. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65" },
  1687. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65" },
  1688. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65" },
  1689. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65" },
  1690. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65" },
  1691. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65" },
  1692. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65" },
  1693. { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65" },
  1694. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65" },
  1695. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65" },
  1696. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65" },
  1697. { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65" },
  1698. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65" },
  1699. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65" },
  1700. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65" },
  1701. { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65" },
  1702. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65" },
  1703. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65" },
  1704. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65" },
  1705. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65" },
  1706. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65" },
  1707. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65" },
  1708. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65" },
  1709. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65" },
  1710. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65" },
  1711. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65" },
  1712. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65" },
  1713. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65" },
  1714. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65" },
  1715. { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65" },
  1716. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65" },
  1717. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65" },
  1718. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65" },
  1719. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65" },
  1720. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65" },
  1721. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65" },
  1722. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65" },
  1723. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65" },
  1724. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65" },
  1725. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65" },
  1726. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65" },
  1727. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65" },
  1728. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65" },
  1729. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65" },
  1730. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65" },
  1731. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65" },
  1732. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65" },
  1733. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65" },
  1734. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65" },
  1735. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65" },
  1736. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65" },
  1737. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65" },
  1738. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65" },
  1739. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65" },
  1740. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65" },
  1741. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65" },
  1742. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65" },
  1743. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65" },
  1744. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65" },
  1745. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65" },
  1746. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65" },
  1747. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65" },
  1748. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65" },
  1749. { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65" },
  1750. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65" },
  1751. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65" },
  1752. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65" },
  1753. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65" },
  1754. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65" },
  1755. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65" },
  1756. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65" },
  1757. { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65" },
  1758. { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65" },
  1759. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65" },
  1760. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65" },
  1761. { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65" },
  1762. { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65" },
  1763. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65" },
  1764. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65" },
  1765. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65" },
  1766. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65" },
  1767. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65" },
  1768. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65" },
  1769. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65" },
  1770. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65" },
  1771. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65" },
  1772. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65" },
  1773. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65" },
  1774. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65" },
  1775. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65" },
  1776. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65" },
  1777. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65" },
  1778. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65" },
  1779. { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65" },
  1780. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65" },
  1781. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65" },
  1782. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65" },
  1783. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65" },
  1784. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65" },
  1785. { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65" },
  1786. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65" },
  1787. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65" },
  1788. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65" },
  1789. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65" },
  1790. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65" },
  1791. { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65" },
  1792. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65" },
  1793. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65" },
  1794. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65" },
  1795. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65" },
  1796. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65" },
  1797. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65" },
  1798. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65" },
  1799. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65" },
  1800. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65" },
  1801. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65" },
  1802. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65" },
  1803. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65" },
  1804. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65" },
  1805. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65" },
  1806. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65" },
  1807. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65" },
  1808. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65" },
  1809. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65" },
  1810. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65" },
  1811. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65" },
  1812. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65" },
  1813. { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65" },
  1814. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65" },
  1815. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65" },
  1816. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65" },
  1817. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65" },
  1818. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65" },
  1819. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65" },
  1820. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65" },
  1821. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65" },
  1822. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65" },
  1823. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65" },
  1824. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65" },
  1825. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65" },
  1826. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65" },
  1827. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65" },
  1828. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65" },
  1829. { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65" },
  1830. { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65" },
  1831. { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65" },
  1832. { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65" },
  1833. { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65" },
  1834. { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65" },
  1835. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65" },
  1836. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65" },
  1837. { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65" },
  1838. { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65" },
  1839. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65" },
  1840. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65" },
  1841. { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65" },
  1842. { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65" },
  1843. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65" },
  1844. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65" },
  1845. { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65" },
  1846. { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65" },
  1847. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65" },
  1848. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65" },
  1849. { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65" },
  1850. { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65" },
  1851. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65" },
  1852. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65" },
  1853. { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65" },
  1854. { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65" },
  1855. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65" },
  1856. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65" },
  1857. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65" },
  1858. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65" },
  1859. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65" },
  1860. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65" },
  1861. { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65" },
  1862. { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65" },
  1863. { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65" },
  1864. { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65" },
  1865. { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65" },
  1866. { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65" },
  1867. { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65" },
  1868. { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65" },
  1869. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65" },
  1870. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65" },
  1871. { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65" },
  1872. { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65" },
  1873. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65" },
  1874. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65" },
  1875. { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65" },
  1876. { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65" },
  1877. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65" },
  1878. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65" },
  1879. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65" },
  1880. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65" },
  1881. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65" },
  1882. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65" },
  1883. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65" },
  1884. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65" },
  1885. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65" },
  1886. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65" },
  1887. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65" },
  1888. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65" },
  1889. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65" },
  1890. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65" },
  1891. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65" },
  1892. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65" },
  1893. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65" },
  1894. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65" },
  1895. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65" },
  1896. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65" },
  1897. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65" },
  1898. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65" },
  1899. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65" },
  1900. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65" },
  1901. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65" },
  1902. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65" },
  1903. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65" },
  1904. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65" },
  1905. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65" },
  1906. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65" },
  1907. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65" },
  1908. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65" },
  1909. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65" },
  1910. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65" },
  1911. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65" },
  1912. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65" },
  1913. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65" },
  1914. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65" },
  1915. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65" },
  1916. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65" },
  1917. { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65" },
  1918. { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65" },
  1919. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65" },
  1920. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65" },
  1921. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65" },
  1922. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65" },
  1923. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65" },
  1924. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65" },
  1925. { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65" },
  1926. { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65" },
  1927. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65" },
  1928. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65" },
  1929. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65" },
  1930. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65" },
  1931. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65" },
  1932. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65" },
  1933. { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65" },
  1934. { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65" },
  1935. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65" },
  1936. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65" },
  1937. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65" },
  1938. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65" },
  1939. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65" },
  1940. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65" },
  1941. { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65" },
  1942. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65" },
  1943. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65" },
  1944. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65" },
  1945. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65" },
  1946. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65" },
  1947. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65" },
  1948. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65" },
  1949. { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65" },
  1950. { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65" },
  1951. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65" },
  1952. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65" },
  1953. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65" },
  1954. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65" },
  1955. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65" },
  1956. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65" },
  1957. { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65" },
  1958. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65" },
  1959. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65" },
  1960. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65" },
  1961. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65" },
  1962. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65" },
  1963. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65" },
  1964. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65" },
  1965. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65" },
  1966. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65" },
  1967. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65" },
  1968. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65" },
  1969. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65" },
  1970. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65" },
  1971. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65" },
  1972. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65" },
  1973. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65" },
  1974. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65" },
  1975. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65" },
  1976. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65" },
  1977. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65" },
  1978. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65" },
  1979. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65" },
  1980. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65" },
  1981. { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65" },
  1982. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65" },
  1983. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65" },
  1984. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65" },
  1985. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65" },
  1986. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65" },
  1987. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65" },
  1988. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65" },
  1989. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65" },
  1990. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65" },
  1991. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65" },
  1992. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65" },
  1993. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65" },
  1994. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65" },
  1995. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65" },
  1996. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65" },
  1997. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65" },
  1998. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65" },
  1999. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65" },
  2000. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65" },
  2001. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65" },
  2002. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65" },
  2003. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65" },
  2004. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65" },
  2005. { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65" },
  2006. { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65" },
  2007. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65" },
  2008. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65" },
  2009. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65" },
  2010. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65" },
  2011. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65" },
  2012. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65" },
  2013. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65" },
  2014. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65" },
  2015. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65" },
  2016. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65" },
  2017. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65" },
  2018. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65" },
  2019. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65" },
  2020. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65" },
  2021. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65" },
  2022. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65" },
  2023. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65" },
  2024. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65" },
  2025. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65" },
  2026. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65" },
  2027. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65" },
  2028. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65" },
  2029. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65" },
  2030. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65" },
  2031. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65" },
  2032. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65" },
  2033. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65" },
  2034. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65" },
  2035. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65" },
  2036. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65" },
  2037. { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65" },
  2038. { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65" },
  2039. { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65" },
  2040. { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65" },
  2041. { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65" },
  2042. { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65" },
  2043. { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65" },
  2044. { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65" },
  2045. { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65" },
  2046. { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65" },
  2047. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65" },
  2048. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65" },
  2049. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65" },
  2050. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65" },
  2051. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65" },
  2052. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65" },
  2053. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65" },
  2054. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65" },
  2055. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65" },
  2056. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65" },
  2057. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65" },
  2058. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65" },
  2059. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65" },
  2060. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65" },
  2061. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65" },
  2062. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65" },
  2063. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65" },
  2064. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65" },
  2065. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65" },
  2066. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65" },
  2067. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65" },
  2068. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65" },
  2069. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65" },
  2070. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65" },
  2071. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65" },
  2072. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65" },
  2073. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65" },
  2074. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65" },
  2075. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65" },
  2076. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65" },
  2077. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65" },
  2078. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65" },
  2079. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65" },
  2080. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65" },
  2081. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65" },
  2082. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65" },
  2083. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65" },
  2084. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65" },
  2085. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65" },
  2086. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65" },
  2087. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65" },
  2088. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65" },
  2089. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65" },
  2090. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65" },
  2091. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65" },
  2092. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65" },
  2093. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65" },
  2094. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65" },
  2095. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65" },
  2096. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65" },
  2097. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65" },
  2098. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65" },
  2099. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65" },
  2100. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65" },
  2101. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65" },
  2102. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65" },
  2103. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65" },
  2104. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65" },
  2105. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65" },
  2106. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65" },
  2107. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65" },
  2108. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65" },
  2109. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65" },
  2110. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65" },
  2111. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65" },
  2112. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65" },
  2113. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65" },
  2114. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65" },
  2115. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65" },
  2116. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65" },
  2117. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65" },
  2118. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65" },
  2119. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65" },
  2120. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65" },
  2121. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65" },
  2122. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65" },
  2123. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65" },
  2124. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65" },
  2125. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65" },
  2126. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65" },
  2127. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65" },
  2128. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65" },
  2129. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65" },
  2130. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65" },
  2131. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65" },
  2132. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65" },
  2133. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65" },
  2134. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65" },
  2135. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65" },
  2136. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65" },
  2137. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65" },
  2138. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65" },
  2139. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65" },
  2140. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65" },
  2141. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65" },
  2142. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65" },
  2143. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65" },
  2144. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65" },
  2145. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65" },
  2146. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65" },
  2147. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65" },
  2148. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65" },
  2149. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65" },
  2150. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65" },
  2151. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65" },
  2152. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65" },
  2153. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65" },
  2154. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65" },
  2155. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65" },
  2156. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65" },
  2157. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65" },
  2158. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65" },
  2159. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65" },
  2160. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65" },
  2161. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65" },
  2162. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65" },
  2163. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65" },
  2164. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65" },
  2165. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65" },
  2166. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65" },
  2167. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65" },
  2168. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65" },
  2169. { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65" },
  2170. { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65" },
  2171. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65" },
  2172. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65" },
  2173. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65" },
  2174. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65" },
  2175. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65" },
  2176. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65" },
  2177. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65" },
  2178. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65" },
  2179. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65" },
  2180. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65" },
  2181. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65" },
  2182. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65" },
  2183. { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65" },
  2184. { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65" },
  2185. { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65" },
  2186. { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65" },
  2187. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65" },
  2188. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65" },
  2189. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65" },
  2190. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65" },
  2191. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65" },
  2192. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65" },
  2193. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65" },
  2194. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65" },
  2195. { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65" },
  2196. { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65" },
  2197. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65" },
  2198. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65" },
  2199. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65" },
  2200. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65" },
  2201. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65" },
  2202. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65" },
  2203. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65" },
  2204. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65" },
  2205. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65" },
  2206. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65" },
  2207. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65" },
  2208. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65" },
  2209. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65" },
  2210. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65" },
  2211. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65" },
  2212. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65" },
  2213. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
  2214. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
  2215. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
  2216. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
  2217. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65" },
  2218. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65" },
  2219. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65" },
  2220. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65" },
  2221. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65" },
  2222. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65" },
  2223. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65" },
  2224. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65" },
  2225. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65" },
  2226. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65" },
  2227. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65" },
  2228. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65" },
  2229. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65" },
  2230. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65" },
  2231. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65" },
  2232. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65" },
  2233. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65" },
  2234. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65" },
  2235. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65" },
  2236. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65" },
  2237. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65" },
  2238. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65" },
  2239. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65" },
  2240. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65" },
  2241. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
  2242. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
  2243. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
  2244. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
  2245. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65" },
  2246. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65" },
  2247. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65" },
  2248. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65" },
  2249. { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65" },
  2250. { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65" },
  2251. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65" },
  2252. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65" },
  2253. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65" },
  2254. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65" },
  2255. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65" },
  2256. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65" },
  2257. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65" },
  2258. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65" },
  2259. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65" },
  2260. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65" },
  2261. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65" },
  2262. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65" },
  2263. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65" },
  2264. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65" },
  2265. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65" },
  2266. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65" },
  2267. { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65" },
  2268. { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65" },
  2269. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65" },
  2270. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65" },
  2271. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65" },
  2272. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65" },
  2273. { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65" },
  2274. { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65" },
  2275. { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65" },
  2276. { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65" },
  2277. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65" },
  2278. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65" },
  2279. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65" },
  2280. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65" },
  2281. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65" },
  2282. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65" },
  2283. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65" },
  2284. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65" },
  2285. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65" },
  2286. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65" },
  2287. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65" },
  2288. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65" },
  2289. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65" },
  2290. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65" },
  2291. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65" },
  2292. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65" },
  2293. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65" },
  2294. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65" },
  2295. { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65" },
  2296. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65" },
  2297. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65" },
  2298. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65" },
  2299. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65" },
  2300. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65" },
  2301. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65" },
  2302. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65" },
  2303. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65" },
  2304. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65" },
  2305. { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65" },
  2306. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65" },
  2307. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65" },
  2308. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65" },
  2309. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65" },
  2310. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65" },
  2311. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65" },
  2312. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65" },
  2313. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65" },
  2314. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65" },
  2315. { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65" },
  2316. { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65" },
  2317. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65" },
  2318. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65" },
  2319. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65" },
  2320. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65" },
  2321. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65" },
  2322. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65" },
  2323. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65" },
  2324. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65" },
  2325. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65" },
  2326. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65" },
  2327. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65" },
  2328. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65" },
  2329. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65" },
  2330. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65" },
  2331. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65" },
  2332. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65" },
  2333. { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65" },
  2334. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65" },
  2335. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65" },
  2336. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65" },
  2337. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65" },
  2338. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65" },
  2339. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65" },
  2340. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65" },
  2341. { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65" },
  2342. { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65" },
  2343. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65" },
  2344. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65" },
  2345. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65" },
  2346. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65" },
  2347. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65" },
  2348. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65" },
  2349. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65" },
  2350. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65" },
  2351. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65" },
  2352. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65" },
  2353. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65" },
  2354. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65" },
  2355. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65" },
  2356. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65" },
  2357. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65" },
  2358. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65" },
  2359. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65" },
  2360. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65" },
  2361. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65" },
  2362. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65" },
  2363. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65" },
  2364. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65" },
  2365. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65" },
  2366. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65" },
  2367. { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65" },
  2368. { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65" },
  2369. { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65" },
  2370. { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65" },
  2371. { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65" },
  2372. { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65" },
  2373. };
  2374. // Sort the tables on first execution so we can binary search them.
  2375. auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
  2376. return LHS.BuiltinID < RHS.BuiltinID;
  2377. };
  2378. static const bool SortOnce =
  2379. (std::sort(std::begin(ValidCPU), std::end(ValidCPU), SortCmp),
  2380. std::sort(std::begin(ValidHVX), std::end(ValidHVX), SortCmp), true);
  2381. (void)SortOnce;
  2382. auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
  2383. return BI.BuiltinID < BuiltinID;
  2384. };
  2385. const TargetInfo &TI = Context.getTargetInfo();
  2386. const BuiltinAndString *FC =
  2387. std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
  2388. LowerBoundCmp);
  2389. if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
  2390. const TargetOptions &Opts = TI.getTargetOpts();
  2391. StringRef CPU = Opts.CPU;
  2392. if (!CPU.empty()) {
  2393. assert(CPU.startswith("hexagon") && "Unexpected CPU name");
  2394. CPU.consume_front("hexagon");
  2395. SmallVector<StringRef, 3> CPUs;
  2396. StringRef(FC->Str).split(CPUs, ',');
  2397. if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
  2398. return Diag(TheCall->getBeginLoc(),
  2399. diag::err_hexagon_builtin_unsupported_cpu);
  2400. }
  2401. }
  2402. const BuiltinAndString *FH =
  2403. std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
  2404. LowerBoundCmp);
  2405. if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
  2406. if (!TI.hasFeature("hvx"))
  2407. return Diag(TheCall->getBeginLoc(),
  2408. diag::err_hexagon_builtin_requires_hvx);
  2409. SmallVector<StringRef, 3> HVXs;
  2410. StringRef(FH->Str).split(HVXs, ',');
  2411. bool IsValid = llvm::any_of(HVXs,
  2412. [&TI] (StringRef V) {
  2413. std::string F = "hvx" + V.str();
  2414. return TI.hasFeature(F);
  2415. });
  2416. if (!IsValid)
  2417. return Diag(TheCall->getBeginLoc(),
  2418. diag::err_hexagon_builtin_unsupported_hvx);
  2419. }
  2420. return false;
  2421. }
  2422. bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
  2423. struct ArgInfo {
  2424. uint8_t OpNum;
  2425. bool IsSigned;
  2426. uint8_t BitWidth;
  2427. uint8_t Align;
  2428. };
  2429. struct BuiltinInfo {
  2430. unsigned BuiltinID;
  2431. ArgInfo Infos[2];
  2432. };
  2433. static BuiltinInfo Infos[] = {
  2434. { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
  2435. { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
  2436. { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
  2437. { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
  2438. { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
  2439. { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
  2440. { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
  2441. { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
  2442. { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
  2443. { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
  2444. { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
  2445. { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
  2446. { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
  2447. { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
  2448. { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
  2449. { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
  2450. { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
  2451. { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
  2452. { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
  2453. { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
  2454. { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
  2455. { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
  2456. { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
  2457. { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
  2458. { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
  2459. { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
  2460. { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
  2461. { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
  2462. { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
  2463. { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
  2464. { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
  2465. { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
  2466. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
  2467. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
  2468. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
  2469. { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
  2470. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
  2471. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
  2472. { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
  2473. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
  2474. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
  2475. { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
  2476. { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
  2477. { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
  2478. { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
  2479. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
  2480. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
  2481. { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
  2482. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
  2483. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
  2484. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
  2485. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
  2486. { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
  2487. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
  2488. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
  2489. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
  2490. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
  2491. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
  2492. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
  2493. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
  2494. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
  2495. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
  2496. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
  2497. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
  2498. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
  2499. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
  2500. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
  2501. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
  2502. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
  2503. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
  2504. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
  2505. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
  2506. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
  2507. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
  2508. {{ 1, false, 6, 0 }} },
  2509. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
  2510. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
  2511. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
  2512. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
  2513. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
  2514. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
  2515. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
  2516. {{ 1, false, 5, 0 }} },
  2517. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
  2518. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
  2519. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
  2520. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
  2521. { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
  2522. { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
  2523. { 2, false, 5, 0 }} },
  2524. { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
  2525. { 2, false, 6, 0 }} },
  2526. { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
  2527. { 3, false, 5, 0 }} },
  2528. { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
  2529. { 3, false, 6, 0 }} },
  2530. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
  2531. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
  2532. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
  2533. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
  2534. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
  2535. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
  2536. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
  2537. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
  2538. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
  2539. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
  2540. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
  2541. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
  2542. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
  2543. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
  2544. { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
  2545. { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
  2546. {{ 2, false, 4, 0 },
  2547. { 3, false, 5, 0 }} },
  2548. { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
  2549. {{ 2, false, 4, 0 },
  2550. { 3, false, 5, 0 }} },
  2551. { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
  2552. {{ 2, false, 4, 0 },
  2553. { 3, false, 5, 0 }} },
  2554. { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
  2555. {{ 2, false, 4, 0 },
  2556. { 3, false, 5, 0 }} },
  2557. { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
  2558. { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
  2559. { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
  2560. { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
  2561. { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
  2562. { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
  2563. { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
  2564. { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
  2565. { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
  2566. { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
  2567. { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
  2568. { 2, false, 5, 0 }} },
  2569. { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
  2570. { 2, false, 6, 0 }} },
  2571. { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
  2572. { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
  2573. { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
  2574. { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
  2575. { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
  2576. { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
  2577. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
  2578. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
  2579. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
  2580. {{ 1, false, 4, 0 }} },
  2581. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
  2582. { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
  2583. {{ 1, false, 4, 0 }} },
  2584. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
  2585. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
  2586. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
  2587. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
  2588. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
  2589. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
  2590. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
  2591. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
  2592. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
  2593. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
  2594. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
  2595. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
  2596. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
  2597. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
  2598. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
  2599. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
  2600. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
  2601. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
  2602. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
  2603. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
  2604. {{ 3, false, 1, 0 }} },
  2605. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
  2606. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
  2607. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
  2608. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
  2609. {{ 3, false, 1, 0 }} },
  2610. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
  2611. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
  2612. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
  2613. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
  2614. {{ 3, false, 1, 0 }} },
  2615. };
  2616. // Use a dynamically initialized static to sort the table exactly once on
  2617. // first run.
  2618. static const bool SortOnce =
  2619. (std::sort(std::begin(Infos), std::end(Infos),
  2620. [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
  2621. return LHS.BuiltinID < RHS.BuiltinID;
  2622. }),
  2623. true);
  2624. (void)SortOnce;
  2625. const BuiltinInfo *F =
  2626. std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
  2627. [](const BuiltinInfo &BI, unsigned BuiltinID) {
  2628. return BI.BuiltinID < BuiltinID;
  2629. });
  2630. if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
  2631. return false;
  2632. bool Error = false;
  2633. for (const ArgInfo &A : F->Infos) {
  2634. // Ignore empty ArgInfo elements.
  2635. if (A.BitWidth == 0)
  2636. continue;
  2637. int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
  2638. int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
  2639. if (!A.Align) {
  2640. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
  2641. } else {
  2642. unsigned M = 1 << A.Align;
  2643. Min *= M;
  2644. Max *= M;
  2645. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
  2646. SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
  2647. }
  2648. }
  2649. return Error;
  2650. }
  2651. bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
  2652. CallExpr *TheCall) {
  2653. return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
  2654. CheckHexagonBuiltinArgument(BuiltinID, TheCall);
  2655. }
  2656. // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
  2657. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  2658. // ordering for DSP is unspecified. MSA is ordered by the data format used
  2659. // by the underlying instruction i.e., df/m, df/n and then by size.
  2660. //
  2661. // FIXME: The size tests here should instead be tablegen'd along with the
  2662. // definitions from include/clang/Basic/BuiltinsMips.def.
  2663. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  2664. // be too.
  2665. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2666. unsigned i = 0, l = 0, u = 0, m = 0;
  2667. switch (BuiltinID) {
  2668. default: return false;
  2669. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  2670. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  2671. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  2672. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  2673. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  2674. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  2675. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  2676. // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
  2677. // df/m field.
  2678. // These intrinsics take an unsigned 3 bit immediate.
  2679. case Mips::BI__builtin_msa_bclri_b:
  2680. case Mips::BI__builtin_msa_bnegi_b:
  2681. case Mips::BI__builtin_msa_bseti_b:
  2682. case Mips::BI__builtin_msa_sat_s_b:
  2683. case Mips::BI__builtin_msa_sat_u_b:
  2684. case Mips::BI__builtin_msa_slli_b:
  2685. case Mips::BI__builtin_msa_srai_b:
  2686. case Mips::BI__builtin_msa_srari_b:
  2687. case Mips::BI__builtin_msa_srli_b:
  2688. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  2689. case Mips::BI__builtin_msa_binsli_b:
  2690. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  2691. // These intrinsics take an unsigned 4 bit immediate.
  2692. case Mips::BI__builtin_msa_bclri_h:
  2693. case Mips::BI__builtin_msa_bnegi_h:
  2694. case Mips::BI__builtin_msa_bseti_h:
  2695. case Mips::BI__builtin_msa_sat_s_h:
  2696. case Mips::BI__builtin_msa_sat_u_h:
  2697. case Mips::BI__builtin_msa_slli_h:
  2698. case Mips::BI__builtin_msa_srai_h:
  2699. case Mips::BI__builtin_msa_srari_h:
  2700. case Mips::BI__builtin_msa_srli_h:
  2701. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  2702. case Mips::BI__builtin_msa_binsli_h:
  2703. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  2704. // These intrinsics take an unsigned 5 bit immediate.
  2705. // The first block of intrinsics actually have an unsigned 5 bit field,
  2706. // not a df/n field.
  2707. case Mips::BI__builtin_msa_clei_u_b:
  2708. case Mips::BI__builtin_msa_clei_u_h:
  2709. case Mips::BI__builtin_msa_clei_u_w:
  2710. case Mips::BI__builtin_msa_clei_u_d:
  2711. case Mips::BI__builtin_msa_clti_u_b:
  2712. case Mips::BI__builtin_msa_clti_u_h:
  2713. case Mips::BI__builtin_msa_clti_u_w:
  2714. case Mips::BI__builtin_msa_clti_u_d:
  2715. case Mips::BI__builtin_msa_maxi_u_b:
  2716. case Mips::BI__builtin_msa_maxi_u_h:
  2717. case Mips::BI__builtin_msa_maxi_u_w:
  2718. case Mips::BI__builtin_msa_maxi_u_d:
  2719. case Mips::BI__builtin_msa_mini_u_b:
  2720. case Mips::BI__builtin_msa_mini_u_h:
  2721. case Mips::BI__builtin_msa_mini_u_w:
  2722. case Mips::BI__builtin_msa_mini_u_d:
  2723. case Mips::BI__builtin_msa_addvi_b:
  2724. case Mips::BI__builtin_msa_addvi_h:
  2725. case Mips::BI__builtin_msa_addvi_w:
  2726. case Mips::BI__builtin_msa_addvi_d:
  2727. case Mips::BI__builtin_msa_bclri_w:
  2728. case Mips::BI__builtin_msa_bnegi_w:
  2729. case Mips::BI__builtin_msa_bseti_w:
  2730. case Mips::BI__builtin_msa_sat_s_w:
  2731. case Mips::BI__builtin_msa_sat_u_w:
  2732. case Mips::BI__builtin_msa_slli_w:
  2733. case Mips::BI__builtin_msa_srai_w:
  2734. case Mips::BI__builtin_msa_srari_w:
  2735. case Mips::BI__builtin_msa_srli_w:
  2736. case Mips::BI__builtin_msa_srlri_w:
  2737. case Mips::BI__builtin_msa_subvi_b:
  2738. case Mips::BI__builtin_msa_subvi_h:
  2739. case Mips::BI__builtin_msa_subvi_w:
  2740. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  2741. case Mips::BI__builtin_msa_binsli_w:
  2742. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  2743. // These intrinsics take an unsigned 6 bit immediate.
  2744. case Mips::BI__builtin_msa_bclri_d:
  2745. case Mips::BI__builtin_msa_bnegi_d:
  2746. case Mips::BI__builtin_msa_bseti_d:
  2747. case Mips::BI__builtin_msa_sat_s_d:
  2748. case Mips::BI__builtin_msa_sat_u_d:
  2749. case Mips::BI__builtin_msa_slli_d:
  2750. case Mips::BI__builtin_msa_srai_d:
  2751. case Mips::BI__builtin_msa_srari_d:
  2752. case Mips::BI__builtin_msa_srli_d:
  2753. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  2754. case Mips::BI__builtin_msa_binsli_d:
  2755. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  2756. // These intrinsics take a signed 5 bit immediate.
  2757. case Mips::BI__builtin_msa_ceqi_b:
  2758. case Mips::BI__builtin_msa_ceqi_h:
  2759. case Mips::BI__builtin_msa_ceqi_w:
  2760. case Mips::BI__builtin_msa_ceqi_d:
  2761. case Mips::BI__builtin_msa_clti_s_b:
  2762. case Mips::BI__builtin_msa_clti_s_h:
  2763. case Mips::BI__builtin_msa_clti_s_w:
  2764. case Mips::BI__builtin_msa_clti_s_d:
  2765. case Mips::BI__builtin_msa_clei_s_b:
  2766. case Mips::BI__builtin_msa_clei_s_h:
  2767. case Mips::BI__builtin_msa_clei_s_w:
  2768. case Mips::BI__builtin_msa_clei_s_d:
  2769. case Mips::BI__builtin_msa_maxi_s_b:
  2770. case Mips::BI__builtin_msa_maxi_s_h:
  2771. case Mips::BI__builtin_msa_maxi_s_w:
  2772. case Mips::BI__builtin_msa_maxi_s_d:
  2773. case Mips::BI__builtin_msa_mini_s_b:
  2774. case Mips::BI__builtin_msa_mini_s_h:
  2775. case Mips::BI__builtin_msa_mini_s_w:
  2776. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  2777. // These intrinsics take an unsigned 8 bit immediate.
  2778. case Mips::BI__builtin_msa_andi_b:
  2779. case Mips::BI__builtin_msa_nori_b:
  2780. case Mips::BI__builtin_msa_ori_b:
  2781. case Mips::BI__builtin_msa_shf_b:
  2782. case Mips::BI__builtin_msa_shf_h:
  2783. case Mips::BI__builtin_msa_shf_w:
  2784. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  2785. case Mips::BI__builtin_msa_bseli_b:
  2786. case Mips::BI__builtin_msa_bmnzi_b:
  2787. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  2788. // df/n format
  2789. // These intrinsics take an unsigned 4 bit immediate.
  2790. case Mips::BI__builtin_msa_copy_s_b:
  2791. case Mips::BI__builtin_msa_copy_u_b:
  2792. case Mips::BI__builtin_msa_insve_b:
  2793. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  2794. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  2795. // These intrinsics take an unsigned 3 bit immediate.
  2796. case Mips::BI__builtin_msa_copy_s_h:
  2797. case Mips::BI__builtin_msa_copy_u_h:
  2798. case Mips::BI__builtin_msa_insve_h:
  2799. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  2800. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  2801. // These intrinsics take an unsigned 2 bit immediate.
  2802. case Mips::BI__builtin_msa_copy_s_w:
  2803. case Mips::BI__builtin_msa_copy_u_w:
  2804. case Mips::BI__builtin_msa_insve_w:
  2805. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  2806. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  2807. // These intrinsics take an unsigned 1 bit immediate.
  2808. case Mips::BI__builtin_msa_copy_s_d:
  2809. case Mips::BI__builtin_msa_copy_u_d:
  2810. case Mips::BI__builtin_msa_insve_d:
  2811. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  2812. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  2813. // Memory offsets and immediate loads.
  2814. // These intrinsics take a signed 10 bit immediate.
  2815. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  2816. case Mips::BI__builtin_msa_ldi_h:
  2817. case Mips::BI__builtin_msa_ldi_w:
  2818. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  2819. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
  2820. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
  2821. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
  2822. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
  2823. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
  2824. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
  2825. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
  2826. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
  2827. }
  2828. if (!m)
  2829. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2830. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  2831. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  2832. }
  2833. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2834. unsigned i = 0, l = 0, u = 0;
  2835. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  2836. BuiltinID == PPC::BI__builtin_divdeu ||
  2837. BuiltinID == PPC::BI__builtin_bpermd;
  2838. bool IsTarget64Bit = Context.getTargetInfo()
  2839. .getTypeWidth(Context
  2840. .getTargetInfo()
  2841. .getIntPtrType()) == 64;
  2842. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  2843. BuiltinID == PPC::BI__builtin_divweu ||
  2844. BuiltinID == PPC::BI__builtin_divde ||
  2845. BuiltinID == PPC::BI__builtin_divdeu;
  2846. if (Is64BitBltin && !IsTarget64Bit)
  2847. return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
  2848. << TheCall->getSourceRange();
  2849. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  2850. (BuiltinID == PPC::BI__builtin_bpermd &&
  2851. !Context.getTargetInfo().hasFeature("bpermd")))
  2852. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  2853. << TheCall->getSourceRange();
  2854. auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
  2855. if (!Context.getTargetInfo().hasFeature("vsx"))
  2856. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  2857. << TheCall->getSourceRange();
  2858. return false;
  2859. };
  2860. switch (BuiltinID) {
  2861. default: return false;
  2862. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  2863. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  2864. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  2865. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  2866. case PPC::BI__builtin_tbegin:
  2867. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  2868. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  2869. case PPC::BI__builtin_tabortwc:
  2870. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  2871. case PPC::BI__builtin_tabortwci:
  2872. case PPC::BI__builtin_tabortdci:
  2873. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  2874. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  2875. case PPC::BI__builtin_vsx_xxpermdi:
  2876. case PPC::BI__builtin_vsx_xxsldwi:
  2877. return SemaBuiltinVSX(TheCall);
  2878. case PPC::BI__builtin_unpack_vector_int128:
  2879. return SemaVSXCheck(TheCall) ||
  2880. SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  2881. case PPC::BI__builtin_pack_vector_int128:
  2882. return SemaVSXCheck(TheCall);
  2883. }
  2884. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2885. }
  2886. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  2887. CallExpr *TheCall) {
  2888. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  2889. Expr *Arg = TheCall->getArg(0);
  2890. llvm::APSInt AbortCode(32);
  2891. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  2892. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  2893. return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
  2894. << Arg->getSourceRange();
  2895. }
  2896. // For intrinsics which take an immediate value as part of the instruction,
  2897. // range check them here.
  2898. unsigned i = 0, l = 0, u = 0;
  2899. switch (BuiltinID) {
  2900. default: return false;
  2901. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  2902. case SystemZ::BI__builtin_s390_verimb:
  2903. case SystemZ::BI__builtin_s390_verimh:
  2904. case SystemZ::BI__builtin_s390_verimf:
  2905. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  2906. case SystemZ::BI__builtin_s390_vfaeb:
  2907. case SystemZ::BI__builtin_s390_vfaeh:
  2908. case SystemZ::BI__builtin_s390_vfaef:
  2909. case SystemZ::BI__builtin_s390_vfaebs:
  2910. case SystemZ::BI__builtin_s390_vfaehs:
  2911. case SystemZ::BI__builtin_s390_vfaefs:
  2912. case SystemZ::BI__builtin_s390_vfaezb:
  2913. case SystemZ::BI__builtin_s390_vfaezh:
  2914. case SystemZ::BI__builtin_s390_vfaezf:
  2915. case SystemZ::BI__builtin_s390_vfaezbs:
  2916. case SystemZ::BI__builtin_s390_vfaezhs:
  2917. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  2918. case SystemZ::BI__builtin_s390_vfisb:
  2919. case SystemZ::BI__builtin_s390_vfidb:
  2920. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  2921. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  2922. case SystemZ::BI__builtin_s390_vftcisb:
  2923. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  2924. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  2925. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  2926. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  2927. case SystemZ::BI__builtin_s390_vstrcb:
  2928. case SystemZ::BI__builtin_s390_vstrch:
  2929. case SystemZ::BI__builtin_s390_vstrcf:
  2930. case SystemZ::BI__builtin_s390_vstrczb:
  2931. case SystemZ::BI__builtin_s390_vstrczh:
  2932. case SystemZ::BI__builtin_s390_vstrczf:
  2933. case SystemZ::BI__builtin_s390_vstrcbs:
  2934. case SystemZ::BI__builtin_s390_vstrchs:
  2935. case SystemZ::BI__builtin_s390_vstrcfs:
  2936. case SystemZ::BI__builtin_s390_vstrczbs:
  2937. case SystemZ::BI__builtin_s390_vstrczhs:
  2938. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  2939. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  2940. case SystemZ::BI__builtin_s390_vfminsb:
  2941. case SystemZ::BI__builtin_s390_vfmaxsb:
  2942. case SystemZ::BI__builtin_s390_vfmindb:
  2943. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  2944. }
  2945. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2946. }
  2947. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  2948. /// This checks that the target supports __builtin_cpu_supports and
  2949. /// that the string argument is constant and valid.
  2950. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  2951. Expr *Arg = TheCall->getArg(0);
  2952. // Check if the argument is a string literal.
  2953. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  2954. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  2955. << Arg->getSourceRange();
  2956. // Check the contents of the string.
  2957. StringRef Feature =
  2958. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  2959. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  2960. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
  2961. << Arg->getSourceRange();
  2962. return false;
  2963. }
  2964. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  2965. /// This checks that the target supports __builtin_cpu_is and
  2966. /// that the string argument is constant and valid.
  2967. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  2968. Expr *Arg = TheCall->getArg(0);
  2969. // Check if the argument is a string literal.
  2970. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  2971. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  2972. << Arg->getSourceRange();
  2973. // Check the contents of the string.
  2974. StringRef Feature =
  2975. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  2976. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  2977. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
  2978. << Arg->getSourceRange();
  2979. return false;
  2980. }
  2981. // Check if the rounding mode is legal.
  2982. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  2983. // Indicates if this instruction has rounding control or just SAE.
  2984. bool HasRC = false;
  2985. unsigned ArgNum = 0;
  2986. switch (BuiltinID) {
  2987. default:
  2988. return false;
  2989. case X86::BI__builtin_ia32_vcvttsd2si32:
  2990. case X86::BI__builtin_ia32_vcvttsd2si64:
  2991. case X86::BI__builtin_ia32_vcvttsd2usi32:
  2992. case X86::BI__builtin_ia32_vcvttsd2usi64:
  2993. case X86::BI__builtin_ia32_vcvttss2si32:
  2994. case X86::BI__builtin_ia32_vcvttss2si64:
  2995. case X86::BI__builtin_ia32_vcvttss2usi32:
  2996. case X86::BI__builtin_ia32_vcvttss2usi64:
  2997. ArgNum = 1;
  2998. break;
  2999. case X86::BI__builtin_ia32_maxpd512:
  3000. case X86::BI__builtin_ia32_maxps512:
  3001. case X86::BI__builtin_ia32_minpd512:
  3002. case X86::BI__builtin_ia32_minps512:
  3003. ArgNum = 2;
  3004. break;
  3005. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  3006. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  3007. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  3008. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  3009. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  3010. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  3011. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  3012. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  3013. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  3014. case X86::BI__builtin_ia32_exp2pd_mask:
  3015. case X86::BI__builtin_ia32_exp2ps_mask:
  3016. case X86::BI__builtin_ia32_getexppd512_mask:
  3017. case X86::BI__builtin_ia32_getexpps512_mask:
  3018. case X86::BI__builtin_ia32_rcp28pd_mask:
  3019. case X86::BI__builtin_ia32_rcp28ps_mask:
  3020. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  3021. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  3022. case X86::BI__builtin_ia32_vcomisd:
  3023. case X86::BI__builtin_ia32_vcomiss:
  3024. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  3025. ArgNum = 3;
  3026. break;
  3027. case X86::BI__builtin_ia32_cmppd512_mask:
  3028. case X86::BI__builtin_ia32_cmpps512_mask:
  3029. case X86::BI__builtin_ia32_cmpsd_mask:
  3030. case X86::BI__builtin_ia32_cmpss_mask:
  3031. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  3032. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  3033. case X86::BI__builtin_ia32_getexpss128_round_mask:
  3034. case X86::BI__builtin_ia32_maxsd_round_mask:
  3035. case X86::BI__builtin_ia32_maxss_round_mask:
  3036. case X86::BI__builtin_ia32_minsd_round_mask:
  3037. case X86::BI__builtin_ia32_minss_round_mask:
  3038. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  3039. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  3040. case X86::BI__builtin_ia32_reducepd512_mask:
  3041. case X86::BI__builtin_ia32_reduceps512_mask:
  3042. case X86::BI__builtin_ia32_rndscalepd_mask:
  3043. case X86::BI__builtin_ia32_rndscaleps_mask:
  3044. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  3045. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  3046. ArgNum = 4;
  3047. break;
  3048. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3049. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3050. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3051. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3052. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3053. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3054. case X86::BI__builtin_ia32_fixupimmss_mask:
  3055. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3056. case X86::BI__builtin_ia32_rangepd512_mask:
  3057. case X86::BI__builtin_ia32_rangeps512_mask:
  3058. case X86::BI__builtin_ia32_rangesd128_round_mask:
  3059. case X86::BI__builtin_ia32_rangess128_round_mask:
  3060. case X86::BI__builtin_ia32_reducesd_mask:
  3061. case X86::BI__builtin_ia32_reducess_mask:
  3062. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3063. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3064. ArgNum = 5;
  3065. break;
  3066. case X86::BI__builtin_ia32_vcvtsd2si64:
  3067. case X86::BI__builtin_ia32_vcvtsd2si32:
  3068. case X86::BI__builtin_ia32_vcvtsd2usi32:
  3069. case X86::BI__builtin_ia32_vcvtsd2usi64:
  3070. case X86::BI__builtin_ia32_vcvtss2si32:
  3071. case X86::BI__builtin_ia32_vcvtss2si64:
  3072. case X86::BI__builtin_ia32_vcvtss2usi32:
  3073. case X86::BI__builtin_ia32_vcvtss2usi64:
  3074. case X86::BI__builtin_ia32_sqrtpd512:
  3075. case X86::BI__builtin_ia32_sqrtps512:
  3076. ArgNum = 1;
  3077. HasRC = true;
  3078. break;
  3079. case X86::BI__builtin_ia32_addpd512:
  3080. case X86::BI__builtin_ia32_addps512:
  3081. case X86::BI__builtin_ia32_divpd512:
  3082. case X86::BI__builtin_ia32_divps512:
  3083. case X86::BI__builtin_ia32_mulpd512:
  3084. case X86::BI__builtin_ia32_mulps512:
  3085. case X86::BI__builtin_ia32_subpd512:
  3086. case X86::BI__builtin_ia32_subps512:
  3087. case X86::BI__builtin_ia32_cvtsi2sd64:
  3088. case X86::BI__builtin_ia32_cvtsi2ss32:
  3089. case X86::BI__builtin_ia32_cvtsi2ss64:
  3090. case X86::BI__builtin_ia32_cvtusi2sd64:
  3091. case X86::BI__builtin_ia32_cvtusi2ss32:
  3092. case X86::BI__builtin_ia32_cvtusi2ss64:
  3093. ArgNum = 2;
  3094. HasRC = true;
  3095. break;
  3096. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  3097. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  3098. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  3099. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  3100. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  3101. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  3102. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  3103. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  3104. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  3105. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  3106. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  3107. ArgNum = 3;
  3108. HasRC = true;
  3109. break;
  3110. case X86::BI__builtin_ia32_addss_round_mask:
  3111. case X86::BI__builtin_ia32_addsd_round_mask:
  3112. case X86::BI__builtin_ia32_divss_round_mask:
  3113. case X86::BI__builtin_ia32_divsd_round_mask:
  3114. case X86::BI__builtin_ia32_mulss_round_mask:
  3115. case X86::BI__builtin_ia32_mulsd_round_mask:
  3116. case X86::BI__builtin_ia32_subss_round_mask:
  3117. case X86::BI__builtin_ia32_subsd_round_mask:
  3118. case X86::BI__builtin_ia32_scalefpd512_mask:
  3119. case X86::BI__builtin_ia32_scalefps512_mask:
  3120. case X86::BI__builtin_ia32_scalefsd_round_mask:
  3121. case X86::BI__builtin_ia32_scalefss_round_mask:
  3122. case X86::BI__builtin_ia32_getmantpd512_mask:
  3123. case X86::BI__builtin_ia32_getmantps512_mask:
  3124. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  3125. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  3126. case X86::BI__builtin_ia32_sqrtss_round_mask:
  3127. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  3128. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  3129. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  3130. case X86::BI__builtin_ia32_vfmaddss3_mask:
  3131. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  3132. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  3133. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  3134. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  3135. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  3136. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  3137. case X86::BI__builtin_ia32_vfmaddps512_mask:
  3138. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  3139. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  3140. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  3141. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  3142. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  3143. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  3144. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  3145. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  3146. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  3147. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  3148. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  3149. ArgNum = 4;
  3150. HasRC = true;
  3151. break;
  3152. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3153. case X86::BI__builtin_ia32_getmantss_round_mask:
  3154. ArgNum = 5;
  3155. HasRC = true;
  3156. break;
  3157. }
  3158. llvm::APSInt Result;
  3159. // We can't check the value of a dependent argument.
  3160. Expr *Arg = TheCall->getArg(ArgNum);
  3161. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3162. return false;
  3163. // Check constant-ness first.
  3164. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3165. return true;
  3166. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  3167. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  3168. // combined with ROUND_NO_EXC.
  3169. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  3170. Result == 8/*ROUND_NO_EXC*/ ||
  3171. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  3172. return false;
  3173. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
  3174. << Arg->getSourceRange();
  3175. }
  3176. // Check if the gather/scatter scale is legal.
  3177. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  3178. CallExpr *TheCall) {
  3179. unsigned ArgNum = 0;
  3180. switch (BuiltinID) {
  3181. default:
  3182. return false;
  3183. case X86::BI__builtin_ia32_gatherpfdpd:
  3184. case X86::BI__builtin_ia32_gatherpfdps:
  3185. case X86::BI__builtin_ia32_gatherpfqpd:
  3186. case X86::BI__builtin_ia32_gatherpfqps:
  3187. case X86::BI__builtin_ia32_scatterpfdpd:
  3188. case X86::BI__builtin_ia32_scatterpfdps:
  3189. case X86::BI__builtin_ia32_scatterpfqpd:
  3190. case X86::BI__builtin_ia32_scatterpfqps:
  3191. ArgNum = 3;
  3192. break;
  3193. case X86::BI__builtin_ia32_gatherd_pd:
  3194. case X86::BI__builtin_ia32_gatherd_pd256:
  3195. case X86::BI__builtin_ia32_gatherq_pd:
  3196. case X86::BI__builtin_ia32_gatherq_pd256:
  3197. case X86::BI__builtin_ia32_gatherd_ps:
  3198. case X86::BI__builtin_ia32_gatherd_ps256:
  3199. case X86::BI__builtin_ia32_gatherq_ps:
  3200. case X86::BI__builtin_ia32_gatherq_ps256:
  3201. case X86::BI__builtin_ia32_gatherd_q:
  3202. case X86::BI__builtin_ia32_gatherd_q256:
  3203. case X86::BI__builtin_ia32_gatherq_q:
  3204. case X86::BI__builtin_ia32_gatherq_q256:
  3205. case X86::BI__builtin_ia32_gatherd_d:
  3206. case X86::BI__builtin_ia32_gatherd_d256:
  3207. case X86::BI__builtin_ia32_gatherq_d:
  3208. case X86::BI__builtin_ia32_gatherq_d256:
  3209. case X86::BI__builtin_ia32_gather3div2df:
  3210. case X86::BI__builtin_ia32_gather3div2di:
  3211. case X86::BI__builtin_ia32_gather3div4df:
  3212. case X86::BI__builtin_ia32_gather3div4di:
  3213. case X86::BI__builtin_ia32_gather3div4sf:
  3214. case X86::BI__builtin_ia32_gather3div4si:
  3215. case X86::BI__builtin_ia32_gather3div8sf:
  3216. case X86::BI__builtin_ia32_gather3div8si:
  3217. case X86::BI__builtin_ia32_gather3siv2df:
  3218. case X86::BI__builtin_ia32_gather3siv2di:
  3219. case X86::BI__builtin_ia32_gather3siv4df:
  3220. case X86::BI__builtin_ia32_gather3siv4di:
  3221. case X86::BI__builtin_ia32_gather3siv4sf:
  3222. case X86::BI__builtin_ia32_gather3siv4si:
  3223. case X86::BI__builtin_ia32_gather3siv8sf:
  3224. case X86::BI__builtin_ia32_gather3siv8si:
  3225. case X86::BI__builtin_ia32_gathersiv8df:
  3226. case X86::BI__builtin_ia32_gathersiv16sf:
  3227. case X86::BI__builtin_ia32_gatherdiv8df:
  3228. case X86::BI__builtin_ia32_gatherdiv16sf:
  3229. case X86::BI__builtin_ia32_gathersiv8di:
  3230. case X86::BI__builtin_ia32_gathersiv16si:
  3231. case X86::BI__builtin_ia32_gatherdiv8di:
  3232. case X86::BI__builtin_ia32_gatherdiv16si:
  3233. case X86::BI__builtin_ia32_scatterdiv2df:
  3234. case X86::BI__builtin_ia32_scatterdiv2di:
  3235. case X86::BI__builtin_ia32_scatterdiv4df:
  3236. case X86::BI__builtin_ia32_scatterdiv4di:
  3237. case X86::BI__builtin_ia32_scatterdiv4sf:
  3238. case X86::BI__builtin_ia32_scatterdiv4si:
  3239. case X86::BI__builtin_ia32_scatterdiv8sf:
  3240. case X86::BI__builtin_ia32_scatterdiv8si:
  3241. case X86::BI__builtin_ia32_scattersiv2df:
  3242. case X86::BI__builtin_ia32_scattersiv2di:
  3243. case X86::BI__builtin_ia32_scattersiv4df:
  3244. case X86::BI__builtin_ia32_scattersiv4di:
  3245. case X86::BI__builtin_ia32_scattersiv4sf:
  3246. case X86::BI__builtin_ia32_scattersiv4si:
  3247. case X86::BI__builtin_ia32_scattersiv8sf:
  3248. case X86::BI__builtin_ia32_scattersiv8si:
  3249. case X86::BI__builtin_ia32_scattersiv8df:
  3250. case X86::BI__builtin_ia32_scattersiv16sf:
  3251. case X86::BI__builtin_ia32_scatterdiv8df:
  3252. case X86::BI__builtin_ia32_scatterdiv16sf:
  3253. case X86::BI__builtin_ia32_scattersiv8di:
  3254. case X86::BI__builtin_ia32_scattersiv16si:
  3255. case X86::BI__builtin_ia32_scatterdiv8di:
  3256. case X86::BI__builtin_ia32_scatterdiv16si:
  3257. ArgNum = 4;
  3258. break;
  3259. }
  3260. llvm::APSInt Result;
  3261. // We can't check the value of a dependent argument.
  3262. Expr *Arg = TheCall->getArg(ArgNum);
  3263. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3264. return false;
  3265. // Check constant-ness first.
  3266. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3267. return true;
  3268. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  3269. return false;
  3270. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
  3271. << Arg->getSourceRange();
  3272. }
  3273. static bool isX86_32Builtin(unsigned BuiltinID) {
  3274. // These builtins only work on x86-32 targets.
  3275. switch (BuiltinID) {
  3276. case X86::BI__builtin_ia32_readeflags_u32:
  3277. case X86::BI__builtin_ia32_writeeflags_u32:
  3278. return true;
  3279. }
  3280. return false;
  3281. }
  3282. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  3283. if (BuiltinID == X86::BI__builtin_cpu_supports)
  3284. return SemaBuiltinCpuSupports(*this, TheCall);
  3285. if (BuiltinID == X86::BI__builtin_cpu_is)
  3286. return SemaBuiltinCpuIs(*this, TheCall);
  3287. // Check for 32-bit only builtins on a 64-bit target.
  3288. const llvm::Triple &TT = Context.getTargetInfo().getTriple();
  3289. if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
  3290. return Diag(TheCall->getCallee()->getBeginLoc(),
  3291. diag::err_32_bit_builtin_64_bit_tgt);
  3292. // If the intrinsic has rounding or SAE make sure its valid.
  3293. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  3294. return true;
  3295. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  3296. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  3297. return true;
  3298. // For intrinsics which take an immediate value as part of the instruction,
  3299. // range check them here.
  3300. int i = 0, l = 0, u = 0;
  3301. switch (BuiltinID) {
  3302. default:
  3303. return false;
  3304. case X86::BI__builtin_ia32_vec_ext_v2si:
  3305. case X86::BI__builtin_ia32_vec_ext_v2di:
  3306. case X86::BI__builtin_ia32_vextractf128_pd256:
  3307. case X86::BI__builtin_ia32_vextractf128_ps256:
  3308. case X86::BI__builtin_ia32_vextractf128_si256:
  3309. case X86::BI__builtin_ia32_extract128i256:
  3310. case X86::BI__builtin_ia32_extractf64x4_mask:
  3311. case X86::BI__builtin_ia32_extracti64x4_mask:
  3312. case X86::BI__builtin_ia32_extractf32x8_mask:
  3313. case X86::BI__builtin_ia32_extracti32x8_mask:
  3314. case X86::BI__builtin_ia32_extractf64x2_256_mask:
  3315. case X86::BI__builtin_ia32_extracti64x2_256_mask:
  3316. case X86::BI__builtin_ia32_extractf32x4_256_mask:
  3317. case X86::BI__builtin_ia32_extracti32x4_256_mask:
  3318. i = 1; l = 0; u = 1;
  3319. break;
  3320. case X86::BI__builtin_ia32_vec_set_v2di:
  3321. case X86::BI__builtin_ia32_vinsertf128_pd256:
  3322. case X86::BI__builtin_ia32_vinsertf128_ps256:
  3323. case X86::BI__builtin_ia32_vinsertf128_si256:
  3324. case X86::BI__builtin_ia32_insert128i256:
  3325. case X86::BI__builtin_ia32_insertf32x8:
  3326. case X86::BI__builtin_ia32_inserti32x8:
  3327. case X86::BI__builtin_ia32_insertf64x4:
  3328. case X86::BI__builtin_ia32_inserti64x4:
  3329. case X86::BI__builtin_ia32_insertf64x2_256:
  3330. case X86::BI__builtin_ia32_inserti64x2_256:
  3331. case X86::BI__builtin_ia32_insertf32x4_256:
  3332. case X86::BI__builtin_ia32_inserti32x4_256:
  3333. i = 2; l = 0; u = 1;
  3334. break;
  3335. case X86::BI__builtin_ia32_vpermilpd:
  3336. case X86::BI__builtin_ia32_vec_ext_v4hi:
  3337. case X86::BI__builtin_ia32_vec_ext_v4si:
  3338. case X86::BI__builtin_ia32_vec_ext_v4sf:
  3339. case X86::BI__builtin_ia32_vec_ext_v4di:
  3340. case X86::BI__builtin_ia32_extractf32x4_mask:
  3341. case X86::BI__builtin_ia32_extracti32x4_mask:
  3342. case X86::BI__builtin_ia32_extractf64x2_512_mask:
  3343. case X86::BI__builtin_ia32_extracti64x2_512_mask:
  3344. i = 1; l = 0; u = 3;
  3345. break;
  3346. case X86::BI_mm_prefetch:
  3347. case X86::BI__builtin_ia32_vec_ext_v8hi:
  3348. case X86::BI__builtin_ia32_vec_ext_v8si:
  3349. i = 1; l = 0; u = 7;
  3350. break;
  3351. case X86::BI__builtin_ia32_sha1rnds4:
  3352. case X86::BI__builtin_ia32_blendpd:
  3353. case X86::BI__builtin_ia32_shufpd:
  3354. case X86::BI__builtin_ia32_vec_set_v4hi:
  3355. case X86::BI__builtin_ia32_vec_set_v4si:
  3356. case X86::BI__builtin_ia32_vec_set_v4di:
  3357. case X86::BI__builtin_ia32_shuf_f32x4_256:
  3358. case X86::BI__builtin_ia32_shuf_f64x2_256:
  3359. case X86::BI__builtin_ia32_shuf_i32x4_256:
  3360. case X86::BI__builtin_ia32_shuf_i64x2_256:
  3361. case X86::BI__builtin_ia32_insertf64x2_512:
  3362. case X86::BI__builtin_ia32_inserti64x2_512:
  3363. case X86::BI__builtin_ia32_insertf32x4:
  3364. case X86::BI__builtin_ia32_inserti32x4:
  3365. i = 2; l = 0; u = 3;
  3366. break;
  3367. case X86::BI__builtin_ia32_vpermil2pd:
  3368. case X86::BI__builtin_ia32_vpermil2pd256:
  3369. case X86::BI__builtin_ia32_vpermil2ps:
  3370. case X86::BI__builtin_ia32_vpermil2ps256:
  3371. i = 3; l = 0; u = 3;
  3372. break;
  3373. case X86::BI__builtin_ia32_cmpb128_mask:
  3374. case X86::BI__builtin_ia32_cmpw128_mask:
  3375. case X86::BI__builtin_ia32_cmpd128_mask:
  3376. case X86::BI__builtin_ia32_cmpq128_mask:
  3377. case X86::BI__builtin_ia32_cmpb256_mask:
  3378. case X86::BI__builtin_ia32_cmpw256_mask:
  3379. case X86::BI__builtin_ia32_cmpd256_mask:
  3380. case X86::BI__builtin_ia32_cmpq256_mask:
  3381. case X86::BI__builtin_ia32_cmpb512_mask:
  3382. case X86::BI__builtin_ia32_cmpw512_mask:
  3383. case X86::BI__builtin_ia32_cmpd512_mask:
  3384. case X86::BI__builtin_ia32_cmpq512_mask:
  3385. case X86::BI__builtin_ia32_ucmpb128_mask:
  3386. case X86::BI__builtin_ia32_ucmpw128_mask:
  3387. case X86::BI__builtin_ia32_ucmpd128_mask:
  3388. case X86::BI__builtin_ia32_ucmpq128_mask:
  3389. case X86::BI__builtin_ia32_ucmpb256_mask:
  3390. case X86::BI__builtin_ia32_ucmpw256_mask:
  3391. case X86::BI__builtin_ia32_ucmpd256_mask:
  3392. case X86::BI__builtin_ia32_ucmpq256_mask:
  3393. case X86::BI__builtin_ia32_ucmpb512_mask:
  3394. case X86::BI__builtin_ia32_ucmpw512_mask:
  3395. case X86::BI__builtin_ia32_ucmpd512_mask:
  3396. case X86::BI__builtin_ia32_ucmpq512_mask:
  3397. case X86::BI__builtin_ia32_vpcomub:
  3398. case X86::BI__builtin_ia32_vpcomuw:
  3399. case X86::BI__builtin_ia32_vpcomud:
  3400. case X86::BI__builtin_ia32_vpcomuq:
  3401. case X86::BI__builtin_ia32_vpcomb:
  3402. case X86::BI__builtin_ia32_vpcomw:
  3403. case X86::BI__builtin_ia32_vpcomd:
  3404. case X86::BI__builtin_ia32_vpcomq:
  3405. case X86::BI__builtin_ia32_vec_set_v8hi:
  3406. case X86::BI__builtin_ia32_vec_set_v8si:
  3407. i = 2; l = 0; u = 7;
  3408. break;
  3409. case X86::BI__builtin_ia32_vpermilpd256:
  3410. case X86::BI__builtin_ia32_roundps:
  3411. case X86::BI__builtin_ia32_roundpd:
  3412. case X86::BI__builtin_ia32_roundps256:
  3413. case X86::BI__builtin_ia32_roundpd256:
  3414. case X86::BI__builtin_ia32_getmantpd128_mask:
  3415. case X86::BI__builtin_ia32_getmantpd256_mask:
  3416. case X86::BI__builtin_ia32_getmantps128_mask:
  3417. case X86::BI__builtin_ia32_getmantps256_mask:
  3418. case X86::BI__builtin_ia32_getmantpd512_mask:
  3419. case X86::BI__builtin_ia32_getmantps512_mask:
  3420. case X86::BI__builtin_ia32_vec_ext_v16qi:
  3421. case X86::BI__builtin_ia32_vec_ext_v16hi:
  3422. i = 1; l = 0; u = 15;
  3423. break;
  3424. case X86::BI__builtin_ia32_pblendd128:
  3425. case X86::BI__builtin_ia32_blendps:
  3426. case X86::BI__builtin_ia32_blendpd256:
  3427. case X86::BI__builtin_ia32_shufpd256:
  3428. case X86::BI__builtin_ia32_roundss:
  3429. case X86::BI__builtin_ia32_roundsd:
  3430. case X86::BI__builtin_ia32_rangepd128_mask:
  3431. case X86::BI__builtin_ia32_rangepd256_mask:
  3432. case X86::BI__builtin_ia32_rangepd512_mask:
  3433. case X86::BI__builtin_ia32_rangeps128_mask:
  3434. case X86::BI__builtin_ia32_rangeps256_mask:
  3435. case X86::BI__builtin_ia32_rangeps512_mask:
  3436. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3437. case X86::BI__builtin_ia32_getmantss_round_mask:
  3438. case X86::BI__builtin_ia32_vec_set_v16qi:
  3439. case X86::BI__builtin_ia32_vec_set_v16hi:
  3440. i = 2; l = 0; u = 15;
  3441. break;
  3442. case X86::BI__builtin_ia32_vec_ext_v32qi:
  3443. i = 1; l = 0; u = 31;
  3444. break;
  3445. case X86::BI__builtin_ia32_cmpps:
  3446. case X86::BI__builtin_ia32_cmpss:
  3447. case X86::BI__builtin_ia32_cmppd:
  3448. case X86::BI__builtin_ia32_cmpsd:
  3449. case X86::BI__builtin_ia32_cmpps256:
  3450. case X86::BI__builtin_ia32_cmppd256:
  3451. case X86::BI__builtin_ia32_cmpps128_mask:
  3452. case X86::BI__builtin_ia32_cmppd128_mask:
  3453. case X86::BI__builtin_ia32_cmpps256_mask:
  3454. case X86::BI__builtin_ia32_cmppd256_mask:
  3455. case X86::BI__builtin_ia32_cmpps512_mask:
  3456. case X86::BI__builtin_ia32_cmppd512_mask:
  3457. case X86::BI__builtin_ia32_cmpsd_mask:
  3458. case X86::BI__builtin_ia32_cmpss_mask:
  3459. case X86::BI__builtin_ia32_vec_set_v32qi:
  3460. i = 2; l = 0; u = 31;
  3461. break;
  3462. case X86::BI__builtin_ia32_permdf256:
  3463. case X86::BI__builtin_ia32_permdi256:
  3464. case X86::BI__builtin_ia32_permdf512:
  3465. case X86::BI__builtin_ia32_permdi512:
  3466. case X86::BI__builtin_ia32_vpermilps:
  3467. case X86::BI__builtin_ia32_vpermilps256:
  3468. case X86::BI__builtin_ia32_vpermilpd512:
  3469. case X86::BI__builtin_ia32_vpermilps512:
  3470. case X86::BI__builtin_ia32_pshufd:
  3471. case X86::BI__builtin_ia32_pshufd256:
  3472. case X86::BI__builtin_ia32_pshufd512:
  3473. case X86::BI__builtin_ia32_pshufhw:
  3474. case X86::BI__builtin_ia32_pshufhw256:
  3475. case X86::BI__builtin_ia32_pshufhw512:
  3476. case X86::BI__builtin_ia32_pshuflw:
  3477. case X86::BI__builtin_ia32_pshuflw256:
  3478. case X86::BI__builtin_ia32_pshuflw512:
  3479. case X86::BI__builtin_ia32_vcvtps2ph:
  3480. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  3481. case X86::BI__builtin_ia32_vcvtps2ph256:
  3482. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  3483. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  3484. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  3485. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  3486. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  3487. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  3488. case X86::BI__builtin_ia32_rndscaleps_mask:
  3489. case X86::BI__builtin_ia32_rndscalepd_mask:
  3490. case X86::BI__builtin_ia32_reducepd128_mask:
  3491. case X86::BI__builtin_ia32_reducepd256_mask:
  3492. case X86::BI__builtin_ia32_reducepd512_mask:
  3493. case X86::BI__builtin_ia32_reduceps128_mask:
  3494. case X86::BI__builtin_ia32_reduceps256_mask:
  3495. case X86::BI__builtin_ia32_reduceps512_mask:
  3496. case X86::BI__builtin_ia32_prold512:
  3497. case X86::BI__builtin_ia32_prolq512:
  3498. case X86::BI__builtin_ia32_prold128:
  3499. case X86::BI__builtin_ia32_prold256:
  3500. case X86::BI__builtin_ia32_prolq128:
  3501. case X86::BI__builtin_ia32_prolq256:
  3502. case X86::BI__builtin_ia32_prord512:
  3503. case X86::BI__builtin_ia32_prorq512:
  3504. case X86::BI__builtin_ia32_prord128:
  3505. case X86::BI__builtin_ia32_prord256:
  3506. case X86::BI__builtin_ia32_prorq128:
  3507. case X86::BI__builtin_ia32_prorq256:
  3508. case X86::BI__builtin_ia32_fpclasspd128_mask:
  3509. case X86::BI__builtin_ia32_fpclasspd256_mask:
  3510. case X86::BI__builtin_ia32_fpclassps128_mask:
  3511. case X86::BI__builtin_ia32_fpclassps256_mask:
  3512. case X86::BI__builtin_ia32_fpclassps512_mask:
  3513. case X86::BI__builtin_ia32_fpclasspd512_mask:
  3514. case X86::BI__builtin_ia32_fpclasssd_mask:
  3515. case X86::BI__builtin_ia32_fpclassss_mask:
  3516. case X86::BI__builtin_ia32_pslldqi128_byteshift:
  3517. case X86::BI__builtin_ia32_pslldqi256_byteshift:
  3518. case X86::BI__builtin_ia32_pslldqi512_byteshift:
  3519. case X86::BI__builtin_ia32_psrldqi128_byteshift:
  3520. case X86::BI__builtin_ia32_psrldqi256_byteshift:
  3521. case X86::BI__builtin_ia32_psrldqi512_byteshift:
  3522. case X86::BI__builtin_ia32_kshiftliqi:
  3523. case X86::BI__builtin_ia32_kshiftlihi:
  3524. case X86::BI__builtin_ia32_kshiftlisi:
  3525. case X86::BI__builtin_ia32_kshiftlidi:
  3526. case X86::BI__builtin_ia32_kshiftriqi:
  3527. case X86::BI__builtin_ia32_kshiftrihi:
  3528. case X86::BI__builtin_ia32_kshiftrisi:
  3529. case X86::BI__builtin_ia32_kshiftridi:
  3530. i = 1; l = 0; u = 255;
  3531. break;
  3532. case X86::BI__builtin_ia32_vperm2f128_pd256:
  3533. case X86::BI__builtin_ia32_vperm2f128_ps256:
  3534. case X86::BI__builtin_ia32_vperm2f128_si256:
  3535. case X86::BI__builtin_ia32_permti256:
  3536. case X86::BI__builtin_ia32_pblendw128:
  3537. case X86::BI__builtin_ia32_pblendw256:
  3538. case X86::BI__builtin_ia32_blendps256:
  3539. case X86::BI__builtin_ia32_pblendd256:
  3540. case X86::BI__builtin_ia32_palignr128:
  3541. case X86::BI__builtin_ia32_palignr256:
  3542. case X86::BI__builtin_ia32_palignr512:
  3543. case X86::BI__builtin_ia32_alignq512:
  3544. case X86::BI__builtin_ia32_alignd512:
  3545. case X86::BI__builtin_ia32_alignd128:
  3546. case X86::BI__builtin_ia32_alignd256:
  3547. case X86::BI__builtin_ia32_alignq128:
  3548. case X86::BI__builtin_ia32_alignq256:
  3549. case X86::BI__builtin_ia32_vcomisd:
  3550. case X86::BI__builtin_ia32_vcomiss:
  3551. case X86::BI__builtin_ia32_shuf_f32x4:
  3552. case X86::BI__builtin_ia32_shuf_f64x2:
  3553. case X86::BI__builtin_ia32_shuf_i32x4:
  3554. case X86::BI__builtin_ia32_shuf_i64x2:
  3555. case X86::BI__builtin_ia32_shufpd512:
  3556. case X86::BI__builtin_ia32_shufps:
  3557. case X86::BI__builtin_ia32_shufps256:
  3558. case X86::BI__builtin_ia32_shufps512:
  3559. case X86::BI__builtin_ia32_dbpsadbw128:
  3560. case X86::BI__builtin_ia32_dbpsadbw256:
  3561. case X86::BI__builtin_ia32_dbpsadbw512:
  3562. case X86::BI__builtin_ia32_vpshldd128:
  3563. case X86::BI__builtin_ia32_vpshldd256:
  3564. case X86::BI__builtin_ia32_vpshldd512:
  3565. case X86::BI__builtin_ia32_vpshldq128:
  3566. case X86::BI__builtin_ia32_vpshldq256:
  3567. case X86::BI__builtin_ia32_vpshldq512:
  3568. case X86::BI__builtin_ia32_vpshldw128:
  3569. case X86::BI__builtin_ia32_vpshldw256:
  3570. case X86::BI__builtin_ia32_vpshldw512:
  3571. case X86::BI__builtin_ia32_vpshrdd128:
  3572. case X86::BI__builtin_ia32_vpshrdd256:
  3573. case X86::BI__builtin_ia32_vpshrdd512:
  3574. case X86::BI__builtin_ia32_vpshrdq128:
  3575. case X86::BI__builtin_ia32_vpshrdq256:
  3576. case X86::BI__builtin_ia32_vpshrdq512:
  3577. case X86::BI__builtin_ia32_vpshrdw128:
  3578. case X86::BI__builtin_ia32_vpshrdw256:
  3579. case X86::BI__builtin_ia32_vpshrdw512:
  3580. i = 2; l = 0; u = 255;
  3581. break;
  3582. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3583. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3584. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3585. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3586. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3587. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3588. case X86::BI__builtin_ia32_fixupimmss_mask:
  3589. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3590. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  3591. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  3592. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  3593. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  3594. case X86::BI__builtin_ia32_fixupimmps128_mask:
  3595. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  3596. case X86::BI__builtin_ia32_fixupimmps256_mask:
  3597. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  3598. case X86::BI__builtin_ia32_pternlogd512_mask:
  3599. case X86::BI__builtin_ia32_pternlogd512_maskz:
  3600. case X86::BI__builtin_ia32_pternlogq512_mask:
  3601. case X86::BI__builtin_ia32_pternlogq512_maskz:
  3602. case X86::BI__builtin_ia32_pternlogd128_mask:
  3603. case X86::BI__builtin_ia32_pternlogd128_maskz:
  3604. case X86::BI__builtin_ia32_pternlogd256_mask:
  3605. case X86::BI__builtin_ia32_pternlogd256_maskz:
  3606. case X86::BI__builtin_ia32_pternlogq128_mask:
  3607. case X86::BI__builtin_ia32_pternlogq128_maskz:
  3608. case X86::BI__builtin_ia32_pternlogq256_mask:
  3609. case X86::BI__builtin_ia32_pternlogq256_maskz:
  3610. i = 3; l = 0; u = 255;
  3611. break;
  3612. case X86::BI__builtin_ia32_gatherpfdpd:
  3613. case X86::BI__builtin_ia32_gatherpfdps:
  3614. case X86::BI__builtin_ia32_gatherpfqpd:
  3615. case X86::BI__builtin_ia32_gatherpfqps:
  3616. case X86::BI__builtin_ia32_scatterpfdpd:
  3617. case X86::BI__builtin_ia32_scatterpfdps:
  3618. case X86::BI__builtin_ia32_scatterpfqpd:
  3619. case X86::BI__builtin_ia32_scatterpfqps:
  3620. i = 4; l = 2; u = 3;
  3621. break;
  3622. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3623. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3624. i = 4; l = 0; u = 255;
  3625. break;
  3626. }
  3627. // Note that we don't force a hard error on the range check here, allowing
  3628. // template-generated or macro-generated dead code to potentially have out-of-
  3629. // range values. These need to code generate, but don't need to necessarily
  3630. // make any sense. We use a warning that defaults to an error.
  3631. return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
  3632. }
  3633. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  3634. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  3635. /// Returns true when the format fits the function and the FormatStringInfo has
  3636. /// been populated.
  3637. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  3638. FormatStringInfo *FSI) {
  3639. FSI->HasVAListArg = Format->getFirstArg() == 0;
  3640. FSI->FormatIdx = Format->getFormatIdx() - 1;
  3641. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  3642. // The way the format attribute works in GCC, the implicit this argument
  3643. // of member functions is counted. However, it doesn't appear in our own
  3644. // lists, so decrement format_idx in that case.
  3645. if (IsCXXMember) {
  3646. if(FSI->FormatIdx == 0)
  3647. return false;
  3648. --FSI->FormatIdx;
  3649. if (FSI->FirstDataArg != 0)
  3650. --FSI->FirstDataArg;
  3651. }
  3652. return true;
  3653. }
  3654. /// Checks if a the given expression evaluates to null.
  3655. ///
  3656. /// Returns true if the value evaluates to null.
  3657. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  3658. // If the expression has non-null type, it doesn't evaluate to null.
  3659. if (auto nullability
  3660. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  3661. if (*nullability == NullabilityKind::NonNull)
  3662. return false;
  3663. }
  3664. // As a special case, transparent unions initialized with zero are
  3665. // considered null for the purposes of the nonnull attribute.
  3666. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  3667. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  3668. if (const CompoundLiteralExpr *CLE =
  3669. dyn_cast<CompoundLiteralExpr>(Expr))
  3670. if (const InitListExpr *ILE =
  3671. dyn_cast<InitListExpr>(CLE->getInitializer()))
  3672. Expr = ILE->getInit(0);
  3673. }
  3674. bool Result;
  3675. return (!Expr->isValueDependent() &&
  3676. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  3677. !Result);
  3678. }
  3679. static void CheckNonNullArgument(Sema &S,
  3680. const Expr *ArgExpr,
  3681. SourceLocation CallSiteLoc) {
  3682. if (CheckNonNullExpr(S, ArgExpr))
  3683. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  3684. S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
  3685. }
  3686. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  3687. FormatStringInfo FSI;
  3688. if ((GetFormatStringType(Format) == FST_NSString) &&
  3689. getFormatStringInfo(Format, false, &FSI)) {
  3690. Idx = FSI.FormatIdx;
  3691. return true;
  3692. }
  3693. return false;
  3694. }
  3695. /// Diagnose use of %s directive in an NSString which is being passed
  3696. /// as formatting string to formatting method.
  3697. static void
  3698. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  3699. const NamedDecl *FDecl,
  3700. Expr **Args,
  3701. unsigned NumArgs) {
  3702. unsigned Idx = 0;
  3703. bool Format = false;
  3704. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  3705. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  3706. Idx = 2;
  3707. Format = true;
  3708. }
  3709. else
  3710. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3711. if (S.GetFormatNSStringIdx(I, Idx)) {
  3712. Format = true;
  3713. break;
  3714. }
  3715. }
  3716. if (!Format || NumArgs <= Idx)
  3717. return;
  3718. const Expr *FormatExpr = Args[Idx];
  3719. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  3720. FormatExpr = CSCE->getSubExpr();
  3721. const StringLiteral *FormatString;
  3722. if (const ObjCStringLiteral *OSL =
  3723. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  3724. FormatString = OSL->getString();
  3725. else
  3726. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  3727. if (!FormatString)
  3728. return;
  3729. if (S.FormatStringHasSArg(FormatString)) {
  3730. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  3731. << "%s" << 1 << 1;
  3732. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  3733. << FDecl->getDeclName();
  3734. }
  3735. }
  3736. /// Determine whether the given type has a non-null nullability annotation.
  3737. static bool isNonNullType(ASTContext &ctx, QualType type) {
  3738. if (auto nullability = type->getNullability(ctx))
  3739. return *nullability == NullabilityKind::NonNull;
  3740. return false;
  3741. }
  3742. static void CheckNonNullArguments(Sema &S,
  3743. const NamedDecl *FDecl,
  3744. const FunctionProtoType *Proto,
  3745. ArrayRef<const Expr *> Args,
  3746. SourceLocation CallSiteLoc) {
  3747. assert((FDecl || Proto) && "Need a function declaration or prototype");
  3748. // Check the attributes attached to the method/function itself.
  3749. llvm::SmallBitVector NonNullArgs;
  3750. if (FDecl) {
  3751. // Handle the nonnull attribute on the function/method declaration itself.
  3752. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  3753. if (!NonNull->args_size()) {
  3754. // Easy case: all pointer arguments are nonnull.
  3755. for (const auto *Arg : Args)
  3756. if (S.isValidPointerAttrType(Arg->getType()))
  3757. CheckNonNullArgument(S, Arg, CallSiteLoc);
  3758. return;
  3759. }
  3760. for (const ParamIdx &Idx : NonNull->args()) {
  3761. unsigned IdxAST = Idx.getASTIndex();
  3762. if (IdxAST >= Args.size())
  3763. continue;
  3764. if (NonNullArgs.empty())
  3765. NonNullArgs.resize(Args.size());
  3766. NonNullArgs.set(IdxAST);
  3767. }
  3768. }
  3769. }
  3770. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  3771. // Handle the nonnull attribute on the parameters of the
  3772. // function/method.
  3773. ArrayRef<ParmVarDecl*> parms;
  3774. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  3775. parms = FD->parameters();
  3776. else
  3777. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  3778. unsigned ParamIndex = 0;
  3779. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  3780. I != E; ++I, ++ParamIndex) {
  3781. const ParmVarDecl *PVD = *I;
  3782. if (PVD->hasAttr<NonNullAttr>() ||
  3783. isNonNullType(S.Context, PVD->getType())) {
  3784. if (NonNullArgs.empty())
  3785. NonNullArgs.resize(Args.size());
  3786. NonNullArgs.set(ParamIndex);
  3787. }
  3788. }
  3789. } else {
  3790. // If we have a non-function, non-method declaration but no
  3791. // function prototype, try to dig out the function prototype.
  3792. if (!Proto) {
  3793. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  3794. QualType type = VD->getType().getNonReferenceType();
  3795. if (auto pointerType = type->getAs<PointerType>())
  3796. type = pointerType->getPointeeType();
  3797. else if (auto blockType = type->getAs<BlockPointerType>())
  3798. type = blockType->getPointeeType();
  3799. // FIXME: data member pointers?
  3800. // Dig out the function prototype, if there is one.
  3801. Proto = type->getAs<FunctionProtoType>();
  3802. }
  3803. }
  3804. // Fill in non-null argument information from the nullability
  3805. // information on the parameter types (if we have them).
  3806. if (Proto) {
  3807. unsigned Index = 0;
  3808. for (auto paramType : Proto->getParamTypes()) {
  3809. if (isNonNullType(S.Context, paramType)) {
  3810. if (NonNullArgs.empty())
  3811. NonNullArgs.resize(Args.size());
  3812. NonNullArgs.set(Index);
  3813. }
  3814. ++Index;
  3815. }
  3816. }
  3817. }
  3818. // Check for non-null arguments.
  3819. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  3820. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  3821. if (NonNullArgs[ArgIndex])
  3822. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  3823. }
  3824. }
  3825. /// Handles the checks for format strings, non-POD arguments to vararg
  3826. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  3827. /// attributes.
  3828. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  3829. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  3830. bool IsMemberFunction, SourceLocation Loc,
  3831. SourceRange Range, VariadicCallType CallType) {
  3832. // FIXME: We should check as much as we can in the template definition.
  3833. if (CurContext->isDependentContext())
  3834. return;
  3835. // Printf and scanf checking.
  3836. llvm::SmallBitVector CheckedVarArgs;
  3837. if (FDecl) {
  3838. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3839. // Only create vector if there are format attributes.
  3840. CheckedVarArgs.resize(Args.size());
  3841. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  3842. CheckedVarArgs);
  3843. }
  3844. }
  3845. // Refuse POD arguments that weren't caught by the format string
  3846. // checks above.
  3847. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  3848. if (CallType != VariadicDoesNotApply &&
  3849. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  3850. unsigned NumParams = Proto ? Proto->getNumParams()
  3851. : FDecl && isa<FunctionDecl>(FDecl)
  3852. ? cast<FunctionDecl>(FDecl)->getNumParams()
  3853. : FDecl && isa<ObjCMethodDecl>(FDecl)
  3854. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  3855. : 0;
  3856. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  3857. // Args[ArgIdx] can be null in malformed code.
  3858. if (const Expr *Arg = Args[ArgIdx]) {
  3859. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  3860. checkVariadicArgument(Arg, CallType);
  3861. }
  3862. }
  3863. }
  3864. if (FDecl || Proto) {
  3865. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  3866. // Type safety checking.
  3867. if (FDecl) {
  3868. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  3869. CheckArgumentWithTypeTag(I, Args, Loc);
  3870. }
  3871. }
  3872. if (FD)
  3873. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  3874. }
  3875. /// CheckConstructorCall - Check a constructor call for correctness and safety
  3876. /// properties not enforced by the C type system.
  3877. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  3878. ArrayRef<const Expr *> Args,
  3879. const FunctionProtoType *Proto,
  3880. SourceLocation Loc) {
  3881. VariadicCallType CallType =
  3882. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  3883. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  3884. Loc, SourceRange(), CallType);
  3885. }
  3886. /// CheckFunctionCall - Check a direct function call for various correctness
  3887. /// and safety properties not strictly enforced by the C type system.
  3888. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  3889. const FunctionProtoType *Proto) {
  3890. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  3891. isa<CXXMethodDecl>(FDecl);
  3892. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  3893. IsMemberOperatorCall;
  3894. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  3895. TheCall->getCallee());
  3896. Expr** Args = TheCall->getArgs();
  3897. unsigned NumArgs = TheCall->getNumArgs();
  3898. Expr *ImplicitThis = nullptr;
  3899. if (IsMemberOperatorCall) {
  3900. // If this is a call to a member operator, hide the first argument
  3901. // from checkCall.
  3902. // FIXME: Our choice of AST representation here is less than ideal.
  3903. ImplicitThis = Args[0];
  3904. ++Args;
  3905. --NumArgs;
  3906. } else if (IsMemberFunction)
  3907. ImplicitThis =
  3908. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  3909. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  3910. IsMemberFunction, TheCall->getRParenLoc(),
  3911. TheCall->getCallee()->getSourceRange(), CallType);
  3912. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  3913. // None of the checks below are needed for functions that don't have
  3914. // simple names (e.g., C++ conversion functions).
  3915. if (!FnInfo)
  3916. return false;
  3917. CheckAbsoluteValueFunction(TheCall, FDecl);
  3918. CheckMaxUnsignedZero(TheCall, FDecl);
  3919. if (getLangOpts().ObjC)
  3920. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  3921. unsigned CMId = FDecl->getMemoryFunctionKind();
  3922. if (CMId == 0)
  3923. return false;
  3924. // Handle memory setting and copying functions.
  3925. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  3926. CheckStrlcpycatArguments(TheCall, FnInfo);
  3927. else if (CMId == Builtin::BIstrncat)
  3928. CheckStrncatArguments(TheCall, FnInfo);
  3929. else
  3930. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  3931. return false;
  3932. }
  3933. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  3934. ArrayRef<const Expr *> Args) {
  3935. VariadicCallType CallType =
  3936. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  3937. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  3938. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  3939. CallType);
  3940. return false;
  3941. }
  3942. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  3943. const FunctionProtoType *Proto) {
  3944. QualType Ty;
  3945. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  3946. Ty = V->getType().getNonReferenceType();
  3947. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  3948. Ty = F->getType().getNonReferenceType();
  3949. else
  3950. return false;
  3951. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  3952. !Ty->isFunctionProtoType())
  3953. return false;
  3954. VariadicCallType CallType;
  3955. if (!Proto || !Proto->isVariadic()) {
  3956. CallType = VariadicDoesNotApply;
  3957. } else if (Ty->isBlockPointerType()) {
  3958. CallType = VariadicBlock;
  3959. } else { // Ty->isFunctionPointerType()
  3960. CallType = VariadicFunction;
  3961. }
  3962. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  3963. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  3964. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  3965. TheCall->getCallee()->getSourceRange(), CallType);
  3966. return false;
  3967. }
  3968. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  3969. /// such as function pointers returned from functions.
  3970. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  3971. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  3972. TheCall->getCallee());
  3973. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  3974. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  3975. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  3976. TheCall->getCallee()->getSourceRange(), CallType);
  3977. return false;
  3978. }
  3979. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  3980. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  3981. return false;
  3982. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  3983. switch (Op) {
  3984. case AtomicExpr::AO__c11_atomic_init:
  3985. case AtomicExpr::AO__opencl_atomic_init:
  3986. llvm_unreachable("There is no ordering argument for an init");
  3987. case AtomicExpr::AO__c11_atomic_load:
  3988. case AtomicExpr::AO__opencl_atomic_load:
  3989. case AtomicExpr::AO__atomic_load_n:
  3990. case AtomicExpr::AO__atomic_load:
  3991. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  3992. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  3993. case AtomicExpr::AO__c11_atomic_store:
  3994. case AtomicExpr::AO__opencl_atomic_store:
  3995. case AtomicExpr::AO__atomic_store:
  3996. case AtomicExpr::AO__atomic_store_n:
  3997. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  3998. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  3999. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4000. default:
  4001. return true;
  4002. }
  4003. }
  4004. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  4005. AtomicExpr::AtomicOp Op) {
  4006. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  4007. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4008. // All the non-OpenCL operations take one of the following forms.
  4009. // The OpenCL operations take the __c11 forms with one extra argument for
  4010. // synchronization scope.
  4011. enum {
  4012. // C __c11_atomic_init(A *, C)
  4013. Init,
  4014. // C __c11_atomic_load(A *, int)
  4015. Load,
  4016. // void __atomic_load(A *, CP, int)
  4017. LoadCopy,
  4018. // void __atomic_store(A *, CP, int)
  4019. Copy,
  4020. // C __c11_atomic_add(A *, M, int)
  4021. Arithmetic,
  4022. // C __atomic_exchange_n(A *, CP, int)
  4023. Xchg,
  4024. // void __atomic_exchange(A *, C *, CP, int)
  4025. GNUXchg,
  4026. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  4027. C11CmpXchg,
  4028. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  4029. GNUCmpXchg
  4030. } Form = Init;
  4031. const unsigned NumForm = GNUCmpXchg + 1;
  4032. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  4033. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  4034. // where:
  4035. // C is an appropriate type,
  4036. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  4037. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  4038. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  4039. // the int parameters are for orderings.
  4040. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  4041. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  4042. "need to update code for modified forms");
  4043. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  4044. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  4045. AtomicExpr::AO__atomic_load,
  4046. "need to update code for modified C11 atomics");
  4047. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  4048. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  4049. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  4050. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  4051. IsOpenCL;
  4052. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  4053. Op == AtomicExpr::AO__atomic_store_n ||
  4054. Op == AtomicExpr::AO__atomic_exchange_n ||
  4055. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  4056. bool IsAddSub = false;
  4057. bool IsMinMax = false;
  4058. switch (Op) {
  4059. case AtomicExpr::AO__c11_atomic_init:
  4060. case AtomicExpr::AO__opencl_atomic_init:
  4061. Form = Init;
  4062. break;
  4063. case AtomicExpr::AO__c11_atomic_load:
  4064. case AtomicExpr::AO__opencl_atomic_load:
  4065. case AtomicExpr::AO__atomic_load_n:
  4066. Form = Load;
  4067. break;
  4068. case AtomicExpr::AO__atomic_load:
  4069. Form = LoadCopy;
  4070. break;
  4071. case AtomicExpr::AO__c11_atomic_store:
  4072. case AtomicExpr::AO__opencl_atomic_store:
  4073. case AtomicExpr::AO__atomic_store:
  4074. case AtomicExpr::AO__atomic_store_n:
  4075. Form = Copy;
  4076. break;
  4077. case AtomicExpr::AO__c11_atomic_fetch_add:
  4078. case AtomicExpr::AO__c11_atomic_fetch_sub:
  4079. case AtomicExpr::AO__opencl_atomic_fetch_add:
  4080. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  4081. case AtomicExpr::AO__opencl_atomic_fetch_min:
  4082. case AtomicExpr::AO__opencl_atomic_fetch_max:
  4083. case AtomicExpr::AO__atomic_fetch_add:
  4084. case AtomicExpr::AO__atomic_fetch_sub:
  4085. case AtomicExpr::AO__atomic_add_fetch:
  4086. case AtomicExpr::AO__atomic_sub_fetch:
  4087. IsAddSub = true;
  4088. LLVM_FALLTHROUGH;
  4089. case AtomicExpr::AO__c11_atomic_fetch_and:
  4090. case AtomicExpr::AO__c11_atomic_fetch_or:
  4091. case AtomicExpr::AO__c11_atomic_fetch_xor:
  4092. case AtomicExpr::AO__opencl_atomic_fetch_and:
  4093. case AtomicExpr::AO__opencl_atomic_fetch_or:
  4094. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  4095. case AtomicExpr::AO__atomic_fetch_and:
  4096. case AtomicExpr::AO__atomic_fetch_or:
  4097. case AtomicExpr::AO__atomic_fetch_xor:
  4098. case AtomicExpr::AO__atomic_fetch_nand:
  4099. case AtomicExpr::AO__atomic_and_fetch:
  4100. case AtomicExpr::AO__atomic_or_fetch:
  4101. case AtomicExpr::AO__atomic_xor_fetch:
  4102. case AtomicExpr::AO__atomic_nand_fetch:
  4103. Form = Arithmetic;
  4104. break;
  4105. case AtomicExpr::AO__atomic_fetch_min:
  4106. case AtomicExpr::AO__atomic_fetch_max:
  4107. IsMinMax = true;
  4108. Form = Arithmetic;
  4109. break;
  4110. case AtomicExpr::AO__c11_atomic_exchange:
  4111. case AtomicExpr::AO__opencl_atomic_exchange:
  4112. case AtomicExpr::AO__atomic_exchange_n:
  4113. Form = Xchg;
  4114. break;
  4115. case AtomicExpr::AO__atomic_exchange:
  4116. Form = GNUXchg;
  4117. break;
  4118. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  4119. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  4120. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  4121. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  4122. Form = C11CmpXchg;
  4123. break;
  4124. case AtomicExpr::AO__atomic_compare_exchange:
  4125. case AtomicExpr::AO__atomic_compare_exchange_n:
  4126. Form = GNUCmpXchg;
  4127. break;
  4128. }
  4129. unsigned AdjustedNumArgs = NumArgs[Form];
  4130. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  4131. ++AdjustedNumArgs;
  4132. // Check we have the right number of arguments.
  4133. if (TheCall->getNumArgs() < AdjustedNumArgs) {
  4134. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  4135. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4136. << TheCall->getCallee()->getSourceRange();
  4137. return ExprError();
  4138. } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
  4139. Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
  4140. diag::err_typecheck_call_too_many_args)
  4141. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4142. << TheCall->getCallee()->getSourceRange();
  4143. return ExprError();
  4144. }
  4145. // Inspect the first argument of the atomic operation.
  4146. Expr *Ptr = TheCall->getArg(0);
  4147. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  4148. if (ConvertedPtr.isInvalid())
  4149. return ExprError();
  4150. Ptr = ConvertedPtr.get();
  4151. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  4152. if (!pointerType) {
  4153. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4154. << Ptr->getType() << Ptr->getSourceRange();
  4155. return ExprError();
  4156. }
  4157. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  4158. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  4159. QualType ValType = AtomTy; // 'C'
  4160. if (IsC11) {
  4161. if (!AtomTy->isAtomicType()) {
  4162. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
  4163. << Ptr->getType() << Ptr->getSourceRange();
  4164. return ExprError();
  4165. }
  4166. if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
  4167. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  4168. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
  4169. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  4170. << Ptr->getSourceRange();
  4171. return ExprError();
  4172. }
  4173. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  4174. } else if (Form != Load && Form != LoadCopy) {
  4175. if (ValType.isConstQualified()) {
  4176. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
  4177. << Ptr->getType() << Ptr->getSourceRange();
  4178. return ExprError();
  4179. }
  4180. }
  4181. // For an arithmetic operation, the implied arithmetic must be well-formed.
  4182. if (Form == Arithmetic) {
  4183. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  4184. if (IsAddSub && !ValType->isIntegerType()
  4185. && !ValType->isPointerType()) {
  4186. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4187. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4188. return ExprError();
  4189. }
  4190. if (IsMinMax) {
  4191. const BuiltinType *BT = ValType->getAs<BuiltinType>();
  4192. if (!BT || (BT->getKind() != BuiltinType::Int &&
  4193. BT->getKind() != BuiltinType::UInt)) {
  4194. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
  4195. return ExprError();
  4196. }
  4197. }
  4198. if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
  4199. Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
  4200. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4201. return ExprError();
  4202. }
  4203. if (IsC11 && ValType->isPointerType() &&
  4204. RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
  4205. diag::err_incomplete_type)) {
  4206. return ExprError();
  4207. }
  4208. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  4209. // For __atomic_*_n operations, the value type must be a scalar integral or
  4210. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  4211. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4212. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4213. return ExprError();
  4214. }
  4215. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  4216. !AtomTy->isScalarType()) {
  4217. // For GNU atomics, require a trivially-copyable type. This is not part of
  4218. // the GNU atomics specification, but we enforce it for sanity.
  4219. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
  4220. << Ptr->getType() << Ptr->getSourceRange();
  4221. return ExprError();
  4222. }
  4223. switch (ValType.getObjCLifetime()) {
  4224. case Qualifiers::OCL_None:
  4225. case Qualifiers::OCL_ExplicitNone:
  4226. // okay
  4227. break;
  4228. case Qualifiers::OCL_Weak:
  4229. case Qualifiers::OCL_Strong:
  4230. case Qualifiers::OCL_Autoreleasing:
  4231. // FIXME: Can this happen? By this point, ValType should be known
  4232. // to be trivially copyable.
  4233. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4234. << ValType << Ptr->getSourceRange();
  4235. return ExprError();
  4236. }
  4237. // All atomic operations have an overload which takes a pointer to a volatile
  4238. // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
  4239. // into the result or the other operands. Similarly atomic_load takes a
  4240. // pointer to a const 'A'.
  4241. ValType.removeLocalVolatile();
  4242. ValType.removeLocalConst();
  4243. QualType ResultType = ValType;
  4244. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  4245. Form == Init)
  4246. ResultType = Context.VoidTy;
  4247. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  4248. ResultType = Context.BoolTy;
  4249. // The type of a parameter passed 'by value'. In the GNU atomics, such
  4250. // arguments are actually passed as pointers.
  4251. QualType ByValType = ValType; // 'CP'
  4252. bool IsPassedByAddress = false;
  4253. if (!IsC11 && !IsN) {
  4254. ByValType = Ptr->getType();
  4255. IsPassedByAddress = true;
  4256. }
  4257. // The first argument's non-CV pointer type is used to deduce the type of
  4258. // subsequent arguments, except for:
  4259. // - weak flag (always converted to bool)
  4260. // - memory order (always converted to int)
  4261. // - scope (always converted to int)
  4262. for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
  4263. QualType Ty;
  4264. if (i < NumVals[Form] + 1) {
  4265. switch (i) {
  4266. case 0:
  4267. // The first argument is always a pointer. It has a fixed type.
  4268. // It is always dereferenced, a nullptr is undefined.
  4269. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4270. // Nothing else to do: we already know all we want about this pointer.
  4271. continue;
  4272. case 1:
  4273. // The second argument is the non-atomic operand. For arithmetic, this
  4274. // is always passed by value, and for a compare_exchange it is always
  4275. // passed by address. For the rest, GNU uses by-address and C11 uses
  4276. // by-value.
  4277. assert(Form != Load);
  4278. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  4279. Ty = ValType;
  4280. else if (Form == Copy || Form == Xchg) {
  4281. if (IsPassedByAddress)
  4282. // The value pointer is always dereferenced, a nullptr is undefined.
  4283. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4284. Ty = ByValType;
  4285. } else if (Form == Arithmetic)
  4286. Ty = Context.getPointerDiffType();
  4287. else {
  4288. Expr *ValArg = TheCall->getArg(i);
  4289. // The value pointer is always dereferenced, a nullptr is undefined.
  4290. CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
  4291. LangAS AS = LangAS::Default;
  4292. // Keep address space of non-atomic pointer type.
  4293. if (const PointerType *PtrTy =
  4294. ValArg->getType()->getAs<PointerType>()) {
  4295. AS = PtrTy->getPointeeType().getAddressSpace();
  4296. }
  4297. Ty = Context.getPointerType(
  4298. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  4299. }
  4300. break;
  4301. case 2:
  4302. // The third argument to compare_exchange / GNU exchange is the desired
  4303. // value, either by-value (for the C11 and *_n variant) or as a pointer.
  4304. if (IsPassedByAddress)
  4305. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4306. Ty = ByValType;
  4307. break;
  4308. case 3:
  4309. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  4310. Ty = Context.BoolTy;
  4311. break;
  4312. }
  4313. } else {
  4314. // The order(s) and scope are always converted to int.
  4315. Ty = Context.IntTy;
  4316. }
  4317. InitializedEntity Entity =
  4318. InitializedEntity::InitializeParameter(Context, Ty, false);
  4319. ExprResult Arg = TheCall->getArg(i);
  4320. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4321. if (Arg.isInvalid())
  4322. return true;
  4323. TheCall->setArg(i, Arg.get());
  4324. }
  4325. // Permute the arguments into a 'consistent' order.
  4326. SmallVector<Expr*, 5> SubExprs;
  4327. SubExprs.push_back(Ptr);
  4328. switch (Form) {
  4329. case Init:
  4330. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  4331. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4332. break;
  4333. case Load:
  4334. SubExprs.push_back(TheCall->getArg(1)); // Order
  4335. break;
  4336. case LoadCopy:
  4337. case Copy:
  4338. case Arithmetic:
  4339. case Xchg:
  4340. SubExprs.push_back(TheCall->getArg(2)); // Order
  4341. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4342. break;
  4343. case GNUXchg:
  4344. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  4345. SubExprs.push_back(TheCall->getArg(3)); // Order
  4346. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4347. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4348. break;
  4349. case C11CmpXchg:
  4350. SubExprs.push_back(TheCall->getArg(3)); // Order
  4351. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4352. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  4353. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4354. break;
  4355. case GNUCmpXchg:
  4356. SubExprs.push_back(TheCall->getArg(4)); // Order
  4357. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4358. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  4359. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4360. SubExprs.push_back(TheCall->getArg(3)); // Weak
  4361. break;
  4362. }
  4363. if (SubExprs.size() >= 2 && Form != Init) {
  4364. llvm::APSInt Result(32);
  4365. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  4366. !isValidOrderingForOp(Result.getSExtValue(), Op))
  4367. Diag(SubExprs[1]->getBeginLoc(),
  4368. diag::warn_atomic_op_has_invalid_memory_order)
  4369. << SubExprs[1]->getSourceRange();
  4370. }
  4371. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  4372. auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
  4373. llvm::APSInt Result(32);
  4374. if (Scope->isIntegerConstantExpr(Result, Context) &&
  4375. !ScopeModel->isValid(Result.getZExtValue())) {
  4376. Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
  4377. << Scope->getSourceRange();
  4378. }
  4379. SubExprs.push_back(Scope);
  4380. }
  4381. AtomicExpr *AE =
  4382. new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
  4383. ResultType, Op, TheCall->getRParenLoc());
  4384. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  4385. Op == AtomicExpr::AO__c11_atomic_store ||
  4386. Op == AtomicExpr::AO__opencl_atomic_load ||
  4387. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  4388. Context.AtomicUsesUnsupportedLibcall(AE))
  4389. Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
  4390. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  4391. Op == AtomicExpr::AO__opencl_atomic_load)
  4392. ? 0
  4393. : 1);
  4394. return AE;
  4395. }
  4396. /// checkBuiltinArgument - Given a call to a builtin function, perform
  4397. /// normal type-checking on the given argument, updating the call in
  4398. /// place. This is useful when a builtin function requires custom
  4399. /// type-checking for some of its arguments but not necessarily all of
  4400. /// them.
  4401. ///
  4402. /// Returns true on error.
  4403. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  4404. FunctionDecl *Fn = E->getDirectCallee();
  4405. assert(Fn && "builtin call without direct callee!");
  4406. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  4407. InitializedEntity Entity =
  4408. InitializedEntity::InitializeParameter(S.Context, Param);
  4409. ExprResult Arg = E->getArg(0);
  4410. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4411. if (Arg.isInvalid())
  4412. return true;
  4413. E->setArg(ArgIndex, Arg.get());
  4414. return false;
  4415. }
  4416. /// We have a call to a function like __sync_fetch_and_add, which is an
  4417. /// overloaded function based on the pointer type of its first argument.
  4418. /// The main ActOnCallExpr routines have already promoted the types of
  4419. /// arguments because all of these calls are prototyped as void(...).
  4420. ///
  4421. /// This function goes through and does final semantic checking for these
  4422. /// builtins, as well as generating any warnings.
  4423. ExprResult
  4424. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  4425. CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
  4426. Expr *Callee = TheCall->getCallee();
  4427. DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
  4428. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4429. // Ensure that we have at least one argument to do type inference from.
  4430. if (TheCall->getNumArgs() < 1) {
  4431. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4432. << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
  4433. return ExprError();
  4434. }
  4435. // Inspect the first argument of the atomic builtin. This should always be
  4436. // a pointer type, whose element is an integral scalar or pointer type.
  4437. // Because it is a pointer type, we don't have to worry about any implicit
  4438. // casts here.
  4439. // FIXME: We don't allow floating point scalars as input.
  4440. Expr *FirstArg = TheCall->getArg(0);
  4441. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  4442. if (FirstArgResult.isInvalid())
  4443. return ExprError();
  4444. FirstArg = FirstArgResult.get();
  4445. TheCall->setArg(0, FirstArg);
  4446. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  4447. if (!pointerType) {
  4448. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4449. << FirstArg->getType() << FirstArg->getSourceRange();
  4450. return ExprError();
  4451. }
  4452. QualType ValType = pointerType->getPointeeType();
  4453. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4454. !ValType->isBlockPointerType()) {
  4455. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
  4456. << FirstArg->getType() << FirstArg->getSourceRange();
  4457. return ExprError();
  4458. }
  4459. if (ValType.isConstQualified()) {
  4460. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
  4461. << FirstArg->getType() << FirstArg->getSourceRange();
  4462. return ExprError();
  4463. }
  4464. switch (ValType.getObjCLifetime()) {
  4465. case Qualifiers::OCL_None:
  4466. case Qualifiers::OCL_ExplicitNone:
  4467. // okay
  4468. break;
  4469. case Qualifiers::OCL_Weak:
  4470. case Qualifiers::OCL_Strong:
  4471. case Qualifiers::OCL_Autoreleasing:
  4472. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4473. << ValType << FirstArg->getSourceRange();
  4474. return ExprError();
  4475. }
  4476. // Strip any qualifiers off ValType.
  4477. ValType = ValType.getUnqualifiedType();
  4478. // The majority of builtins return a value, but a few have special return
  4479. // types, so allow them to override appropriately below.
  4480. QualType ResultType = ValType;
  4481. // We need to figure out which concrete builtin this maps onto. For example,
  4482. // __sync_fetch_and_add with a 2 byte object turns into
  4483. // __sync_fetch_and_add_2.
  4484. #define BUILTIN_ROW(x) \
  4485. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  4486. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  4487. static const unsigned BuiltinIndices[][5] = {
  4488. BUILTIN_ROW(__sync_fetch_and_add),
  4489. BUILTIN_ROW(__sync_fetch_and_sub),
  4490. BUILTIN_ROW(__sync_fetch_and_or),
  4491. BUILTIN_ROW(__sync_fetch_and_and),
  4492. BUILTIN_ROW(__sync_fetch_and_xor),
  4493. BUILTIN_ROW(__sync_fetch_and_nand),
  4494. BUILTIN_ROW(__sync_add_and_fetch),
  4495. BUILTIN_ROW(__sync_sub_and_fetch),
  4496. BUILTIN_ROW(__sync_and_and_fetch),
  4497. BUILTIN_ROW(__sync_or_and_fetch),
  4498. BUILTIN_ROW(__sync_xor_and_fetch),
  4499. BUILTIN_ROW(__sync_nand_and_fetch),
  4500. BUILTIN_ROW(__sync_val_compare_and_swap),
  4501. BUILTIN_ROW(__sync_bool_compare_and_swap),
  4502. BUILTIN_ROW(__sync_lock_test_and_set),
  4503. BUILTIN_ROW(__sync_lock_release),
  4504. BUILTIN_ROW(__sync_swap)
  4505. };
  4506. #undef BUILTIN_ROW
  4507. // Determine the index of the size.
  4508. unsigned SizeIndex;
  4509. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  4510. case 1: SizeIndex = 0; break;
  4511. case 2: SizeIndex = 1; break;
  4512. case 4: SizeIndex = 2; break;
  4513. case 8: SizeIndex = 3; break;
  4514. case 16: SizeIndex = 4; break;
  4515. default:
  4516. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
  4517. << FirstArg->getType() << FirstArg->getSourceRange();
  4518. return ExprError();
  4519. }
  4520. // Each of these builtins has one pointer argument, followed by some number of
  4521. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  4522. // that we ignore. Find out which row of BuiltinIndices to read from as well
  4523. // as the number of fixed args.
  4524. unsigned BuiltinID = FDecl->getBuiltinID();
  4525. unsigned BuiltinIndex, NumFixed = 1;
  4526. bool WarnAboutSemanticsChange = false;
  4527. switch (BuiltinID) {
  4528. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  4529. case Builtin::BI__sync_fetch_and_add:
  4530. case Builtin::BI__sync_fetch_and_add_1:
  4531. case Builtin::BI__sync_fetch_and_add_2:
  4532. case Builtin::BI__sync_fetch_and_add_4:
  4533. case Builtin::BI__sync_fetch_and_add_8:
  4534. case Builtin::BI__sync_fetch_and_add_16:
  4535. BuiltinIndex = 0;
  4536. break;
  4537. case Builtin::BI__sync_fetch_and_sub:
  4538. case Builtin::BI__sync_fetch_and_sub_1:
  4539. case Builtin::BI__sync_fetch_and_sub_2:
  4540. case Builtin::BI__sync_fetch_and_sub_4:
  4541. case Builtin::BI__sync_fetch_and_sub_8:
  4542. case Builtin::BI__sync_fetch_and_sub_16:
  4543. BuiltinIndex = 1;
  4544. break;
  4545. case Builtin::BI__sync_fetch_and_or:
  4546. case Builtin::BI__sync_fetch_and_or_1:
  4547. case Builtin::BI__sync_fetch_and_or_2:
  4548. case Builtin::BI__sync_fetch_and_or_4:
  4549. case Builtin::BI__sync_fetch_and_or_8:
  4550. case Builtin::BI__sync_fetch_and_or_16:
  4551. BuiltinIndex = 2;
  4552. break;
  4553. case Builtin::BI__sync_fetch_and_and:
  4554. case Builtin::BI__sync_fetch_and_and_1:
  4555. case Builtin::BI__sync_fetch_and_and_2:
  4556. case Builtin::BI__sync_fetch_and_and_4:
  4557. case Builtin::BI__sync_fetch_and_and_8:
  4558. case Builtin::BI__sync_fetch_and_and_16:
  4559. BuiltinIndex = 3;
  4560. break;
  4561. case Builtin::BI__sync_fetch_and_xor:
  4562. case Builtin::BI__sync_fetch_and_xor_1:
  4563. case Builtin::BI__sync_fetch_and_xor_2:
  4564. case Builtin::BI__sync_fetch_and_xor_4:
  4565. case Builtin::BI__sync_fetch_and_xor_8:
  4566. case Builtin::BI__sync_fetch_and_xor_16:
  4567. BuiltinIndex = 4;
  4568. break;
  4569. case Builtin::BI__sync_fetch_and_nand:
  4570. case Builtin::BI__sync_fetch_and_nand_1:
  4571. case Builtin::BI__sync_fetch_and_nand_2:
  4572. case Builtin::BI__sync_fetch_and_nand_4:
  4573. case Builtin::BI__sync_fetch_and_nand_8:
  4574. case Builtin::BI__sync_fetch_and_nand_16:
  4575. BuiltinIndex = 5;
  4576. WarnAboutSemanticsChange = true;
  4577. break;
  4578. case Builtin::BI__sync_add_and_fetch:
  4579. case Builtin::BI__sync_add_and_fetch_1:
  4580. case Builtin::BI__sync_add_and_fetch_2:
  4581. case Builtin::BI__sync_add_and_fetch_4:
  4582. case Builtin::BI__sync_add_and_fetch_8:
  4583. case Builtin::BI__sync_add_and_fetch_16:
  4584. BuiltinIndex = 6;
  4585. break;
  4586. case Builtin::BI__sync_sub_and_fetch:
  4587. case Builtin::BI__sync_sub_and_fetch_1:
  4588. case Builtin::BI__sync_sub_and_fetch_2:
  4589. case Builtin::BI__sync_sub_and_fetch_4:
  4590. case Builtin::BI__sync_sub_and_fetch_8:
  4591. case Builtin::BI__sync_sub_and_fetch_16:
  4592. BuiltinIndex = 7;
  4593. break;
  4594. case Builtin::BI__sync_and_and_fetch:
  4595. case Builtin::BI__sync_and_and_fetch_1:
  4596. case Builtin::BI__sync_and_and_fetch_2:
  4597. case Builtin::BI__sync_and_and_fetch_4:
  4598. case Builtin::BI__sync_and_and_fetch_8:
  4599. case Builtin::BI__sync_and_and_fetch_16:
  4600. BuiltinIndex = 8;
  4601. break;
  4602. case Builtin::BI__sync_or_and_fetch:
  4603. case Builtin::BI__sync_or_and_fetch_1:
  4604. case Builtin::BI__sync_or_and_fetch_2:
  4605. case Builtin::BI__sync_or_and_fetch_4:
  4606. case Builtin::BI__sync_or_and_fetch_8:
  4607. case Builtin::BI__sync_or_and_fetch_16:
  4608. BuiltinIndex = 9;
  4609. break;
  4610. case Builtin::BI__sync_xor_and_fetch:
  4611. case Builtin::BI__sync_xor_and_fetch_1:
  4612. case Builtin::BI__sync_xor_and_fetch_2:
  4613. case Builtin::BI__sync_xor_and_fetch_4:
  4614. case Builtin::BI__sync_xor_and_fetch_8:
  4615. case Builtin::BI__sync_xor_and_fetch_16:
  4616. BuiltinIndex = 10;
  4617. break;
  4618. case Builtin::BI__sync_nand_and_fetch:
  4619. case Builtin::BI__sync_nand_and_fetch_1:
  4620. case Builtin::BI__sync_nand_and_fetch_2:
  4621. case Builtin::BI__sync_nand_and_fetch_4:
  4622. case Builtin::BI__sync_nand_and_fetch_8:
  4623. case Builtin::BI__sync_nand_and_fetch_16:
  4624. BuiltinIndex = 11;
  4625. WarnAboutSemanticsChange = true;
  4626. break;
  4627. case Builtin::BI__sync_val_compare_and_swap:
  4628. case Builtin::BI__sync_val_compare_and_swap_1:
  4629. case Builtin::BI__sync_val_compare_and_swap_2:
  4630. case Builtin::BI__sync_val_compare_and_swap_4:
  4631. case Builtin::BI__sync_val_compare_and_swap_8:
  4632. case Builtin::BI__sync_val_compare_and_swap_16:
  4633. BuiltinIndex = 12;
  4634. NumFixed = 2;
  4635. break;
  4636. case Builtin::BI__sync_bool_compare_and_swap:
  4637. case Builtin::BI__sync_bool_compare_and_swap_1:
  4638. case Builtin::BI__sync_bool_compare_and_swap_2:
  4639. case Builtin::BI__sync_bool_compare_and_swap_4:
  4640. case Builtin::BI__sync_bool_compare_and_swap_8:
  4641. case Builtin::BI__sync_bool_compare_and_swap_16:
  4642. BuiltinIndex = 13;
  4643. NumFixed = 2;
  4644. ResultType = Context.BoolTy;
  4645. break;
  4646. case Builtin::BI__sync_lock_test_and_set:
  4647. case Builtin::BI__sync_lock_test_and_set_1:
  4648. case Builtin::BI__sync_lock_test_and_set_2:
  4649. case Builtin::BI__sync_lock_test_and_set_4:
  4650. case Builtin::BI__sync_lock_test_and_set_8:
  4651. case Builtin::BI__sync_lock_test_and_set_16:
  4652. BuiltinIndex = 14;
  4653. break;
  4654. case Builtin::BI__sync_lock_release:
  4655. case Builtin::BI__sync_lock_release_1:
  4656. case Builtin::BI__sync_lock_release_2:
  4657. case Builtin::BI__sync_lock_release_4:
  4658. case Builtin::BI__sync_lock_release_8:
  4659. case Builtin::BI__sync_lock_release_16:
  4660. BuiltinIndex = 15;
  4661. NumFixed = 0;
  4662. ResultType = Context.VoidTy;
  4663. break;
  4664. case Builtin::BI__sync_swap:
  4665. case Builtin::BI__sync_swap_1:
  4666. case Builtin::BI__sync_swap_2:
  4667. case Builtin::BI__sync_swap_4:
  4668. case Builtin::BI__sync_swap_8:
  4669. case Builtin::BI__sync_swap_16:
  4670. BuiltinIndex = 16;
  4671. break;
  4672. }
  4673. // Now that we know how many fixed arguments we expect, first check that we
  4674. // have at least that many.
  4675. if (TheCall->getNumArgs() < 1+NumFixed) {
  4676. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4677. << 0 << 1 + NumFixed << TheCall->getNumArgs()
  4678. << Callee->getSourceRange();
  4679. return ExprError();
  4680. }
  4681. Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
  4682. << Callee->getSourceRange();
  4683. if (WarnAboutSemanticsChange) {
  4684. Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
  4685. << Callee->getSourceRange();
  4686. }
  4687. // Get the decl for the concrete builtin from this, we can tell what the
  4688. // concrete integer type we should convert to is.
  4689. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  4690. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  4691. FunctionDecl *NewBuiltinDecl;
  4692. if (NewBuiltinID == BuiltinID)
  4693. NewBuiltinDecl = FDecl;
  4694. else {
  4695. // Perform builtin lookup to avoid redeclaring it.
  4696. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  4697. LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
  4698. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  4699. assert(Res.getFoundDecl());
  4700. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  4701. if (!NewBuiltinDecl)
  4702. return ExprError();
  4703. }
  4704. // The first argument --- the pointer --- has a fixed type; we
  4705. // deduce the types of the rest of the arguments accordingly. Walk
  4706. // the remaining arguments, converting them to the deduced value type.
  4707. for (unsigned i = 0; i != NumFixed; ++i) {
  4708. ExprResult Arg = TheCall->getArg(i+1);
  4709. // GCC does an implicit conversion to the pointer or integer ValType. This
  4710. // can fail in some cases (1i -> int**), check for this error case now.
  4711. // Initialize the argument.
  4712. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  4713. ValType, /*consume*/ false);
  4714. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4715. if (Arg.isInvalid())
  4716. return ExprError();
  4717. // Okay, we have something that *can* be converted to the right type. Check
  4718. // to see if there is a potentially weird extension going on here. This can
  4719. // happen when you do an atomic operation on something like an char* and
  4720. // pass in 42. The 42 gets converted to char. This is even more strange
  4721. // for things like 45.123 -> char, etc.
  4722. // FIXME: Do this check.
  4723. TheCall->setArg(i+1, Arg.get());
  4724. }
  4725. ASTContext& Context = this->getASTContext();
  4726. // Create a new DeclRefExpr to refer to the new decl.
  4727. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  4728. Context,
  4729. DRE->getQualifierLoc(),
  4730. SourceLocation(),
  4731. NewBuiltinDecl,
  4732. /*enclosing*/ false,
  4733. DRE->getLocation(),
  4734. Context.BuiltinFnTy,
  4735. DRE->getValueKind());
  4736. // Set the callee in the CallExpr.
  4737. // FIXME: This loses syntactic information.
  4738. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  4739. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  4740. CK_BuiltinFnToFnPtr);
  4741. TheCall->setCallee(PromotedCall.get());
  4742. // Change the result type of the call to match the original value type. This
  4743. // is arbitrary, but the codegen for these builtins ins design to handle it
  4744. // gracefully.
  4745. TheCall->setType(ResultType);
  4746. return TheCallResult;
  4747. }
  4748. /// SemaBuiltinNontemporalOverloaded - We have a call to
  4749. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  4750. /// overloaded function based on the pointer type of its last argument.
  4751. ///
  4752. /// This function goes through and does final semantic checking for these
  4753. /// builtins.
  4754. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  4755. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  4756. DeclRefExpr *DRE =
  4757. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4758. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4759. unsigned BuiltinID = FDecl->getBuiltinID();
  4760. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  4761. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  4762. "Unexpected nontemporal load/store builtin!");
  4763. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  4764. unsigned numArgs = isStore ? 2 : 1;
  4765. // Ensure that we have the proper number of arguments.
  4766. if (checkArgCount(*this, TheCall, numArgs))
  4767. return ExprError();
  4768. // Inspect the last argument of the nontemporal builtin. This should always
  4769. // be a pointer type, from which we imply the type of the memory access.
  4770. // Because it is a pointer type, we don't have to worry about any implicit
  4771. // casts here.
  4772. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  4773. ExprResult PointerArgResult =
  4774. DefaultFunctionArrayLvalueConversion(PointerArg);
  4775. if (PointerArgResult.isInvalid())
  4776. return ExprError();
  4777. PointerArg = PointerArgResult.get();
  4778. TheCall->setArg(numArgs - 1, PointerArg);
  4779. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  4780. if (!pointerType) {
  4781. Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
  4782. << PointerArg->getType() << PointerArg->getSourceRange();
  4783. return ExprError();
  4784. }
  4785. QualType ValType = pointerType->getPointeeType();
  4786. // Strip any qualifiers off ValType.
  4787. ValType = ValType.getUnqualifiedType();
  4788. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4789. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  4790. !ValType->isVectorType()) {
  4791. Diag(DRE->getBeginLoc(),
  4792. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  4793. << PointerArg->getType() << PointerArg->getSourceRange();
  4794. return ExprError();
  4795. }
  4796. if (!isStore) {
  4797. TheCall->setType(ValType);
  4798. return TheCallResult;
  4799. }
  4800. ExprResult ValArg = TheCall->getArg(0);
  4801. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4802. Context, ValType, /*consume*/ false);
  4803. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  4804. if (ValArg.isInvalid())
  4805. return ExprError();
  4806. TheCall->setArg(0, ValArg.get());
  4807. TheCall->setType(Context.VoidTy);
  4808. return TheCallResult;
  4809. }
  4810. /// CheckObjCString - Checks that the argument to the builtin
  4811. /// CFString constructor is correct
  4812. /// Note: It might also make sense to do the UTF-16 conversion here (would
  4813. /// simplify the backend).
  4814. bool Sema::CheckObjCString(Expr *Arg) {
  4815. Arg = Arg->IgnoreParenCasts();
  4816. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  4817. if (!Literal || !Literal->isAscii()) {
  4818. Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
  4819. << Arg->getSourceRange();
  4820. return true;
  4821. }
  4822. if (Literal->containsNonAsciiOrNull()) {
  4823. StringRef String = Literal->getString();
  4824. unsigned NumBytes = String.size();
  4825. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  4826. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  4827. llvm::UTF16 *ToPtr = &ToBuf[0];
  4828. llvm::ConversionResult Result =
  4829. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  4830. ToPtr + NumBytes, llvm::strictConversion);
  4831. // Check for conversion failure.
  4832. if (Result != llvm::conversionOK)
  4833. Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
  4834. << Arg->getSourceRange();
  4835. }
  4836. return false;
  4837. }
  4838. /// CheckObjCString - Checks that the format string argument to the os_log()
  4839. /// and os_trace() functions is correct, and converts it to const char *.
  4840. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  4841. Arg = Arg->IgnoreParenCasts();
  4842. auto *Literal = dyn_cast<StringLiteral>(Arg);
  4843. if (!Literal) {
  4844. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  4845. Literal = ObjcLiteral->getString();
  4846. }
  4847. }
  4848. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  4849. return ExprError(
  4850. Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
  4851. << Arg->getSourceRange());
  4852. }
  4853. ExprResult Result(Literal);
  4854. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  4855. InitializedEntity Entity =
  4856. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  4857. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  4858. return Result;
  4859. }
  4860. /// Check that the user is calling the appropriate va_start builtin for the
  4861. /// target and calling convention.
  4862. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  4863. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  4864. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  4865. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  4866. bool IsWindows = TT.isOSWindows();
  4867. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  4868. if (IsX64 || IsAArch64) {
  4869. CallingConv CC = CC_C;
  4870. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  4871. CC = FD->getType()->getAs<FunctionType>()->getCallConv();
  4872. if (IsMSVAStart) {
  4873. // Don't allow this in System V ABI functions.
  4874. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  4875. return S.Diag(Fn->getBeginLoc(),
  4876. diag::err_ms_va_start_used_in_sysv_function);
  4877. } else {
  4878. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  4879. // On x64 Windows, don't allow this in System V ABI functions.
  4880. // (Yes, that means there's no corresponding way to support variadic
  4881. // System V ABI functions on Windows.)
  4882. if ((IsWindows && CC == CC_X86_64SysV) ||
  4883. (!IsWindows && CC == CC_Win64))
  4884. return S.Diag(Fn->getBeginLoc(),
  4885. diag::err_va_start_used_in_wrong_abi_function)
  4886. << !IsWindows;
  4887. }
  4888. return false;
  4889. }
  4890. if (IsMSVAStart)
  4891. return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
  4892. return false;
  4893. }
  4894. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  4895. ParmVarDecl **LastParam = nullptr) {
  4896. // Determine whether the current function, block, or obj-c method is variadic
  4897. // and get its parameter list.
  4898. bool IsVariadic = false;
  4899. ArrayRef<ParmVarDecl *> Params;
  4900. DeclContext *Caller = S.CurContext;
  4901. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  4902. IsVariadic = Block->isVariadic();
  4903. Params = Block->parameters();
  4904. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  4905. IsVariadic = FD->isVariadic();
  4906. Params = FD->parameters();
  4907. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  4908. IsVariadic = MD->isVariadic();
  4909. // FIXME: This isn't correct for methods (results in bogus warning).
  4910. Params = MD->parameters();
  4911. } else if (isa<CapturedDecl>(Caller)) {
  4912. // We don't support va_start in a CapturedDecl.
  4913. S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
  4914. return true;
  4915. } else {
  4916. // This must be some other declcontext that parses exprs.
  4917. S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
  4918. return true;
  4919. }
  4920. if (!IsVariadic) {
  4921. S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
  4922. return true;
  4923. }
  4924. if (LastParam)
  4925. *LastParam = Params.empty() ? nullptr : Params.back();
  4926. return false;
  4927. }
  4928. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  4929. /// for validity. Emit an error and return true on failure; return false
  4930. /// on success.
  4931. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  4932. Expr *Fn = TheCall->getCallee();
  4933. if (checkVAStartABI(*this, BuiltinID, Fn))
  4934. return true;
  4935. if (TheCall->getNumArgs() > 2) {
  4936. Diag(TheCall->getArg(2)->getBeginLoc(),
  4937. diag::err_typecheck_call_too_many_args)
  4938. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  4939. << Fn->getSourceRange()
  4940. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  4941. (*(TheCall->arg_end() - 1))->getEndLoc());
  4942. return true;
  4943. }
  4944. if (TheCall->getNumArgs() < 2) {
  4945. return Diag(TheCall->getEndLoc(),
  4946. diag::err_typecheck_call_too_few_args_at_least)
  4947. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  4948. }
  4949. // Type-check the first argument normally.
  4950. if (checkBuiltinArgument(*this, TheCall, 0))
  4951. return true;
  4952. // Check that the current function is variadic, and get its last parameter.
  4953. ParmVarDecl *LastParam;
  4954. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  4955. return true;
  4956. // Verify that the second argument to the builtin is the last argument of the
  4957. // current function or method.
  4958. bool SecondArgIsLastNamedArgument = false;
  4959. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  4960. // These are valid if SecondArgIsLastNamedArgument is false after the next
  4961. // block.
  4962. QualType Type;
  4963. SourceLocation ParamLoc;
  4964. bool IsCRegister = false;
  4965. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  4966. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  4967. SecondArgIsLastNamedArgument = PV == LastParam;
  4968. Type = PV->getType();
  4969. ParamLoc = PV->getLocation();
  4970. IsCRegister =
  4971. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  4972. }
  4973. }
  4974. if (!SecondArgIsLastNamedArgument)
  4975. Diag(TheCall->getArg(1)->getBeginLoc(),
  4976. diag::warn_second_arg_of_va_start_not_last_named_param);
  4977. else if (IsCRegister || Type->isReferenceType() ||
  4978. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  4979. // Promotable integers are UB, but enumerations need a bit of
  4980. // extra checking to see what their promotable type actually is.
  4981. if (!Type->isPromotableIntegerType())
  4982. return false;
  4983. if (!Type->isEnumeralType())
  4984. return true;
  4985. const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
  4986. return !(ED &&
  4987. Context.typesAreCompatible(ED->getPromotionType(), Type));
  4988. }()) {
  4989. unsigned Reason = 0;
  4990. if (Type->isReferenceType()) Reason = 1;
  4991. else if (IsCRegister) Reason = 2;
  4992. Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
  4993. Diag(ParamLoc, diag::note_parameter_type) << Type;
  4994. }
  4995. TheCall->setType(Context.VoidTy);
  4996. return false;
  4997. }
  4998. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  4999. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  5000. // const char *named_addr);
  5001. Expr *Func = Call->getCallee();
  5002. if (Call->getNumArgs() < 3)
  5003. return Diag(Call->getEndLoc(),
  5004. diag::err_typecheck_call_too_few_args_at_least)
  5005. << 0 /*function call*/ << 3 << Call->getNumArgs();
  5006. // Type-check the first argument normally.
  5007. if (checkBuiltinArgument(*this, Call, 0))
  5008. return true;
  5009. // Check that the current function is variadic.
  5010. if (checkVAStartIsInVariadicFunction(*this, Func))
  5011. return true;
  5012. // __va_start on Windows does not validate the parameter qualifiers
  5013. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  5014. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  5015. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  5016. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  5017. const QualType &ConstCharPtrTy =
  5018. Context.getPointerType(Context.CharTy.withConst());
  5019. if (!Arg1Ty->isPointerType() ||
  5020. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  5021. Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5022. << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
  5023. << 0 /* qualifier difference */
  5024. << 3 /* parameter mismatch */
  5025. << 2 << Arg1->getType() << ConstCharPtrTy;
  5026. const QualType SizeTy = Context.getSizeType();
  5027. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  5028. Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5029. << Arg2->getType() << SizeTy << 1 /* different class */
  5030. << 0 /* qualifier difference */
  5031. << 3 /* parameter mismatch */
  5032. << 3 << Arg2->getType() << SizeTy;
  5033. return false;
  5034. }
  5035. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  5036. /// friends. This is declared to take (...), so we have to check everything.
  5037. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  5038. if (TheCall->getNumArgs() < 2)
  5039. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5040. << 0 << 2 << TheCall->getNumArgs() /*function call*/;
  5041. if (TheCall->getNumArgs() > 2)
  5042. return Diag(TheCall->getArg(2)->getBeginLoc(),
  5043. diag::err_typecheck_call_too_many_args)
  5044. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5045. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5046. (*(TheCall->arg_end() - 1))->getEndLoc());
  5047. ExprResult OrigArg0 = TheCall->getArg(0);
  5048. ExprResult OrigArg1 = TheCall->getArg(1);
  5049. // Do standard promotions between the two arguments, returning their common
  5050. // type.
  5051. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  5052. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  5053. return true;
  5054. // Make sure any conversions are pushed back into the call; this is
  5055. // type safe since unordered compare builtins are declared as "_Bool
  5056. // foo(...)".
  5057. TheCall->setArg(0, OrigArg0.get());
  5058. TheCall->setArg(1, OrigArg1.get());
  5059. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  5060. return false;
  5061. // If the common type isn't a real floating type, then the arguments were
  5062. // invalid for this operation.
  5063. if (Res.isNull() || !Res->isRealFloatingType())
  5064. return Diag(OrigArg0.get()->getBeginLoc(),
  5065. diag::err_typecheck_call_invalid_ordered_compare)
  5066. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  5067. << SourceRange(OrigArg0.get()->getBeginLoc(),
  5068. OrigArg1.get()->getEndLoc());
  5069. return false;
  5070. }
  5071. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  5072. /// __builtin_isnan and friends. This is declared to take (...), so we have
  5073. /// to check everything. We expect the last argument to be a floating point
  5074. /// value.
  5075. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  5076. if (TheCall->getNumArgs() < NumArgs)
  5077. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5078. << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
  5079. if (TheCall->getNumArgs() > NumArgs)
  5080. return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
  5081. diag::err_typecheck_call_too_many_args)
  5082. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  5083. << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
  5084. (*(TheCall->arg_end() - 1))->getEndLoc());
  5085. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  5086. if (OrigArg->isTypeDependent())
  5087. return false;
  5088. // This operation requires a non-_Complex floating-point number.
  5089. if (!OrigArg->getType()->isRealFloatingType())
  5090. return Diag(OrigArg->getBeginLoc(),
  5091. diag::err_typecheck_call_invalid_unary_fp)
  5092. << OrigArg->getType() << OrigArg->getSourceRange();
  5093. // If this is an implicit conversion from float -> float, double, or
  5094. // long double, remove it.
  5095. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  5096. // Only remove standard FloatCasts, leaving other casts inplace
  5097. if (Cast->getCastKind() == CK_FloatingCast) {
  5098. Expr *CastArg = Cast->getSubExpr();
  5099. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  5100. assert(
  5101. (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  5102. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
  5103. Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
  5104. "promotion from float to either float, double, or long double is "
  5105. "the only expected cast here");
  5106. Cast->setSubExpr(nullptr);
  5107. TheCall->setArg(NumArgs-1, CastArg);
  5108. }
  5109. }
  5110. }
  5111. return false;
  5112. }
  5113. // Customized Sema Checking for VSX builtins that have the following signature:
  5114. // vector [...] builtinName(vector [...], vector [...], const int);
  5115. // Which takes the same type of vectors (any legal vector type) for the first
  5116. // two arguments and takes compile time constant for the third argument.
  5117. // Example builtins are :
  5118. // vector double vec_xxpermdi(vector double, vector double, int);
  5119. // vector short vec_xxsldwi(vector short, vector short, int);
  5120. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  5121. unsigned ExpectedNumArgs = 3;
  5122. if (TheCall->getNumArgs() < ExpectedNumArgs)
  5123. return Diag(TheCall->getEndLoc(),
  5124. diag::err_typecheck_call_too_few_args_at_least)
  5125. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5126. << TheCall->getSourceRange();
  5127. if (TheCall->getNumArgs() > ExpectedNumArgs)
  5128. return Diag(TheCall->getEndLoc(),
  5129. diag::err_typecheck_call_too_many_args_at_most)
  5130. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5131. << TheCall->getSourceRange();
  5132. // Check the third argument is a compile time constant
  5133. llvm::APSInt Value;
  5134. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  5135. return Diag(TheCall->getBeginLoc(),
  5136. diag::err_vsx_builtin_nonconstant_argument)
  5137. << 3 /* argument index */ << TheCall->getDirectCallee()
  5138. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5139. TheCall->getArg(2)->getEndLoc());
  5140. QualType Arg1Ty = TheCall->getArg(0)->getType();
  5141. QualType Arg2Ty = TheCall->getArg(1)->getType();
  5142. // Check the type of argument 1 and argument 2 are vectors.
  5143. SourceLocation BuiltinLoc = TheCall->getBeginLoc();
  5144. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  5145. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  5146. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  5147. << TheCall->getDirectCallee()
  5148. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5149. TheCall->getArg(1)->getEndLoc());
  5150. }
  5151. // Check the first two arguments are the same type.
  5152. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  5153. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  5154. << TheCall->getDirectCallee()
  5155. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5156. TheCall->getArg(1)->getEndLoc());
  5157. }
  5158. // When default clang type checking is turned off and the customized type
  5159. // checking is used, the returning type of the function must be explicitly
  5160. // set. Otherwise it is _Bool by default.
  5161. TheCall->setType(Arg1Ty);
  5162. return false;
  5163. }
  5164. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  5165. // This is declared to take (...), so we have to check everything.
  5166. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  5167. if (TheCall->getNumArgs() < 2)
  5168. return ExprError(Diag(TheCall->getEndLoc(),
  5169. diag::err_typecheck_call_too_few_args_at_least)
  5170. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5171. << TheCall->getSourceRange());
  5172. // Determine which of the following types of shufflevector we're checking:
  5173. // 1) unary, vector mask: (lhs, mask)
  5174. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  5175. QualType resType = TheCall->getArg(0)->getType();
  5176. unsigned numElements = 0;
  5177. if (!TheCall->getArg(0)->isTypeDependent() &&
  5178. !TheCall->getArg(1)->isTypeDependent()) {
  5179. QualType LHSType = TheCall->getArg(0)->getType();
  5180. QualType RHSType = TheCall->getArg(1)->getType();
  5181. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  5182. return ExprError(
  5183. Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
  5184. << TheCall->getDirectCallee()
  5185. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5186. TheCall->getArg(1)->getEndLoc()));
  5187. numElements = LHSType->getAs<VectorType>()->getNumElements();
  5188. unsigned numResElements = TheCall->getNumArgs() - 2;
  5189. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  5190. // with mask. If so, verify that RHS is an integer vector type with the
  5191. // same number of elts as lhs.
  5192. if (TheCall->getNumArgs() == 2) {
  5193. if (!RHSType->hasIntegerRepresentation() ||
  5194. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  5195. return ExprError(Diag(TheCall->getBeginLoc(),
  5196. diag::err_vec_builtin_incompatible_vector)
  5197. << TheCall->getDirectCallee()
  5198. << SourceRange(TheCall->getArg(1)->getBeginLoc(),
  5199. TheCall->getArg(1)->getEndLoc()));
  5200. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  5201. return ExprError(Diag(TheCall->getBeginLoc(),
  5202. diag::err_vec_builtin_incompatible_vector)
  5203. << TheCall->getDirectCallee()
  5204. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5205. TheCall->getArg(1)->getEndLoc()));
  5206. } else if (numElements != numResElements) {
  5207. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  5208. resType = Context.getVectorType(eltType, numResElements,
  5209. VectorType::GenericVector);
  5210. }
  5211. }
  5212. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  5213. if (TheCall->getArg(i)->isTypeDependent() ||
  5214. TheCall->getArg(i)->isValueDependent())
  5215. continue;
  5216. llvm::APSInt Result(32);
  5217. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  5218. return ExprError(Diag(TheCall->getBeginLoc(),
  5219. diag::err_shufflevector_nonconstant_argument)
  5220. << TheCall->getArg(i)->getSourceRange());
  5221. // Allow -1 which will be translated to undef in the IR.
  5222. if (Result.isSigned() && Result.isAllOnesValue())
  5223. continue;
  5224. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  5225. return ExprError(Diag(TheCall->getBeginLoc(),
  5226. diag::err_shufflevector_argument_too_large)
  5227. << TheCall->getArg(i)->getSourceRange());
  5228. }
  5229. SmallVector<Expr*, 32> exprs;
  5230. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  5231. exprs.push_back(TheCall->getArg(i));
  5232. TheCall->setArg(i, nullptr);
  5233. }
  5234. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  5235. TheCall->getCallee()->getBeginLoc(),
  5236. TheCall->getRParenLoc());
  5237. }
  5238. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  5239. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  5240. SourceLocation BuiltinLoc,
  5241. SourceLocation RParenLoc) {
  5242. ExprValueKind VK = VK_RValue;
  5243. ExprObjectKind OK = OK_Ordinary;
  5244. QualType DstTy = TInfo->getType();
  5245. QualType SrcTy = E->getType();
  5246. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  5247. return ExprError(Diag(BuiltinLoc,
  5248. diag::err_convertvector_non_vector)
  5249. << E->getSourceRange());
  5250. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  5251. return ExprError(Diag(BuiltinLoc,
  5252. diag::err_convertvector_non_vector_type));
  5253. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  5254. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  5255. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  5256. if (SrcElts != DstElts)
  5257. return ExprError(Diag(BuiltinLoc,
  5258. diag::err_convertvector_incompatible_vector)
  5259. << E->getSourceRange());
  5260. }
  5261. return new (Context)
  5262. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5263. }
  5264. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  5265. // This is declared to take (const void*, ...) and can take two
  5266. // optional constant int args.
  5267. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  5268. unsigned NumArgs = TheCall->getNumArgs();
  5269. if (NumArgs > 3)
  5270. return Diag(TheCall->getEndLoc(),
  5271. diag::err_typecheck_call_too_many_args_at_most)
  5272. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5273. // Argument 0 is checked for us and the remaining arguments must be
  5274. // constant integers.
  5275. for (unsigned i = 1; i != NumArgs; ++i)
  5276. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  5277. return true;
  5278. return false;
  5279. }
  5280. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  5281. // __assume does not evaluate its arguments, and should warn if its argument
  5282. // has side effects.
  5283. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  5284. Expr *Arg = TheCall->getArg(0);
  5285. if (Arg->isInstantiationDependent()) return false;
  5286. if (Arg->HasSideEffects(Context))
  5287. Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
  5288. << Arg->getSourceRange()
  5289. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  5290. return false;
  5291. }
  5292. /// Handle __builtin_alloca_with_align. This is declared
  5293. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  5294. /// than 8.
  5295. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  5296. // The alignment must be a constant integer.
  5297. Expr *Arg = TheCall->getArg(1);
  5298. // We can't check the value of a dependent argument.
  5299. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5300. if (const auto *UE =
  5301. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  5302. if (UE->getKind() == UETT_AlignOf ||
  5303. UE->getKind() == UETT_PreferredAlignOf)
  5304. Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
  5305. << Arg->getSourceRange();
  5306. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  5307. if (!Result.isPowerOf2())
  5308. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5309. << Arg->getSourceRange();
  5310. if (Result < Context.getCharWidth())
  5311. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
  5312. << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
  5313. if (Result > std::numeric_limits<int32_t>::max())
  5314. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
  5315. << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
  5316. }
  5317. return false;
  5318. }
  5319. /// Handle __builtin_assume_aligned. This is declared
  5320. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  5321. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  5322. unsigned NumArgs = TheCall->getNumArgs();
  5323. if (NumArgs > 3)
  5324. return Diag(TheCall->getEndLoc(),
  5325. diag::err_typecheck_call_too_many_args_at_most)
  5326. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5327. // The alignment must be a constant integer.
  5328. Expr *Arg = TheCall->getArg(1);
  5329. // We can't check the value of a dependent argument.
  5330. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5331. llvm::APSInt Result;
  5332. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5333. return true;
  5334. if (!Result.isPowerOf2())
  5335. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5336. << Arg->getSourceRange();
  5337. }
  5338. if (NumArgs > 2) {
  5339. ExprResult Arg(TheCall->getArg(2));
  5340. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  5341. Context.getSizeType(), false);
  5342. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5343. if (Arg.isInvalid()) return true;
  5344. TheCall->setArg(2, Arg.get());
  5345. }
  5346. return false;
  5347. }
  5348. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  5349. unsigned BuiltinID =
  5350. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  5351. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  5352. unsigned NumArgs = TheCall->getNumArgs();
  5353. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  5354. if (NumArgs < NumRequiredArgs) {
  5355. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5356. << 0 /* function call */ << NumRequiredArgs << NumArgs
  5357. << TheCall->getSourceRange();
  5358. }
  5359. if (NumArgs >= NumRequiredArgs + 0x100) {
  5360. return Diag(TheCall->getEndLoc(),
  5361. diag::err_typecheck_call_too_many_args_at_most)
  5362. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  5363. << TheCall->getSourceRange();
  5364. }
  5365. unsigned i = 0;
  5366. // For formatting call, check buffer arg.
  5367. if (!IsSizeCall) {
  5368. ExprResult Arg(TheCall->getArg(i));
  5369. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5370. Context, Context.VoidPtrTy, false);
  5371. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5372. if (Arg.isInvalid())
  5373. return true;
  5374. TheCall->setArg(i, Arg.get());
  5375. i++;
  5376. }
  5377. // Check string literal arg.
  5378. unsigned FormatIdx = i;
  5379. {
  5380. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  5381. if (Arg.isInvalid())
  5382. return true;
  5383. TheCall->setArg(i, Arg.get());
  5384. i++;
  5385. }
  5386. // Make sure variadic args are scalar.
  5387. unsigned FirstDataArg = i;
  5388. while (i < NumArgs) {
  5389. ExprResult Arg = DefaultVariadicArgumentPromotion(
  5390. TheCall->getArg(i), VariadicFunction, nullptr);
  5391. if (Arg.isInvalid())
  5392. return true;
  5393. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  5394. if (ArgSize.getQuantity() >= 0x100) {
  5395. return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
  5396. << i << (int)ArgSize.getQuantity() << 0xff
  5397. << TheCall->getSourceRange();
  5398. }
  5399. TheCall->setArg(i, Arg.get());
  5400. i++;
  5401. }
  5402. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  5403. // call to avoid duplicate diagnostics.
  5404. if (!IsSizeCall) {
  5405. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  5406. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  5407. bool Success = CheckFormatArguments(
  5408. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  5409. VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
  5410. CheckedVarArgs);
  5411. if (!Success)
  5412. return true;
  5413. }
  5414. if (IsSizeCall) {
  5415. TheCall->setType(Context.getSizeType());
  5416. } else {
  5417. TheCall->setType(Context.VoidPtrTy);
  5418. }
  5419. return false;
  5420. }
  5421. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  5422. /// TheCall is a constant expression.
  5423. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  5424. llvm::APSInt &Result) {
  5425. Expr *Arg = TheCall->getArg(ArgNum);
  5426. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5427. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  5428. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  5429. if (!Arg->isIntegerConstantExpr(Result, Context))
  5430. return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
  5431. << FDecl->getDeclName() << Arg->getSourceRange();
  5432. return false;
  5433. }
  5434. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  5435. /// TheCall is a constant expression in the range [Low, High].
  5436. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  5437. int Low, int High, bool RangeIsError) {
  5438. llvm::APSInt Result;
  5439. // We can't check the value of a dependent argument.
  5440. Expr *Arg = TheCall->getArg(ArgNum);
  5441. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5442. return false;
  5443. // Check constant-ness first.
  5444. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5445. return true;
  5446. if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
  5447. if (RangeIsError)
  5448. return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
  5449. << Result.toString(10) << Low << High << Arg->getSourceRange();
  5450. else
  5451. // Defer the warning until we know if the code will be emitted so that
  5452. // dead code can ignore this.
  5453. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  5454. PDiag(diag::warn_argument_invalid_range)
  5455. << Result.toString(10) << Low << High
  5456. << Arg->getSourceRange());
  5457. }
  5458. return false;
  5459. }
  5460. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  5461. /// TheCall is a constant expression is a multiple of Num..
  5462. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  5463. unsigned Num) {
  5464. llvm::APSInt Result;
  5465. // We can't check the value of a dependent argument.
  5466. Expr *Arg = TheCall->getArg(ArgNum);
  5467. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5468. return false;
  5469. // Check constant-ness first.
  5470. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5471. return true;
  5472. if (Result.getSExtValue() % Num != 0)
  5473. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
  5474. << Num << Arg->getSourceRange();
  5475. return false;
  5476. }
  5477. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  5478. /// TheCall is an ARM/AArch64 special register string literal.
  5479. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  5480. int ArgNum, unsigned ExpectedFieldNum,
  5481. bool AllowName) {
  5482. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  5483. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  5484. BuiltinID == ARM::BI__builtin_arm_rsr ||
  5485. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  5486. BuiltinID == ARM::BI__builtin_arm_wsr ||
  5487. BuiltinID == ARM::BI__builtin_arm_wsrp;
  5488. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  5489. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  5490. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  5491. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  5492. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  5493. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  5494. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  5495. // We can't check the value of a dependent argument.
  5496. Expr *Arg = TheCall->getArg(ArgNum);
  5497. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5498. return false;
  5499. // Check if the argument is a string literal.
  5500. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  5501. return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  5502. << Arg->getSourceRange();
  5503. // Check the type of special register given.
  5504. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  5505. SmallVector<StringRef, 6> Fields;
  5506. Reg.split(Fields, ":");
  5507. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  5508. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5509. << Arg->getSourceRange();
  5510. // If the string is the name of a register then we cannot check that it is
  5511. // valid here but if the string is of one the forms described in ACLE then we
  5512. // can check that the supplied fields are integers and within the valid
  5513. // ranges.
  5514. if (Fields.size() > 1) {
  5515. bool FiveFields = Fields.size() == 5;
  5516. bool ValidString = true;
  5517. if (IsARMBuiltin) {
  5518. ValidString &= Fields[0].startswith_lower("cp") ||
  5519. Fields[0].startswith_lower("p");
  5520. if (ValidString)
  5521. Fields[0] =
  5522. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  5523. ValidString &= Fields[2].startswith_lower("c");
  5524. if (ValidString)
  5525. Fields[2] = Fields[2].drop_front(1);
  5526. if (FiveFields) {
  5527. ValidString &= Fields[3].startswith_lower("c");
  5528. if (ValidString)
  5529. Fields[3] = Fields[3].drop_front(1);
  5530. }
  5531. }
  5532. SmallVector<int, 5> Ranges;
  5533. if (FiveFields)
  5534. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  5535. else
  5536. Ranges.append({15, 7, 15});
  5537. for (unsigned i=0; i<Fields.size(); ++i) {
  5538. int IntField;
  5539. ValidString &= !Fields[i].getAsInteger(10, IntField);
  5540. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  5541. }
  5542. if (!ValidString)
  5543. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5544. << Arg->getSourceRange();
  5545. } else if (IsAArch64Builtin && Fields.size() == 1) {
  5546. // If the register name is one of those that appear in the condition below
  5547. // and the special register builtin being used is one of the write builtins,
  5548. // then we require that the argument provided for writing to the register
  5549. // is an integer constant expression. This is because it will be lowered to
  5550. // an MSR (immediate) instruction, so we need to know the immediate at
  5551. // compile time.
  5552. if (TheCall->getNumArgs() != 2)
  5553. return false;
  5554. std::string RegLower = Reg.lower();
  5555. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  5556. RegLower != "pan" && RegLower != "uao")
  5557. return false;
  5558. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5559. }
  5560. return false;
  5561. }
  5562. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  5563. /// This checks that the target supports __builtin_longjmp and
  5564. /// that val is a constant 1.
  5565. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  5566. if (!Context.getTargetInfo().hasSjLjLowering())
  5567. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
  5568. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5569. Expr *Arg = TheCall->getArg(1);
  5570. llvm::APSInt Result;
  5571. // TODO: This is less than ideal. Overload this to take a value.
  5572. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5573. return true;
  5574. if (Result != 1)
  5575. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
  5576. << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
  5577. return false;
  5578. }
  5579. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  5580. /// This checks that the target supports __builtin_setjmp.
  5581. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  5582. if (!Context.getTargetInfo().hasSjLjLowering())
  5583. return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
  5584. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5585. return false;
  5586. }
  5587. namespace {
  5588. class UncoveredArgHandler {
  5589. enum { Unknown = -1, AllCovered = -2 };
  5590. signed FirstUncoveredArg = Unknown;
  5591. SmallVector<const Expr *, 4> DiagnosticExprs;
  5592. public:
  5593. UncoveredArgHandler() = default;
  5594. bool hasUncoveredArg() const {
  5595. return (FirstUncoveredArg >= 0);
  5596. }
  5597. unsigned getUncoveredArg() const {
  5598. assert(hasUncoveredArg() && "no uncovered argument");
  5599. return FirstUncoveredArg;
  5600. }
  5601. void setAllCovered() {
  5602. // A string has been found with all arguments covered, so clear out
  5603. // the diagnostics.
  5604. DiagnosticExprs.clear();
  5605. FirstUncoveredArg = AllCovered;
  5606. }
  5607. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  5608. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  5609. // Don't update if a previous string covers all arguments.
  5610. if (FirstUncoveredArg == AllCovered)
  5611. return;
  5612. // UncoveredArgHandler tracks the highest uncovered argument index
  5613. // and with it all the strings that match this index.
  5614. if (NewFirstUncoveredArg == FirstUncoveredArg)
  5615. DiagnosticExprs.push_back(StrExpr);
  5616. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  5617. DiagnosticExprs.clear();
  5618. DiagnosticExprs.push_back(StrExpr);
  5619. FirstUncoveredArg = NewFirstUncoveredArg;
  5620. }
  5621. }
  5622. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  5623. };
  5624. enum StringLiteralCheckType {
  5625. SLCT_NotALiteral,
  5626. SLCT_UncheckedLiteral,
  5627. SLCT_CheckedLiteral
  5628. };
  5629. } // namespace
  5630. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  5631. BinaryOperatorKind BinOpKind,
  5632. bool AddendIsRight) {
  5633. unsigned BitWidth = Offset.getBitWidth();
  5634. unsigned AddendBitWidth = Addend.getBitWidth();
  5635. // There might be negative interim results.
  5636. if (Addend.isUnsigned()) {
  5637. Addend = Addend.zext(++AddendBitWidth);
  5638. Addend.setIsSigned(true);
  5639. }
  5640. // Adjust the bit width of the APSInts.
  5641. if (AddendBitWidth > BitWidth) {
  5642. Offset = Offset.sext(AddendBitWidth);
  5643. BitWidth = AddendBitWidth;
  5644. } else if (BitWidth > AddendBitWidth) {
  5645. Addend = Addend.sext(BitWidth);
  5646. }
  5647. bool Ov = false;
  5648. llvm::APSInt ResOffset = Offset;
  5649. if (BinOpKind == BO_Add)
  5650. ResOffset = Offset.sadd_ov(Addend, Ov);
  5651. else {
  5652. assert(AddendIsRight && BinOpKind == BO_Sub &&
  5653. "operator must be add or sub with addend on the right");
  5654. ResOffset = Offset.ssub_ov(Addend, Ov);
  5655. }
  5656. // We add an offset to a pointer here so we should support an offset as big as
  5657. // possible.
  5658. if (Ov) {
  5659. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  5660. "index (intermediate) result too big");
  5661. Offset = Offset.sext(2 * BitWidth);
  5662. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  5663. return;
  5664. }
  5665. Offset = ResOffset;
  5666. }
  5667. namespace {
  5668. // This is a wrapper class around StringLiteral to support offsetted string
  5669. // literals as format strings. It takes the offset into account when returning
  5670. // the string and its length or the source locations to display notes correctly.
  5671. class FormatStringLiteral {
  5672. const StringLiteral *FExpr;
  5673. int64_t Offset;
  5674. public:
  5675. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  5676. : FExpr(fexpr), Offset(Offset) {}
  5677. StringRef getString() const {
  5678. return FExpr->getString().drop_front(Offset);
  5679. }
  5680. unsigned getByteLength() const {
  5681. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  5682. }
  5683. unsigned getLength() const { return FExpr->getLength() - Offset; }
  5684. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  5685. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  5686. QualType getType() const { return FExpr->getType(); }
  5687. bool isAscii() const { return FExpr->isAscii(); }
  5688. bool isWide() const { return FExpr->isWide(); }
  5689. bool isUTF8() const { return FExpr->isUTF8(); }
  5690. bool isUTF16() const { return FExpr->isUTF16(); }
  5691. bool isUTF32() const { return FExpr->isUTF32(); }
  5692. bool isPascal() const { return FExpr->isPascal(); }
  5693. SourceLocation getLocationOfByte(
  5694. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  5695. const TargetInfo &Target, unsigned *StartToken = nullptr,
  5696. unsigned *StartTokenByteOffset = nullptr) const {
  5697. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  5698. StartToken, StartTokenByteOffset);
  5699. }
  5700. SourceLocation getBeginLoc() const LLVM_READONLY {
  5701. return FExpr->getBeginLoc().getLocWithOffset(Offset);
  5702. }
  5703. SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
  5704. };
  5705. } // namespace
  5706. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  5707. const Expr *OrigFormatExpr,
  5708. ArrayRef<const Expr *> Args,
  5709. bool HasVAListArg, unsigned format_idx,
  5710. unsigned firstDataArg,
  5711. Sema::FormatStringType Type,
  5712. bool inFunctionCall,
  5713. Sema::VariadicCallType CallType,
  5714. llvm::SmallBitVector &CheckedVarArgs,
  5715. UncoveredArgHandler &UncoveredArg);
  5716. // Determine if an expression is a string literal or constant string.
  5717. // If this function returns false on the arguments to a function expecting a
  5718. // format string, we will usually need to emit a warning.
  5719. // True string literals are then checked by CheckFormatString.
  5720. static StringLiteralCheckType
  5721. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  5722. bool HasVAListArg, unsigned format_idx,
  5723. unsigned firstDataArg, Sema::FormatStringType Type,
  5724. Sema::VariadicCallType CallType, bool InFunctionCall,
  5725. llvm::SmallBitVector &CheckedVarArgs,
  5726. UncoveredArgHandler &UncoveredArg,
  5727. llvm::APSInt Offset) {
  5728. tryAgain:
  5729. assert(Offset.isSigned() && "invalid offset");
  5730. if (E->isTypeDependent() || E->isValueDependent())
  5731. return SLCT_NotALiteral;
  5732. E = E->IgnoreParenCasts();
  5733. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  5734. // Technically -Wformat-nonliteral does not warn about this case.
  5735. // The behavior of printf and friends in this case is implementation
  5736. // dependent. Ideally if the format string cannot be null then
  5737. // it should have a 'nonnull' attribute in the function prototype.
  5738. return SLCT_UncheckedLiteral;
  5739. switch (E->getStmtClass()) {
  5740. case Stmt::BinaryConditionalOperatorClass:
  5741. case Stmt::ConditionalOperatorClass: {
  5742. // The expression is a literal if both sub-expressions were, and it was
  5743. // completely checked only if both sub-expressions were checked.
  5744. const AbstractConditionalOperator *C =
  5745. cast<AbstractConditionalOperator>(E);
  5746. // Determine whether it is necessary to check both sub-expressions, for
  5747. // example, because the condition expression is a constant that can be
  5748. // evaluated at compile time.
  5749. bool CheckLeft = true, CheckRight = true;
  5750. bool Cond;
  5751. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
  5752. if (Cond)
  5753. CheckRight = false;
  5754. else
  5755. CheckLeft = false;
  5756. }
  5757. // We need to maintain the offsets for the right and the left hand side
  5758. // separately to check if every possible indexed expression is a valid
  5759. // string literal. They might have different offsets for different string
  5760. // literals in the end.
  5761. StringLiteralCheckType Left;
  5762. if (!CheckLeft)
  5763. Left = SLCT_UncheckedLiteral;
  5764. else {
  5765. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  5766. HasVAListArg, format_idx, firstDataArg,
  5767. Type, CallType, InFunctionCall,
  5768. CheckedVarArgs, UncoveredArg, Offset);
  5769. if (Left == SLCT_NotALiteral || !CheckRight) {
  5770. return Left;
  5771. }
  5772. }
  5773. StringLiteralCheckType Right =
  5774. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  5775. HasVAListArg, format_idx, firstDataArg,
  5776. Type, CallType, InFunctionCall, CheckedVarArgs,
  5777. UncoveredArg, Offset);
  5778. return (CheckLeft && Left < Right) ? Left : Right;
  5779. }
  5780. case Stmt::ImplicitCastExprClass:
  5781. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  5782. goto tryAgain;
  5783. case Stmt::OpaqueValueExprClass:
  5784. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  5785. E = src;
  5786. goto tryAgain;
  5787. }
  5788. return SLCT_NotALiteral;
  5789. case Stmt::PredefinedExprClass:
  5790. // While __func__, etc., are technically not string literals, they
  5791. // cannot contain format specifiers and thus are not a security
  5792. // liability.
  5793. return SLCT_UncheckedLiteral;
  5794. case Stmt::DeclRefExprClass: {
  5795. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  5796. // As an exception, do not flag errors for variables binding to
  5797. // const string literals.
  5798. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  5799. bool isConstant = false;
  5800. QualType T = DR->getType();
  5801. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  5802. isConstant = AT->getElementType().isConstant(S.Context);
  5803. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  5804. isConstant = T.isConstant(S.Context) &&
  5805. PT->getPointeeType().isConstant(S.Context);
  5806. } else if (T->isObjCObjectPointerType()) {
  5807. // In ObjC, there is usually no "const ObjectPointer" type,
  5808. // so don't check if the pointee type is constant.
  5809. isConstant = T.isConstant(S.Context);
  5810. }
  5811. if (isConstant) {
  5812. if (const Expr *Init = VD->getAnyInitializer()) {
  5813. // Look through initializers like const char c[] = { "foo" }
  5814. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  5815. if (InitList->isStringLiteralInit())
  5816. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  5817. }
  5818. return checkFormatStringExpr(S, Init, Args,
  5819. HasVAListArg, format_idx,
  5820. firstDataArg, Type, CallType,
  5821. /*InFunctionCall*/ false, CheckedVarArgs,
  5822. UncoveredArg, Offset);
  5823. }
  5824. }
  5825. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  5826. // special check to see if the format string is a function parameter
  5827. // of the function calling the printf function. If the function
  5828. // has an attribute indicating it is a printf-like function, then we
  5829. // should suppress warnings concerning non-literals being used in a call
  5830. // to a vprintf function. For example:
  5831. //
  5832. // void
  5833. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  5834. // va_list ap;
  5835. // va_start(ap, fmt);
  5836. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  5837. // ...
  5838. // }
  5839. if (HasVAListArg) {
  5840. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  5841. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  5842. int PVIndex = PV->getFunctionScopeIndex() + 1;
  5843. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  5844. // adjust for implicit parameter
  5845. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  5846. if (MD->isInstance())
  5847. ++PVIndex;
  5848. // We also check if the formats are compatible.
  5849. // We can't pass a 'scanf' string to a 'printf' function.
  5850. if (PVIndex == PVFormat->getFormatIdx() &&
  5851. Type == S.GetFormatStringType(PVFormat))
  5852. return SLCT_UncheckedLiteral;
  5853. }
  5854. }
  5855. }
  5856. }
  5857. }
  5858. return SLCT_NotALiteral;
  5859. }
  5860. case Stmt::CallExprClass:
  5861. case Stmt::CXXMemberCallExprClass: {
  5862. const CallExpr *CE = cast<CallExpr>(E);
  5863. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  5864. bool IsFirst = true;
  5865. StringLiteralCheckType CommonResult;
  5866. for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
  5867. const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
  5868. StringLiteralCheckType Result = checkFormatStringExpr(
  5869. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  5870. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  5871. if (IsFirst) {
  5872. CommonResult = Result;
  5873. IsFirst = false;
  5874. }
  5875. }
  5876. if (!IsFirst)
  5877. return CommonResult;
  5878. if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
  5879. unsigned BuiltinID = FD->getBuiltinID();
  5880. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  5881. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  5882. const Expr *Arg = CE->getArg(0);
  5883. return checkFormatStringExpr(S, Arg, Args,
  5884. HasVAListArg, format_idx,
  5885. firstDataArg, Type, CallType,
  5886. InFunctionCall, CheckedVarArgs,
  5887. UncoveredArg, Offset);
  5888. }
  5889. }
  5890. }
  5891. return SLCT_NotALiteral;
  5892. }
  5893. case Stmt::ObjCMessageExprClass: {
  5894. const auto *ME = cast<ObjCMessageExpr>(E);
  5895. if (const auto *ND = ME->getMethodDecl()) {
  5896. if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
  5897. const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
  5898. return checkFormatStringExpr(
  5899. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  5900. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  5901. }
  5902. }
  5903. return SLCT_NotALiteral;
  5904. }
  5905. case Stmt::ObjCStringLiteralClass:
  5906. case Stmt::StringLiteralClass: {
  5907. const StringLiteral *StrE = nullptr;
  5908. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  5909. StrE = ObjCFExpr->getString();
  5910. else
  5911. StrE = cast<StringLiteral>(E);
  5912. if (StrE) {
  5913. if (Offset.isNegative() || Offset > StrE->getLength()) {
  5914. // TODO: It would be better to have an explicit warning for out of
  5915. // bounds literals.
  5916. return SLCT_NotALiteral;
  5917. }
  5918. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  5919. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  5920. firstDataArg, Type, InFunctionCall, CallType,
  5921. CheckedVarArgs, UncoveredArg);
  5922. return SLCT_CheckedLiteral;
  5923. }
  5924. return SLCT_NotALiteral;
  5925. }
  5926. case Stmt::BinaryOperatorClass: {
  5927. llvm::APSInt LResult;
  5928. llvm::APSInt RResult;
  5929. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  5930. // A string literal + an int offset is still a string literal.
  5931. if (BinOp->isAdditiveOp()) {
  5932. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
  5933. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
  5934. if (LIsInt != RIsInt) {
  5935. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  5936. if (LIsInt) {
  5937. if (BinOpKind == BO_Add) {
  5938. sumOffsets(Offset, LResult, BinOpKind, RIsInt);
  5939. E = BinOp->getRHS();
  5940. goto tryAgain;
  5941. }
  5942. } else {
  5943. sumOffsets(Offset, RResult, BinOpKind, RIsInt);
  5944. E = BinOp->getLHS();
  5945. goto tryAgain;
  5946. }
  5947. }
  5948. }
  5949. return SLCT_NotALiteral;
  5950. }
  5951. case Stmt::UnaryOperatorClass: {
  5952. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  5953. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  5954. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  5955. llvm::APSInt IndexResult;
  5956. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
  5957. sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
  5958. E = ASE->getBase();
  5959. goto tryAgain;
  5960. }
  5961. }
  5962. return SLCT_NotALiteral;
  5963. }
  5964. default:
  5965. return SLCT_NotALiteral;
  5966. }
  5967. }
  5968. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  5969. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  5970. .Case("scanf", FST_Scanf)
  5971. .Cases("printf", "printf0", FST_Printf)
  5972. .Cases("NSString", "CFString", FST_NSString)
  5973. .Case("strftime", FST_Strftime)
  5974. .Case("strfmon", FST_Strfmon)
  5975. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  5976. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  5977. .Case("os_trace", FST_OSLog)
  5978. .Case("os_log", FST_OSLog)
  5979. .Default(FST_Unknown);
  5980. }
  5981. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  5982. /// functions) for correct use of format strings.
  5983. /// Returns true if a format string has been fully checked.
  5984. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  5985. ArrayRef<const Expr *> Args,
  5986. bool IsCXXMember,
  5987. VariadicCallType CallType,
  5988. SourceLocation Loc, SourceRange Range,
  5989. llvm::SmallBitVector &CheckedVarArgs) {
  5990. FormatStringInfo FSI;
  5991. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  5992. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  5993. FSI.FirstDataArg, GetFormatStringType(Format),
  5994. CallType, Loc, Range, CheckedVarArgs);
  5995. return false;
  5996. }
  5997. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  5998. bool HasVAListArg, unsigned format_idx,
  5999. unsigned firstDataArg, FormatStringType Type,
  6000. VariadicCallType CallType,
  6001. SourceLocation Loc, SourceRange Range,
  6002. llvm::SmallBitVector &CheckedVarArgs) {
  6003. // CHECK: printf/scanf-like function is called with no format string.
  6004. if (format_idx >= Args.size()) {
  6005. Diag(Loc, diag::warn_missing_format_string) << Range;
  6006. return false;
  6007. }
  6008. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  6009. // CHECK: format string is not a string literal.
  6010. //
  6011. // Dynamically generated format strings are difficult to
  6012. // automatically vet at compile time. Requiring that format strings
  6013. // are string literals: (1) permits the checking of format strings by
  6014. // the compiler and thereby (2) can practically remove the source of
  6015. // many format string exploits.
  6016. // Format string can be either ObjC string (e.g. @"%d") or
  6017. // C string (e.g. "%d")
  6018. // ObjC string uses the same format specifiers as C string, so we can use
  6019. // the same format string checking logic for both ObjC and C strings.
  6020. UncoveredArgHandler UncoveredArg;
  6021. StringLiteralCheckType CT =
  6022. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  6023. format_idx, firstDataArg, Type, CallType,
  6024. /*IsFunctionCall*/ true, CheckedVarArgs,
  6025. UncoveredArg,
  6026. /*no string offset*/ llvm::APSInt(64, false) = 0);
  6027. // Generate a diagnostic where an uncovered argument is detected.
  6028. if (UncoveredArg.hasUncoveredArg()) {
  6029. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  6030. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  6031. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  6032. }
  6033. if (CT != SLCT_NotALiteral)
  6034. // Literal format string found, check done!
  6035. return CT == SLCT_CheckedLiteral;
  6036. // Strftime is particular as it always uses a single 'time' argument,
  6037. // so it is safe to pass a non-literal string.
  6038. if (Type == FST_Strftime)
  6039. return false;
  6040. // Do not emit diag when the string param is a macro expansion and the
  6041. // format is either NSString or CFString. This is a hack to prevent
  6042. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  6043. // which are usually used in place of NS and CF string literals.
  6044. SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
  6045. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  6046. return false;
  6047. // If there are no arguments specified, warn with -Wformat-security, otherwise
  6048. // warn only with -Wformat-nonliteral.
  6049. if (Args.size() == firstDataArg) {
  6050. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  6051. << OrigFormatExpr->getSourceRange();
  6052. switch (Type) {
  6053. default:
  6054. break;
  6055. case FST_Kprintf:
  6056. case FST_FreeBSDKPrintf:
  6057. case FST_Printf:
  6058. Diag(FormatLoc, diag::note_format_security_fixit)
  6059. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  6060. break;
  6061. case FST_NSString:
  6062. Diag(FormatLoc, diag::note_format_security_fixit)
  6063. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  6064. break;
  6065. }
  6066. } else {
  6067. Diag(FormatLoc, diag::warn_format_nonliteral)
  6068. << OrigFormatExpr->getSourceRange();
  6069. }
  6070. return false;
  6071. }
  6072. namespace {
  6073. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  6074. protected:
  6075. Sema &S;
  6076. const FormatStringLiteral *FExpr;
  6077. const Expr *OrigFormatExpr;
  6078. const Sema::FormatStringType FSType;
  6079. const unsigned FirstDataArg;
  6080. const unsigned NumDataArgs;
  6081. const char *Beg; // Start of format string.
  6082. const bool HasVAListArg;
  6083. ArrayRef<const Expr *> Args;
  6084. unsigned FormatIdx;
  6085. llvm::SmallBitVector CoveredArgs;
  6086. bool usesPositionalArgs = false;
  6087. bool atFirstArg = true;
  6088. bool inFunctionCall;
  6089. Sema::VariadicCallType CallType;
  6090. llvm::SmallBitVector &CheckedVarArgs;
  6091. UncoveredArgHandler &UncoveredArg;
  6092. public:
  6093. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  6094. const Expr *origFormatExpr,
  6095. const Sema::FormatStringType type, unsigned firstDataArg,
  6096. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  6097. ArrayRef<const Expr *> Args, unsigned formatIdx,
  6098. bool inFunctionCall, Sema::VariadicCallType callType,
  6099. llvm::SmallBitVector &CheckedVarArgs,
  6100. UncoveredArgHandler &UncoveredArg)
  6101. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  6102. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  6103. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  6104. inFunctionCall(inFunctionCall), CallType(callType),
  6105. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  6106. CoveredArgs.resize(numDataArgs);
  6107. CoveredArgs.reset();
  6108. }
  6109. void DoneProcessing();
  6110. void HandleIncompleteSpecifier(const char *startSpecifier,
  6111. unsigned specifierLen) override;
  6112. void HandleInvalidLengthModifier(
  6113. const analyze_format_string::FormatSpecifier &FS,
  6114. const analyze_format_string::ConversionSpecifier &CS,
  6115. const char *startSpecifier, unsigned specifierLen,
  6116. unsigned DiagID);
  6117. void HandleNonStandardLengthModifier(
  6118. const analyze_format_string::FormatSpecifier &FS,
  6119. const char *startSpecifier, unsigned specifierLen);
  6120. void HandleNonStandardConversionSpecifier(
  6121. const analyze_format_string::ConversionSpecifier &CS,
  6122. const char *startSpecifier, unsigned specifierLen);
  6123. void HandlePosition(const char *startPos, unsigned posLen) override;
  6124. void HandleInvalidPosition(const char *startSpecifier,
  6125. unsigned specifierLen,
  6126. analyze_format_string::PositionContext p) override;
  6127. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  6128. void HandleNullChar(const char *nullCharacter) override;
  6129. template <typename Range>
  6130. static void
  6131. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  6132. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  6133. bool IsStringLocation, Range StringRange,
  6134. ArrayRef<FixItHint> Fixit = None);
  6135. protected:
  6136. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  6137. const char *startSpec,
  6138. unsigned specifierLen,
  6139. const char *csStart, unsigned csLen);
  6140. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6141. const char *startSpec,
  6142. unsigned specifierLen);
  6143. SourceRange getFormatStringRange();
  6144. CharSourceRange getSpecifierRange(const char *startSpecifier,
  6145. unsigned specifierLen);
  6146. SourceLocation getLocationOfByte(const char *x);
  6147. const Expr *getDataArg(unsigned i) const;
  6148. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  6149. const analyze_format_string::ConversionSpecifier &CS,
  6150. const char *startSpecifier, unsigned specifierLen,
  6151. unsigned argIndex);
  6152. template <typename Range>
  6153. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  6154. bool IsStringLocation, Range StringRange,
  6155. ArrayRef<FixItHint> Fixit = None);
  6156. };
  6157. } // namespace
  6158. SourceRange CheckFormatHandler::getFormatStringRange() {
  6159. return OrigFormatExpr->getSourceRange();
  6160. }
  6161. CharSourceRange CheckFormatHandler::
  6162. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  6163. SourceLocation Start = getLocationOfByte(startSpecifier);
  6164. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  6165. // Advance the end SourceLocation by one due to half-open ranges.
  6166. End = End.getLocWithOffset(1);
  6167. return CharSourceRange::getCharRange(Start, End);
  6168. }
  6169. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  6170. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  6171. S.getLangOpts(), S.Context.getTargetInfo());
  6172. }
  6173. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  6174. unsigned specifierLen){
  6175. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  6176. getLocationOfByte(startSpecifier),
  6177. /*IsStringLocation*/true,
  6178. getSpecifierRange(startSpecifier, specifierLen));
  6179. }
  6180. void CheckFormatHandler::HandleInvalidLengthModifier(
  6181. const analyze_format_string::FormatSpecifier &FS,
  6182. const analyze_format_string::ConversionSpecifier &CS,
  6183. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  6184. using namespace analyze_format_string;
  6185. const LengthModifier &LM = FS.getLengthModifier();
  6186. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6187. // See if we know how to fix this length modifier.
  6188. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6189. if (FixedLM) {
  6190. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6191. getLocationOfByte(LM.getStart()),
  6192. /*IsStringLocation*/true,
  6193. getSpecifierRange(startSpecifier, specifierLen));
  6194. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6195. << FixedLM->toString()
  6196. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6197. } else {
  6198. FixItHint Hint;
  6199. if (DiagID == diag::warn_format_nonsensical_length)
  6200. Hint = FixItHint::CreateRemoval(LMRange);
  6201. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6202. getLocationOfByte(LM.getStart()),
  6203. /*IsStringLocation*/true,
  6204. getSpecifierRange(startSpecifier, specifierLen),
  6205. Hint);
  6206. }
  6207. }
  6208. void CheckFormatHandler::HandleNonStandardLengthModifier(
  6209. const analyze_format_string::FormatSpecifier &FS,
  6210. const char *startSpecifier, unsigned specifierLen) {
  6211. using namespace analyze_format_string;
  6212. const LengthModifier &LM = FS.getLengthModifier();
  6213. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6214. // See if we know how to fix this length modifier.
  6215. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6216. if (FixedLM) {
  6217. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6218. << LM.toString() << 0,
  6219. getLocationOfByte(LM.getStart()),
  6220. /*IsStringLocation*/true,
  6221. getSpecifierRange(startSpecifier, specifierLen));
  6222. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6223. << FixedLM->toString()
  6224. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6225. } else {
  6226. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6227. << LM.toString() << 0,
  6228. getLocationOfByte(LM.getStart()),
  6229. /*IsStringLocation*/true,
  6230. getSpecifierRange(startSpecifier, specifierLen));
  6231. }
  6232. }
  6233. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  6234. const analyze_format_string::ConversionSpecifier &CS,
  6235. const char *startSpecifier, unsigned specifierLen) {
  6236. using namespace analyze_format_string;
  6237. // See if we know how to fix this conversion specifier.
  6238. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  6239. if (FixedCS) {
  6240. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6241. << CS.toString() << /*conversion specifier*/1,
  6242. getLocationOfByte(CS.getStart()),
  6243. /*IsStringLocation*/true,
  6244. getSpecifierRange(startSpecifier, specifierLen));
  6245. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  6246. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  6247. << FixedCS->toString()
  6248. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  6249. } else {
  6250. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6251. << CS.toString() << /*conversion specifier*/1,
  6252. getLocationOfByte(CS.getStart()),
  6253. /*IsStringLocation*/true,
  6254. getSpecifierRange(startSpecifier, specifierLen));
  6255. }
  6256. }
  6257. void CheckFormatHandler::HandlePosition(const char *startPos,
  6258. unsigned posLen) {
  6259. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  6260. getLocationOfByte(startPos),
  6261. /*IsStringLocation*/true,
  6262. getSpecifierRange(startPos, posLen));
  6263. }
  6264. void
  6265. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  6266. analyze_format_string::PositionContext p) {
  6267. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  6268. << (unsigned) p,
  6269. getLocationOfByte(startPos), /*IsStringLocation*/true,
  6270. getSpecifierRange(startPos, posLen));
  6271. }
  6272. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  6273. unsigned posLen) {
  6274. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  6275. getLocationOfByte(startPos),
  6276. /*IsStringLocation*/true,
  6277. getSpecifierRange(startPos, posLen));
  6278. }
  6279. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  6280. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  6281. // The presence of a null character is likely an error.
  6282. EmitFormatDiagnostic(
  6283. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  6284. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  6285. getFormatStringRange());
  6286. }
  6287. }
  6288. // Note that this may return NULL if there was an error parsing or building
  6289. // one of the argument expressions.
  6290. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  6291. return Args[FirstDataArg + i];
  6292. }
  6293. void CheckFormatHandler::DoneProcessing() {
  6294. // Does the number of data arguments exceed the number of
  6295. // format conversions in the format string?
  6296. if (!HasVAListArg) {
  6297. // Find any arguments that weren't covered.
  6298. CoveredArgs.flip();
  6299. signed notCoveredArg = CoveredArgs.find_first();
  6300. if (notCoveredArg >= 0) {
  6301. assert((unsigned)notCoveredArg < NumDataArgs);
  6302. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  6303. } else {
  6304. UncoveredArg.setAllCovered();
  6305. }
  6306. }
  6307. }
  6308. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  6309. const Expr *ArgExpr) {
  6310. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  6311. "Invalid state");
  6312. if (!ArgExpr)
  6313. return;
  6314. SourceLocation Loc = ArgExpr->getBeginLoc();
  6315. if (S.getSourceManager().isInSystemMacro(Loc))
  6316. return;
  6317. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  6318. for (auto E : DiagnosticExprs)
  6319. PDiag << E->getSourceRange();
  6320. CheckFormatHandler::EmitFormatDiagnostic(
  6321. S, IsFunctionCall, DiagnosticExprs[0],
  6322. PDiag, Loc, /*IsStringLocation*/false,
  6323. DiagnosticExprs[0]->getSourceRange());
  6324. }
  6325. bool
  6326. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  6327. SourceLocation Loc,
  6328. const char *startSpec,
  6329. unsigned specifierLen,
  6330. const char *csStart,
  6331. unsigned csLen) {
  6332. bool keepGoing = true;
  6333. if (argIndex < NumDataArgs) {
  6334. // Consider the argument coverered, even though the specifier doesn't
  6335. // make sense.
  6336. CoveredArgs.set(argIndex);
  6337. }
  6338. else {
  6339. // If argIndex exceeds the number of data arguments we
  6340. // don't issue a warning because that is just a cascade of warnings (and
  6341. // they may have intended '%%' anyway). We don't want to continue processing
  6342. // the format string after this point, however, as we will like just get
  6343. // gibberish when trying to match arguments.
  6344. keepGoing = false;
  6345. }
  6346. StringRef Specifier(csStart, csLen);
  6347. // If the specifier in non-printable, it could be the first byte of a UTF-8
  6348. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  6349. // hex value.
  6350. std::string CodePointStr;
  6351. if (!llvm::sys::locale::isPrint(*csStart)) {
  6352. llvm::UTF32 CodePoint;
  6353. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  6354. const llvm::UTF8 *E =
  6355. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  6356. llvm::ConversionResult Result =
  6357. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  6358. if (Result != llvm::conversionOK) {
  6359. unsigned char FirstChar = *csStart;
  6360. CodePoint = (llvm::UTF32)FirstChar;
  6361. }
  6362. llvm::raw_string_ostream OS(CodePointStr);
  6363. if (CodePoint < 256)
  6364. OS << "\\x" << llvm::format("%02x", CodePoint);
  6365. else if (CodePoint <= 0xFFFF)
  6366. OS << "\\u" << llvm::format("%04x", CodePoint);
  6367. else
  6368. OS << "\\U" << llvm::format("%08x", CodePoint);
  6369. OS.flush();
  6370. Specifier = CodePointStr;
  6371. }
  6372. EmitFormatDiagnostic(
  6373. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  6374. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  6375. return keepGoing;
  6376. }
  6377. void
  6378. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6379. const char *startSpec,
  6380. unsigned specifierLen) {
  6381. EmitFormatDiagnostic(
  6382. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  6383. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  6384. }
  6385. bool
  6386. CheckFormatHandler::CheckNumArgs(
  6387. const analyze_format_string::FormatSpecifier &FS,
  6388. const analyze_format_string::ConversionSpecifier &CS,
  6389. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  6390. if (argIndex >= NumDataArgs) {
  6391. PartialDiagnostic PDiag = FS.usesPositionalArg()
  6392. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  6393. << (argIndex+1) << NumDataArgs)
  6394. : S.PDiag(diag::warn_printf_insufficient_data_args);
  6395. EmitFormatDiagnostic(
  6396. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  6397. getSpecifierRange(startSpecifier, specifierLen));
  6398. // Since more arguments than conversion tokens are given, by extension
  6399. // all arguments are covered, so mark this as so.
  6400. UncoveredArg.setAllCovered();
  6401. return false;
  6402. }
  6403. return true;
  6404. }
  6405. template<typename Range>
  6406. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  6407. SourceLocation Loc,
  6408. bool IsStringLocation,
  6409. Range StringRange,
  6410. ArrayRef<FixItHint> FixIt) {
  6411. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  6412. Loc, IsStringLocation, StringRange, FixIt);
  6413. }
  6414. /// If the format string is not within the function call, emit a note
  6415. /// so that the function call and string are in diagnostic messages.
  6416. ///
  6417. /// \param InFunctionCall if true, the format string is within the function
  6418. /// call and only one diagnostic message will be produced. Otherwise, an
  6419. /// extra note will be emitted pointing to location of the format string.
  6420. ///
  6421. /// \param ArgumentExpr the expression that is passed as the format string
  6422. /// argument in the function call. Used for getting locations when two
  6423. /// diagnostics are emitted.
  6424. ///
  6425. /// \param PDiag the callee should already have provided any strings for the
  6426. /// diagnostic message. This function only adds locations and fixits
  6427. /// to diagnostics.
  6428. ///
  6429. /// \param Loc primary location for diagnostic. If two diagnostics are
  6430. /// required, one will be at Loc and a new SourceLocation will be created for
  6431. /// the other one.
  6432. ///
  6433. /// \param IsStringLocation if true, Loc points to the format string should be
  6434. /// used for the note. Otherwise, Loc points to the argument list and will
  6435. /// be used with PDiag.
  6436. ///
  6437. /// \param StringRange some or all of the string to highlight. This is
  6438. /// templated so it can accept either a CharSourceRange or a SourceRange.
  6439. ///
  6440. /// \param FixIt optional fix it hint for the format string.
  6441. template <typename Range>
  6442. void CheckFormatHandler::EmitFormatDiagnostic(
  6443. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  6444. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  6445. Range StringRange, ArrayRef<FixItHint> FixIt) {
  6446. if (InFunctionCall) {
  6447. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  6448. D << StringRange;
  6449. D << FixIt;
  6450. } else {
  6451. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  6452. << ArgumentExpr->getSourceRange();
  6453. const Sema::SemaDiagnosticBuilder &Note =
  6454. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  6455. diag::note_format_string_defined);
  6456. Note << StringRange;
  6457. Note << FixIt;
  6458. }
  6459. }
  6460. //===--- CHECK: Printf format string checking ------------------------------===//
  6461. namespace {
  6462. class CheckPrintfHandler : public CheckFormatHandler {
  6463. public:
  6464. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  6465. const Expr *origFormatExpr,
  6466. const Sema::FormatStringType type, unsigned firstDataArg,
  6467. unsigned numDataArgs, bool isObjC, const char *beg,
  6468. bool hasVAListArg, ArrayRef<const Expr *> Args,
  6469. unsigned formatIdx, bool inFunctionCall,
  6470. Sema::VariadicCallType CallType,
  6471. llvm::SmallBitVector &CheckedVarArgs,
  6472. UncoveredArgHandler &UncoveredArg)
  6473. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  6474. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  6475. inFunctionCall, CallType, CheckedVarArgs,
  6476. UncoveredArg) {}
  6477. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  6478. /// Returns true if '%@' specifiers are allowed in the format string.
  6479. bool allowsObjCArg() const {
  6480. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  6481. FSType == Sema::FST_OSTrace;
  6482. }
  6483. bool HandleInvalidPrintfConversionSpecifier(
  6484. const analyze_printf::PrintfSpecifier &FS,
  6485. const char *startSpecifier,
  6486. unsigned specifierLen) override;
  6487. void handleInvalidMaskType(StringRef MaskType) override;
  6488. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  6489. const char *startSpecifier,
  6490. unsigned specifierLen) override;
  6491. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  6492. const char *StartSpecifier,
  6493. unsigned SpecifierLen,
  6494. const Expr *E);
  6495. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  6496. const char *startSpecifier, unsigned specifierLen);
  6497. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  6498. const analyze_printf::OptionalAmount &Amt,
  6499. unsigned type,
  6500. const char *startSpecifier, unsigned specifierLen);
  6501. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6502. const analyze_printf::OptionalFlag &flag,
  6503. const char *startSpecifier, unsigned specifierLen);
  6504. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  6505. const analyze_printf::OptionalFlag &ignoredFlag,
  6506. const analyze_printf::OptionalFlag &flag,
  6507. const char *startSpecifier, unsigned specifierLen);
  6508. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  6509. const Expr *E);
  6510. void HandleEmptyObjCModifierFlag(const char *startFlag,
  6511. unsigned flagLen) override;
  6512. void HandleInvalidObjCModifierFlag(const char *startFlag,
  6513. unsigned flagLen) override;
  6514. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  6515. const char *flagsEnd,
  6516. const char *conversionPosition)
  6517. override;
  6518. };
  6519. } // namespace
  6520. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  6521. const analyze_printf::PrintfSpecifier &FS,
  6522. const char *startSpecifier,
  6523. unsigned specifierLen) {
  6524. const analyze_printf::PrintfConversionSpecifier &CS =
  6525. FS.getConversionSpecifier();
  6526. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  6527. getLocationOfByte(CS.getStart()),
  6528. startSpecifier, specifierLen,
  6529. CS.getStart(), CS.getLength());
  6530. }
  6531. void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
  6532. S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
  6533. }
  6534. bool CheckPrintfHandler::HandleAmount(
  6535. const analyze_format_string::OptionalAmount &Amt,
  6536. unsigned k, const char *startSpecifier,
  6537. unsigned specifierLen) {
  6538. if (Amt.hasDataArgument()) {
  6539. if (!HasVAListArg) {
  6540. unsigned argIndex = Amt.getArgIndex();
  6541. if (argIndex >= NumDataArgs) {
  6542. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  6543. << k,
  6544. getLocationOfByte(Amt.getStart()),
  6545. /*IsStringLocation*/true,
  6546. getSpecifierRange(startSpecifier, specifierLen));
  6547. // Don't do any more checking. We will just emit
  6548. // spurious errors.
  6549. return false;
  6550. }
  6551. // Type check the data argument. It should be an 'int'.
  6552. // Although not in conformance with C99, we also allow the argument to be
  6553. // an 'unsigned int' as that is a reasonably safe case. GCC also
  6554. // doesn't emit a warning for that case.
  6555. CoveredArgs.set(argIndex);
  6556. const Expr *Arg = getDataArg(argIndex);
  6557. if (!Arg)
  6558. return false;
  6559. QualType T = Arg->getType();
  6560. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  6561. assert(AT.isValid());
  6562. if (!AT.matchesType(S.Context, T)) {
  6563. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  6564. << k << AT.getRepresentativeTypeName(S.Context)
  6565. << T << Arg->getSourceRange(),
  6566. getLocationOfByte(Amt.getStart()),
  6567. /*IsStringLocation*/true,
  6568. getSpecifierRange(startSpecifier, specifierLen));
  6569. // Don't do any more checking. We will just emit
  6570. // spurious errors.
  6571. return false;
  6572. }
  6573. }
  6574. }
  6575. return true;
  6576. }
  6577. void CheckPrintfHandler::HandleInvalidAmount(
  6578. const analyze_printf::PrintfSpecifier &FS,
  6579. const analyze_printf::OptionalAmount &Amt,
  6580. unsigned type,
  6581. const char *startSpecifier,
  6582. unsigned specifierLen) {
  6583. const analyze_printf::PrintfConversionSpecifier &CS =
  6584. FS.getConversionSpecifier();
  6585. FixItHint fixit =
  6586. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  6587. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  6588. Amt.getConstantLength()))
  6589. : FixItHint();
  6590. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  6591. << type << CS.toString(),
  6592. getLocationOfByte(Amt.getStart()),
  6593. /*IsStringLocation*/true,
  6594. getSpecifierRange(startSpecifier, specifierLen),
  6595. fixit);
  6596. }
  6597. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6598. const analyze_printf::OptionalFlag &flag,
  6599. const char *startSpecifier,
  6600. unsigned specifierLen) {
  6601. // Warn about pointless flag with a fixit removal.
  6602. const analyze_printf::PrintfConversionSpecifier &CS =
  6603. FS.getConversionSpecifier();
  6604. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  6605. << flag.toString() << CS.toString(),
  6606. getLocationOfByte(flag.getPosition()),
  6607. /*IsStringLocation*/true,
  6608. getSpecifierRange(startSpecifier, specifierLen),
  6609. FixItHint::CreateRemoval(
  6610. getSpecifierRange(flag.getPosition(), 1)));
  6611. }
  6612. void CheckPrintfHandler::HandleIgnoredFlag(
  6613. const analyze_printf::PrintfSpecifier &FS,
  6614. const analyze_printf::OptionalFlag &ignoredFlag,
  6615. const analyze_printf::OptionalFlag &flag,
  6616. const char *startSpecifier,
  6617. unsigned specifierLen) {
  6618. // Warn about ignored flag with a fixit removal.
  6619. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  6620. << ignoredFlag.toString() << flag.toString(),
  6621. getLocationOfByte(ignoredFlag.getPosition()),
  6622. /*IsStringLocation*/true,
  6623. getSpecifierRange(startSpecifier, specifierLen),
  6624. FixItHint::CreateRemoval(
  6625. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  6626. }
  6627. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  6628. unsigned flagLen) {
  6629. // Warn about an empty flag.
  6630. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  6631. getLocationOfByte(startFlag),
  6632. /*IsStringLocation*/true,
  6633. getSpecifierRange(startFlag, flagLen));
  6634. }
  6635. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  6636. unsigned flagLen) {
  6637. // Warn about an invalid flag.
  6638. auto Range = getSpecifierRange(startFlag, flagLen);
  6639. StringRef flag(startFlag, flagLen);
  6640. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  6641. getLocationOfByte(startFlag),
  6642. /*IsStringLocation*/true,
  6643. Range, FixItHint::CreateRemoval(Range));
  6644. }
  6645. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  6646. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  6647. // Warn about using '[...]' without a '@' conversion.
  6648. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  6649. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  6650. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  6651. getLocationOfByte(conversionPosition),
  6652. /*IsStringLocation*/true,
  6653. Range, FixItHint::CreateRemoval(Range));
  6654. }
  6655. // Determines if the specified is a C++ class or struct containing
  6656. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  6657. // "c_str()").
  6658. template<typename MemberKind>
  6659. static llvm::SmallPtrSet<MemberKind*, 1>
  6660. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  6661. const RecordType *RT = Ty->getAs<RecordType>();
  6662. llvm::SmallPtrSet<MemberKind*, 1> Results;
  6663. if (!RT)
  6664. return Results;
  6665. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  6666. if (!RD || !RD->getDefinition())
  6667. return Results;
  6668. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  6669. Sema::LookupMemberName);
  6670. R.suppressDiagnostics();
  6671. // We just need to include all members of the right kind turned up by the
  6672. // filter, at this point.
  6673. if (S.LookupQualifiedName(R, RT->getDecl()))
  6674. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  6675. NamedDecl *decl = (*I)->getUnderlyingDecl();
  6676. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  6677. Results.insert(FK);
  6678. }
  6679. return Results;
  6680. }
  6681. /// Check if we could call '.c_str()' on an object.
  6682. ///
  6683. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  6684. /// allow the call, or if it would be ambiguous).
  6685. bool Sema::hasCStrMethod(const Expr *E) {
  6686. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6687. MethodSet Results =
  6688. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  6689. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6690. MI != ME; ++MI)
  6691. if ((*MI)->getMinRequiredArguments() == 0)
  6692. return true;
  6693. return false;
  6694. }
  6695. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  6696. // better diagnostic if so. AT is assumed to be valid.
  6697. // Returns true when a c_str() conversion method is found.
  6698. bool CheckPrintfHandler::checkForCStrMembers(
  6699. const analyze_printf::ArgType &AT, const Expr *E) {
  6700. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6701. MethodSet Results =
  6702. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  6703. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6704. MI != ME; ++MI) {
  6705. const CXXMethodDecl *Method = *MI;
  6706. if (Method->getMinRequiredArguments() == 0 &&
  6707. AT.matchesType(S.Context, Method->getReturnType())) {
  6708. // FIXME: Suggest parens if the expression needs them.
  6709. SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
  6710. S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
  6711. << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  6712. return true;
  6713. }
  6714. }
  6715. return false;
  6716. }
  6717. bool
  6718. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  6719. &FS,
  6720. const char *startSpecifier,
  6721. unsigned specifierLen) {
  6722. using namespace analyze_format_string;
  6723. using namespace analyze_printf;
  6724. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  6725. if (FS.consumesDataArgument()) {
  6726. if (atFirstArg) {
  6727. atFirstArg = false;
  6728. usesPositionalArgs = FS.usesPositionalArg();
  6729. }
  6730. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  6731. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  6732. startSpecifier, specifierLen);
  6733. return false;
  6734. }
  6735. }
  6736. // First check if the field width, precision, and conversion specifier
  6737. // have matching data arguments.
  6738. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  6739. startSpecifier, specifierLen)) {
  6740. return false;
  6741. }
  6742. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  6743. startSpecifier, specifierLen)) {
  6744. return false;
  6745. }
  6746. if (!CS.consumesDataArgument()) {
  6747. // FIXME: Technically specifying a precision or field width here
  6748. // makes no sense. Worth issuing a warning at some point.
  6749. return true;
  6750. }
  6751. // Consume the argument.
  6752. unsigned argIndex = FS.getArgIndex();
  6753. if (argIndex < NumDataArgs) {
  6754. // The check to see if the argIndex is valid will come later.
  6755. // We set the bit here because we may exit early from this
  6756. // function if we encounter some other error.
  6757. CoveredArgs.set(argIndex);
  6758. }
  6759. // FreeBSD kernel extensions.
  6760. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  6761. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  6762. // We need at least two arguments.
  6763. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  6764. return false;
  6765. // Claim the second argument.
  6766. CoveredArgs.set(argIndex + 1);
  6767. // Type check the first argument (int for %b, pointer for %D)
  6768. const Expr *Ex = getDataArg(argIndex);
  6769. const analyze_printf::ArgType &AT =
  6770. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  6771. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  6772. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  6773. EmitFormatDiagnostic(
  6774. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  6775. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  6776. << false << Ex->getSourceRange(),
  6777. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  6778. getSpecifierRange(startSpecifier, specifierLen));
  6779. // Type check the second argument (char * for both %b and %D)
  6780. Ex = getDataArg(argIndex + 1);
  6781. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  6782. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  6783. EmitFormatDiagnostic(
  6784. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  6785. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  6786. << false << Ex->getSourceRange(),
  6787. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  6788. getSpecifierRange(startSpecifier, specifierLen));
  6789. return true;
  6790. }
  6791. // Check for using an Objective-C specific conversion specifier
  6792. // in a non-ObjC literal.
  6793. if (!allowsObjCArg() && CS.isObjCArg()) {
  6794. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  6795. specifierLen);
  6796. }
  6797. // %P can only be used with os_log.
  6798. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  6799. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  6800. specifierLen);
  6801. }
  6802. // %n is not allowed with os_log.
  6803. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  6804. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  6805. getLocationOfByte(CS.getStart()),
  6806. /*IsStringLocation*/ false,
  6807. getSpecifierRange(startSpecifier, specifierLen));
  6808. return true;
  6809. }
  6810. // Only scalars are allowed for os_trace.
  6811. if (FSType == Sema::FST_OSTrace &&
  6812. (CS.getKind() == ConversionSpecifier::PArg ||
  6813. CS.getKind() == ConversionSpecifier::sArg ||
  6814. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  6815. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  6816. specifierLen);
  6817. }
  6818. // Check for use of public/private annotation outside of os_log().
  6819. if (FSType != Sema::FST_OSLog) {
  6820. if (FS.isPublic().isSet()) {
  6821. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  6822. << "public",
  6823. getLocationOfByte(FS.isPublic().getPosition()),
  6824. /*IsStringLocation*/ false,
  6825. getSpecifierRange(startSpecifier, specifierLen));
  6826. }
  6827. if (FS.isPrivate().isSet()) {
  6828. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  6829. << "private",
  6830. getLocationOfByte(FS.isPrivate().getPosition()),
  6831. /*IsStringLocation*/ false,
  6832. getSpecifierRange(startSpecifier, specifierLen));
  6833. }
  6834. }
  6835. // Check for invalid use of field width
  6836. if (!FS.hasValidFieldWidth()) {
  6837. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  6838. startSpecifier, specifierLen);
  6839. }
  6840. // Check for invalid use of precision
  6841. if (!FS.hasValidPrecision()) {
  6842. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  6843. startSpecifier, specifierLen);
  6844. }
  6845. // Precision is mandatory for %P specifier.
  6846. if (CS.getKind() == ConversionSpecifier::PArg &&
  6847. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  6848. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  6849. getLocationOfByte(startSpecifier),
  6850. /*IsStringLocation*/ false,
  6851. getSpecifierRange(startSpecifier, specifierLen));
  6852. }
  6853. // Check each flag does not conflict with any other component.
  6854. if (!FS.hasValidThousandsGroupingPrefix())
  6855. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  6856. if (!FS.hasValidLeadingZeros())
  6857. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  6858. if (!FS.hasValidPlusPrefix())
  6859. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  6860. if (!FS.hasValidSpacePrefix())
  6861. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  6862. if (!FS.hasValidAlternativeForm())
  6863. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  6864. if (!FS.hasValidLeftJustified())
  6865. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  6866. // Check that flags are not ignored by another flag
  6867. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  6868. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  6869. startSpecifier, specifierLen);
  6870. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  6871. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  6872. startSpecifier, specifierLen);
  6873. // Check the length modifier is valid with the given conversion specifier.
  6874. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  6875. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  6876. diag::warn_format_nonsensical_length);
  6877. else if (!FS.hasStandardLengthModifier())
  6878. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  6879. else if (!FS.hasStandardLengthConversionCombination())
  6880. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  6881. diag::warn_format_non_standard_conversion_spec);
  6882. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  6883. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  6884. // The remaining checks depend on the data arguments.
  6885. if (HasVAListArg)
  6886. return true;
  6887. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  6888. return false;
  6889. const Expr *Arg = getDataArg(argIndex);
  6890. if (!Arg)
  6891. return true;
  6892. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  6893. }
  6894. static bool requiresParensToAddCast(const Expr *E) {
  6895. // FIXME: We should have a general way to reason about operator
  6896. // precedence and whether parens are actually needed here.
  6897. // Take care of a few common cases where they aren't.
  6898. const Expr *Inside = E->IgnoreImpCasts();
  6899. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  6900. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  6901. switch (Inside->getStmtClass()) {
  6902. case Stmt::ArraySubscriptExprClass:
  6903. case Stmt::CallExprClass:
  6904. case Stmt::CharacterLiteralClass:
  6905. case Stmt::CXXBoolLiteralExprClass:
  6906. case Stmt::DeclRefExprClass:
  6907. case Stmt::FloatingLiteralClass:
  6908. case Stmt::IntegerLiteralClass:
  6909. case Stmt::MemberExprClass:
  6910. case Stmt::ObjCArrayLiteralClass:
  6911. case Stmt::ObjCBoolLiteralExprClass:
  6912. case Stmt::ObjCBoxedExprClass:
  6913. case Stmt::ObjCDictionaryLiteralClass:
  6914. case Stmt::ObjCEncodeExprClass:
  6915. case Stmt::ObjCIvarRefExprClass:
  6916. case Stmt::ObjCMessageExprClass:
  6917. case Stmt::ObjCPropertyRefExprClass:
  6918. case Stmt::ObjCStringLiteralClass:
  6919. case Stmt::ObjCSubscriptRefExprClass:
  6920. case Stmt::ParenExprClass:
  6921. case Stmt::StringLiteralClass:
  6922. case Stmt::UnaryOperatorClass:
  6923. return false;
  6924. default:
  6925. return true;
  6926. }
  6927. }
  6928. static std::pair<QualType, StringRef>
  6929. shouldNotPrintDirectly(const ASTContext &Context,
  6930. QualType IntendedTy,
  6931. const Expr *E) {
  6932. // Use a 'while' to peel off layers of typedefs.
  6933. QualType TyTy = IntendedTy;
  6934. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  6935. StringRef Name = UserTy->getDecl()->getName();
  6936. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  6937. .Case("CFIndex", Context.getNSIntegerType())
  6938. .Case("NSInteger", Context.getNSIntegerType())
  6939. .Case("NSUInteger", Context.getNSUIntegerType())
  6940. .Case("SInt32", Context.IntTy)
  6941. .Case("UInt32", Context.UnsignedIntTy)
  6942. .Default(QualType());
  6943. if (!CastTy.isNull())
  6944. return std::make_pair(CastTy, Name);
  6945. TyTy = UserTy->desugar();
  6946. }
  6947. // Strip parens if necessary.
  6948. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  6949. return shouldNotPrintDirectly(Context,
  6950. PE->getSubExpr()->getType(),
  6951. PE->getSubExpr());
  6952. // If this is a conditional expression, then its result type is constructed
  6953. // via usual arithmetic conversions and thus there might be no necessary
  6954. // typedef sugar there. Recurse to operands to check for NSInteger &
  6955. // Co. usage condition.
  6956. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  6957. QualType TrueTy, FalseTy;
  6958. StringRef TrueName, FalseName;
  6959. std::tie(TrueTy, TrueName) =
  6960. shouldNotPrintDirectly(Context,
  6961. CO->getTrueExpr()->getType(),
  6962. CO->getTrueExpr());
  6963. std::tie(FalseTy, FalseName) =
  6964. shouldNotPrintDirectly(Context,
  6965. CO->getFalseExpr()->getType(),
  6966. CO->getFalseExpr());
  6967. if (TrueTy == FalseTy)
  6968. return std::make_pair(TrueTy, TrueName);
  6969. else if (TrueTy.isNull())
  6970. return std::make_pair(FalseTy, FalseName);
  6971. else if (FalseTy.isNull())
  6972. return std::make_pair(TrueTy, TrueName);
  6973. }
  6974. return std::make_pair(QualType(), StringRef());
  6975. }
  6976. bool
  6977. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  6978. const char *StartSpecifier,
  6979. unsigned SpecifierLen,
  6980. const Expr *E) {
  6981. using namespace analyze_format_string;
  6982. using namespace analyze_printf;
  6983. // Now type check the data expression that matches the
  6984. // format specifier.
  6985. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  6986. if (!AT.isValid())
  6987. return true;
  6988. QualType ExprTy = E->getType();
  6989. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  6990. ExprTy = TET->getUnderlyingExpr()->getType();
  6991. }
  6992. const analyze_printf::ArgType::MatchKind Match =
  6993. AT.matchesType(S.Context, ExprTy);
  6994. bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
  6995. if (Match == analyze_printf::ArgType::Match)
  6996. return true;
  6997. // Look through argument promotions for our error message's reported type.
  6998. // This includes the integral and floating promotions, but excludes array
  6999. // and function pointer decay; seeing that an argument intended to be a
  7000. // string has type 'char [6]' is probably more confusing than 'char *'.
  7001. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  7002. if (ICE->getCastKind() == CK_IntegralCast ||
  7003. ICE->getCastKind() == CK_FloatingCast) {
  7004. E = ICE->getSubExpr();
  7005. ExprTy = E->getType();
  7006. // Check if we didn't match because of an implicit cast from a 'char'
  7007. // or 'short' to an 'int'. This is done because printf is a varargs
  7008. // function.
  7009. if (ICE->getType() == S.Context.IntTy ||
  7010. ICE->getType() == S.Context.UnsignedIntTy) {
  7011. // All further checking is done on the subexpression.
  7012. if (AT.matchesType(S.Context, ExprTy))
  7013. return true;
  7014. }
  7015. }
  7016. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  7017. // Special case for 'a', which has type 'int' in C.
  7018. // Note, however, that we do /not/ want to treat multibyte constants like
  7019. // 'MooV' as characters! This form is deprecated but still exists.
  7020. if (ExprTy == S.Context.IntTy)
  7021. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  7022. ExprTy = S.Context.CharTy;
  7023. }
  7024. // Look through enums to their underlying type.
  7025. bool IsEnum = false;
  7026. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  7027. ExprTy = EnumTy->getDecl()->getIntegerType();
  7028. IsEnum = true;
  7029. }
  7030. // %C in an Objective-C context prints a unichar, not a wchar_t.
  7031. // If the argument is an integer of some kind, believe the %C and suggest
  7032. // a cast instead of changing the conversion specifier.
  7033. QualType IntendedTy = ExprTy;
  7034. if (isObjCContext() &&
  7035. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  7036. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  7037. !ExprTy->isCharType()) {
  7038. // 'unichar' is defined as a typedef of unsigned short, but we should
  7039. // prefer using the typedef if it is visible.
  7040. IntendedTy = S.Context.UnsignedShortTy;
  7041. // While we are here, check if the value is an IntegerLiteral that happens
  7042. // to be within the valid range.
  7043. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  7044. const llvm::APInt &V = IL->getValue();
  7045. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  7046. return true;
  7047. }
  7048. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
  7049. Sema::LookupOrdinaryName);
  7050. if (S.LookupName(Result, S.getCurScope())) {
  7051. NamedDecl *ND = Result.getFoundDecl();
  7052. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  7053. if (TD->getUnderlyingType() == IntendedTy)
  7054. IntendedTy = S.Context.getTypedefType(TD);
  7055. }
  7056. }
  7057. }
  7058. // Special-case some of Darwin's platform-independence types by suggesting
  7059. // casts to primitive types that are known to be large enough.
  7060. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  7061. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  7062. QualType CastTy;
  7063. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  7064. if (!CastTy.isNull()) {
  7065. // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
  7066. // (long in ASTContext). Only complain to pedants.
  7067. if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
  7068. (AT.isSizeT() || AT.isPtrdiffT()) &&
  7069. AT.matchesType(S.Context, CastTy))
  7070. Pedantic = true;
  7071. IntendedTy = CastTy;
  7072. ShouldNotPrintDirectly = true;
  7073. }
  7074. }
  7075. // We may be able to offer a FixItHint if it is a supported type.
  7076. PrintfSpecifier fixedFS = FS;
  7077. bool Success =
  7078. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  7079. if (Success) {
  7080. // Get the fix string from the fixed format specifier
  7081. SmallString<16> buf;
  7082. llvm::raw_svector_ostream os(buf);
  7083. fixedFS.toString(os);
  7084. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  7085. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  7086. unsigned Diag =
  7087. Pedantic
  7088. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7089. : diag::warn_format_conversion_argument_type_mismatch;
  7090. // In this case, the specifier is wrong and should be changed to match
  7091. // the argument.
  7092. EmitFormatDiagnostic(S.PDiag(Diag)
  7093. << AT.getRepresentativeTypeName(S.Context)
  7094. << IntendedTy << IsEnum << E->getSourceRange(),
  7095. E->getBeginLoc(),
  7096. /*IsStringLocation*/ false, SpecRange,
  7097. FixItHint::CreateReplacement(SpecRange, os.str()));
  7098. } else {
  7099. // The canonical type for formatting this value is different from the
  7100. // actual type of the expression. (This occurs, for example, with Darwin's
  7101. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  7102. // should be printed as 'long' for 64-bit compatibility.)
  7103. // Rather than emitting a normal format/argument mismatch, we want to
  7104. // add a cast to the recommended type (and correct the format string
  7105. // if necessary).
  7106. SmallString<16> CastBuf;
  7107. llvm::raw_svector_ostream CastFix(CastBuf);
  7108. CastFix << "(";
  7109. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  7110. CastFix << ")";
  7111. SmallVector<FixItHint,4> Hints;
  7112. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  7113. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  7114. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  7115. // If there's already a cast present, just replace it.
  7116. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  7117. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  7118. } else if (!requiresParensToAddCast(E)) {
  7119. // If the expression has high enough precedence,
  7120. // just write the C-style cast.
  7121. Hints.push_back(
  7122. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7123. } else {
  7124. // Otherwise, add parens around the expression as well as the cast.
  7125. CastFix << "(";
  7126. Hints.push_back(
  7127. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7128. SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
  7129. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  7130. }
  7131. if (ShouldNotPrintDirectly) {
  7132. // The expression has a type that should not be printed directly.
  7133. // We extract the name from the typedef because we don't want to show
  7134. // the underlying type in the diagnostic.
  7135. StringRef Name;
  7136. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  7137. Name = TypedefTy->getDecl()->getName();
  7138. else
  7139. Name = CastTyName;
  7140. unsigned Diag = Pedantic
  7141. ? diag::warn_format_argument_needs_cast_pedantic
  7142. : diag::warn_format_argument_needs_cast;
  7143. EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
  7144. << E->getSourceRange(),
  7145. E->getBeginLoc(), /*IsStringLocation=*/false,
  7146. SpecRange, Hints);
  7147. } else {
  7148. // In this case, the expression could be printed using a different
  7149. // specifier, but we've decided that the specifier is probably correct
  7150. // and we should cast instead. Just use the normal warning message.
  7151. EmitFormatDiagnostic(
  7152. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7153. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  7154. << E->getSourceRange(),
  7155. E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
  7156. }
  7157. }
  7158. } else {
  7159. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  7160. SpecifierLen);
  7161. // Since the warning for passing non-POD types to variadic functions
  7162. // was deferred until now, we emit a warning for non-POD
  7163. // arguments here.
  7164. switch (S.isValidVarArgType(ExprTy)) {
  7165. case Sema::VAK_Valid:
  7166. case Sema::VAK_ValidInCXX11: {
  7167. unsigned Diag =
  7168. Pedantic
  7169. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7170. : diag::warn_format_conversion_argument_type_mismatch;
  7171. EmitFormatDiagnostic(
  7172. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  7173. << IsEnum << CSR << E->getSourceRange(),
  7174. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7175. break;
  7176. }
  7177. case Sema::VAK_Undefined:
  7178. case Sema::VAK_MSVCUndefined:
  7179. EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  7180. << S.getLangOpts().CPlusPlus11 << ExprTy
  7181. << CallType
  7182. << AT.getRepresentativeTypeName(S.Context) << CSR
  7183. << E->getSourceRange(),
  7184. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7185. checkForCStrMembers(AT, E);
  7186. break;
  7187. case Sema::VAK_Invalid:
  7188. if (ExprTy->isObjCObjectType())
  7189. EmitFormatDiagnostic(
  7190. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  7191. << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
  7192. << AT.getRepresentativeTypeName(S.Context) << CSR
  7193. << E->getSourceRange(),
  7194. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7195. else
  7196. // FIXME: If this is an initializer list, suggest removing the braces
  7197. // or inserting a cast to the target type.
  7198. S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
  7199. << isa<InitListExpr>(E) << ExprTy << CallType
  7200. << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
  7201. break;
  7202. }
  7203. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  7204. "format string specifier index out of range");
  7205. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  7206. }
  7207. return true;
  7208. }
  7209. //===--- CHECK: Scanf format string checking ------------------------------===//
  7210. namespace {
  7211. class CheckScanfHandler : public CheckFormatHandler {
  7212. public:
  7213. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  7214. const Expr *origFormatExpr, Sema::FormatStringType type,
  7215. unsigned firstDataArg, unsigned numDataArgs,
  7216. const char *beg, bool hasVAListArg,
  7217. ArrayRef<const Expr *> Args, unsigned formatIdx,
  7218. bool inFunctionCall, Sema::VariadicCallType CallType,
  7219. llvm::SmallBitVector &CheckedVarArgs,
  7220. UncoveredArgHandler &UncoveredArg)
  7221. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  7222. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  7223. inFunctionCall, CallType, CheckedVarArgs,
  7224. UncoveredArg) {}
  7225. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  7226. const char *startSpecifier,
  7227. unsigned specifierLen) override;
  7228. bool HandleInvalidScanfConversionSpecifier(
  7229. const analyze_scanf::ScanfSpecifier &FS,
  7230. const char *startSpecifier,
  7231. unsigned specifierLen) override;
  7232. void HandleIncompleteScanList(const char *start, const char *end) override;
  7233. };
  7234. } // namespace
  7235. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  7236. const char *end) {
  7237. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  7238. getLocationOfByte(end), /*IsStringLocation*/true,
  7239. getSpecifierRange(start, end - start));
  7240. }
  7241. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  7242. const analyze_scanf::ScanfSpecifier &FS,
  7243. const char *startSpecifier,
  7244. unsigned specifierLen) {
  7245. const analyze_scanf::ScanfConversionSpecifier &CS =
  7246. FS.getConversionSpecifier();
  7247. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  7248. getLocationOfByte(CS.getStart()),
  7249. startSpecifier, specifierLen,
  7250. CS.getStart(), CS.getLength());
  7251. }
  7252. bool CheckScanfHandler::HandleScanfSpecifier(
  7253. const analyze_scanf::ScanfSpecifier &FS,
  7254. const char *startSpecifier,
  7255. unsigned specifierLen) {
  7256. using namespace analyze_scanf;
  7257. using namespace analyze_format_string;
  7258. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  7259. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  7260. // be used to decide if we are using positional arguments consistently.
  7261. if (FS.consumesDataArgument()) {
  7262. if (atFirstArg) {
  7263. atFirstArg = false;
  7264. usesPositionalArgs = FS.usesPositionalArg();
  7265. }
  7266. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7267. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7268. startSpecifier, specifierLen);
  7269. return false;
  7270. }
  7271. }
  7272. // Check if the field with is non-zero.
  7273. const OptionalAmount &Amt = FS.getFieldWidth();
  7274. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  7275. if (Amt.getConstantAmount() == 0) {
  7276. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  7277. Amt.getConstantLength());
  7278. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  7279. getLocationOfByte(Amt.getStart()),
  7280. /*IsStringLocation*/true, R,
  7281. FixItHint::CreateRemoval(R));
  7282. }
  7283. }
  7284. if (!FS.consumesDataArgument()) {
  7285. // FIXME: Technically specifying a precision or field width here
  7286. // makes no sense. Worth issuing a warning at some point.
  7287. return true;
  7288. }
  7289. // Consume the argument.
  7290. unsigned argIndex = FS.getArgIndex();
  7291. if (argIndex < NumDataArgs) {
  7292. // The check to see if the argIndex is valid will come later.
  7293. // We set the bit here because we may exit early from this
  7294. // function if we encounter some other error.
  7295. CoveredArgs.set(argIndex);
  7296. }
  7297. // Check the length modifier is valid with the given conversion specifier.
  7298. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  7299. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7300. diag::warn_format_nonsensical_length);
  7301. else if (!FS.hasStandardLengthModifier())
  7302. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7303. else if (!FS.hasStandardLengthConversionCombination())
  7304. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7305. diag::warn_format_non_standard_conversion_spec);
  7306. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7307. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7308. // The remaining checks depend on the data arguments.
  7309. if (HasVAListArg)
  7310. return true;
  7311. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7312. return false;
  7313. // Check that the argument type matches the format specifier.
  7314. const Expr *Ex = getDataArg(argIndex);
  7315. if (!Ex)
  7316. return true;
  7317. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  7318. if (!AT.isValid()) {
  7319. return true;
  7320. }
  7321. analyze_format_string::ArgType::MatchKind Match =
  7322. AT.matchesType(S.Context, Ex->getType());
  7323. bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
  7324. if (Match == analyze_format_string::ArgType::Match)
  7325. return true;
  7326. ScanfSpecifier fixedFS = FS;
  7327. bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  7328. S.getLangOpts(), S.Context);
  7329. unsigned Diag =
  7330. Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7331. : diag::warn_format_conversion_argument_type_mismatch;
  7332. if (Success) {
  7333. // Get the fix string from the fixed format specifier.
  7334. SmallString<128> buf;
  7335. llvm::raw_svector_ostream os(buf);
  7336. fixedFS.toString(os);
  7337. EmitFormatDiagnostic(
  7338. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
  7339. << Ex->getType() << false << Ex->getSourceRange(),
  7340. Ex->getBeginLoc(),
  7341. /*IsStringLocation*/ false,
  7342. getSpecifierRange(startSpecifier, specifierLen),
  7343. FixItHint::CreateReplacement(
  7344. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  7345. } else {
  7346. EmitFormatDiagnostic(S.PDiag(Diag)
  7347. << AT.getRepresentativeTypeName(S.Context)
  7348. << Ex->getType() << false << Ex->getSourceRange(),
  7349. Ex->getBeginLoc(),
  7350. /*IsStringLocation*/ false,
  7351. getSpecifierRange(startSpecifier, specifierLen));
  7352. }
  7353. return true;
  7354. }
  7355. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  7356. const Expr *OrigFormatExpr,
  7357. ArrayRef<const Expr *> Args,
  7358. bool HasVAListArg, unsigned format_idx,
  7359. unsigned firstDataArg,
  7360. Sema::FormatStringType Type,
  7361. bool inFunctionCall,
  7362. Sema::VariadicCallType CallType,
  7363. llvm::SmallBitVector &CheckedVarArgs,
  7364. UncoveredArgHandler &UncoveredArg) {
  7365. // CHECK: is the format string a wide literal?
  7366. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  7367. CheckFormatHandler::EmitFormatDiagnostic(
  7368. S, inFunctionCall, Args[format_idx],
  7369. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
  7370. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7371. return;
  7372. }
  7373. // Str - The format string. NOTE: this is NOT null-terminated!
  7374. StringRef StrRef = FExpr->getString();
  7375. const char *Str = StrRef.data();
  7376. // Account for cases where the string literal is truncated in a declaration.
  7377. const ConstantArrayType *T =
  7378. S.Context.getAsConstantArrayType(FExpr->getType());
  7379. assert(T && "String literal not of constant array type!");
  7380. size_t TypeSize = T->getSize().getZExtValue();
  7381. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7382. const unsigned numDataArgs = Args.size() - firstDataArg;
  7383. // Emit a warning if the string literal is truncated and does not contain an
  7384. // embedded null character.
  7385. if (TypeSize <= StrRef.size() &&
  7386. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  7387. CheckFormatHandler::EmitFormatDiagnostic(
  7388. S, inFunctionCall, Args[format_idx],
  7389. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  7390. FExpr->getBeginLoc(),
  7391. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  7392. return;
  7393. }
  7394. // CHECK: empty format string?
  7395. if (StrLen == 0 && numDataArgs > 0) {
  7396. CheckFormatHandler::EmitFormatDiagnostic(
  7397. S, inFunctionCall, Args[format_idx],
  7398. S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
  7399. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7400. return;
  7401. }
  7402. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  7403. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  7404. Type == Sema::FST_OSTrace) {
  7405. CheckPrintfHandler H(
  7406. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  7407. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  7408. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  7409. CheckedVarArgs, UncoveredArg);
  7410. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  7411. S.getLangOpts(),
  7412. S.Context.getTargetInfo(),
  7413. Type == Sema::FST_FreeBSDKPrintf))
  7414. H.DoneProcessing();
  7415. } else if (Type == Sema::FST_Scanf) {
  7416. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  7417. numDataArgs, Str, HasVAListArg, Args, format_idx,
  7418. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  7419. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  7420. S.getLangOpts(),
  7421. S.Context.getTargetInfo()))
  7422. H.DoneProcessing();
  7423. } // TODO: handle other formats
  7424. }
  7425. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  7426. // Str - The format string. NOTE: this is NOT null-terminated!
  7427. StringRef StrRef = FExpr->getString();
  7428. const char *Str = StrRef.data();
  7429. // Account for cases where the string literal is truncated in a declaration.
  7430. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  7431. assert(T && "String literal not of constant array type!");
  7432. size_t TypeSize = T->getSize().getZExtValue();
  7433. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7434. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  7435. getLangOpts(),
  7436. Context.getTargetInfo());
  7437. }
  7438. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  7439. // Returns the related absolute value function that is larger, of 0 if one
  7440. // does not exist.
  7441. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  7442. switch (AbsFunction) {
  7443. default:
  7444. return 0;
  7445. case Builtin::BI__builtin_abs:
  7446. return Builtin::BI__builtin_labs;
  7447. case Builtin::BI__builtin_labs:
  7448. return Builtin::BI__builtin_llabs;
  7449. case Builtin::BI__builtin_llabs:
  7450. return 0;
  7451. case Builtin::BI__builtin_fabsf:
  7452. return Builtin::BI__builtin_fabs;
  7453. case Builtin::BI__builtin_fabs:
  7454. return Builtin::BI__builtin_fabsl;
  7455. case Builtin::BI__builtin_fabsl:
  7456. return 0;
  7457. case Builtin::BI__builtin_cabsf:
  7458. return Builtin::BI__builtin_cabs;
  7459. case Builtin::BI__builtin_cabs:
  7460. return Builtin::BI__builtin_cabsl;
  7461. case Builtin::BI__builtin_cabsl:
  7462. return 0;
  7463. case Builtin::BIabs:
  7464. return Builtin::BIlabs;
  7465. case Builtin::BIlabs:
  7466. return Builtin::BIllabs;
  7467. case Builtin::BIllabs:
  7468. return 0;
  7469. case Builtin::BIfabsf:
  7470. return Builtin::BIfabs;
  7471. case Builtin::BIfabs:
  7472. return Builtin::BIfabsl;
  7473. case Builtin::BIfabsl:
  7474. return 0;
  7475. case Builtin::BIcabsf:
  7476. return Builtin::BIcabs;
  7477. case Builtin::BIcabs:
  7478. return Builtin::BIcabsl;
  7479. case Builtin::BIcabsl:
  7480. return 0;
  7481. }
  7482. }
  7483. // Returns the argument type of the absolute value function.
  7484. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  7485. unsigned AbsType) {
  7486. if (AbsType == 0)
  7487. return QualType();
  7488. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  7489. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  7490. if (Error != ASTContext::GE_None)
  7491. return QualType();
  7492. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  7493. if (!FT)
  7494. return QualType();
  7495. if (FT->getNumParams() != 1)
  7496. return QualType();
  7497. return FT->getParamType(0);
  7498. }
  7499. // Returns the best absolute value function, or zero, based on type and
  7500. // current absolute value function.
  7501. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  7502. unsigned AbsFunctionKind) {
  7503. unsigned BestKind = 0;
  7504. uint64_t ArgSize = Context.getTypeSize(ArgType);
  7505. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  7506. Kind = getLargerAbsoluteValueFunction(Kind)) {
  7507. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  7508. if (Context.getTypeSize(ParamType) >= ArgSize) {
  7509. if (BestKind == 0)
  7510. BestKind = Kind;
  7511. else if (Context.hasSameType(ParamType, ArgType)) {
  7512. BestKind = Kind;
  7513. break;
  7514. }
  7515. }
  7516. }
  7517. return BestKind;
  7518. }
  7519. enum AbsoluteValueKind {
  7520. AVK_Integer,
  7521. AVK_Floating,
  7522. AVK_Complex
  7523. };
  7524. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  7525. if (T->isIntegralOrEnumerationType())
  7526. return AVK_Integer;
  7527. if (T->isRealFloatingType())
  7528. return AVK_Floating;
  7529. if (T->isAnyComplexType())
  7530. return AVK_Complex;
  7531. llvm_unreachable("Type not integer, floating, or complex");
  7532. }
  7533. // Changes the absolute value function to a different type. Preserves whether
  7534. // the function is a builtin.
  7535. static unsigned changeAbsFunction(unsigned AbsKind,
  7536. AbsoluteValueKind ValueKind) {
  7537. switch (ValueKind) {
  7538. case AVK_Integer:
  7539. switch (AbsKind) {
  7540. default:
  7541. return 0;
  7542. case Builtin::BI__builtin_fabsf:
  7543. case Builtin::BI__builtin_fabs:
  7544. case Builtin::BI__builtin_fabsl:
  7545. case Builtin::BI__builtin_cabsf:
  7546. case Builtin::BI__builtin_cabs:
  7547. case Builtin::BI__builtin_cabsl:
  7548. return Builtin::BI__builtin_abs;
  7549. case Builtin::BIfabsf:
  7550. case Builtin::BIfabs:
  7551. case Builtin::BIfabsl:
  7552. case Builtin::BIcabsf:
  7553. case Builtin::BIcabs:
  7554. case Builtin::BIcabsl:
  7555. return Builtin::BIabs;
  7556. }
  7557. case AVK_Floating:
  7558. switch (AbsKind) {
  7559. default:
  7560. return 0;
  7561. case Builtin::BI__builtin_abs:
  7562. case Builtin::BI__builtin_labs:
  7563. case Builtin::BI__builtin_llabs:
  7564. case Builtin::BI__builtin_cabsf:
  7565. case Builtin::BI__builtin_cabs:
  7566. case Builtin::BI__builtin_cabsl:
  7567. return Builtin::BI__builtin_fabsf;
  7568. case Builtin::BIabs:
  7569. case Builtin::BIlabs:
  7570. case Builtin::BIllabs:
  7571. case Builtin::BIcabsf:
  7572. case Builtin::BIcabs:
  7573. case Builtin::BIcabsl:
  7574. return Builtin::BIfabsf;
  7575. }
  7576. case AVK_Complex:
  7577. switch (AbsKind) {
  7578. default:
  7579. return 0;
  7580. case Builtin::BI__builtin_abs:
  7581. case Builtin::BI__builtin_labs:
  7582. case Builtin::BI__builtin_llabs:
  7583. case Builtin::BI__builtin_fabsf:
  7584. case Builtin::BI__builtin_fabs:
  7585. case Builtin::BI__builtin_fabsl:
  7586. return Builtin::BI__builtin_cabsf;
  7587. case Builtin::BIabs:
  7588. case Builtin::BIlabs:
  7589. case Builtin::BIllabs:
  7590. case Builtin::BIfabsf:
  7591. case Builtin::BIfabs:
  7592. case Builtin::BIfabsl:
  7593. return Builtin::BIcabsf;
  7594. }
  7595. }
  7596. llvm_unreachable("Unable to convert function");
  7597. }
  7598. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  7599. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  7600. if (!FnInfo)
  7601. return 0;
  7602. switch (FDecl->getBuiltinID()) {
  7603. default:
  7604. return 0;
  7605. case Builtin::BI__builtin_abs:
  7606. case Builtin::BI__builtin_fabs:
  7607. case Builtin::BI__builtin_fabsf:
  7608. case Builtin::BI__builtin_fabsl:
  7609. case Builtin::BI__builtin_labs:
  7610. case Builtin::BI__builtin_llabs:
  7611. case Builtin::BI__builtin_cabs:
  7612. case Builtin::BI__builtin_cabsf:
  7613. case Builtin::BI__builtin_cabsl:
  7614. case Builtin::BIabs:
  7615. case Builtin::BIlabs:
  7616. case Builtin::BIllabs:
  7617. case Builtin::BIfabs:
  7618. case Builtin::BIfabsf:
  7619. case Builtin::BIfabsl:
  7620. case Builtin::BIcabs:
  7621. case Builtin::BIcabsf:
  7622. case Builtin::BIcabsl:
  7623. return FDecl->getBuiltinID();
  7624. }
  7625. llvm_unreachable("Unknown Builtin type");
  7626. }
  7627. // If the replacement is valid, emit a note with replacement function.
  7628. // Additionally, suggest including the proper header if not already included.
  7629. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  7630. unsigned AbsKind, QualType ArgType) {
  7631. bool EmitHeaderHint = true;
  7632. const char *HeaderName = nullptr;
  7633. const char *FunctionName = nullptr;
  7634. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  7635. FunctionName = "std::abs";
  7636. if (ArgType->isIntegralOrEnumerationType()) {
  7637. HeaderName = "cstdlib";
  7638. } else if (ArgType->isRealFloatingType()) {
  7639. HeaderName = "cmath";
  7640. } else {
  7641. llvm_unreachable("Invalid Type");
  7642. }
  7643. // Lookup all std::abs
  7644. if (NamespaceDecl *Std = S.getStdNamespace()) {
  7645. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  7646. R.suppressDiagnostics();
  7647. S.LookupQualifiedName(R, Std);
  7648. for (const auto *I : R) {
  7649. const FunctionDecl *FDecl = nullptr;
  7650. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  7651. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  7652. } else {
  7653. FDecl = dyn_cast<FunctionDecl>(I);
  7654. }
  7655. if (!FDecl)
  7656. continue;
  7657. // Found std::abs(), check that they are the right ones.
  7658. if (FDecl->getNumParams() != 1)
  7659. continue;
  7660. // Check that the parameter type can handle the argument.
  7661. QualType ParamType = FDecl->getParamDecl(0)->getType();
  7662. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  7663. S.Context.getTypeSize(ArgType) <=
  7664. S.Context.getTypeSize(ParamType)) {
  7665. // Found a function, don't need the header hint.
  7666. EmitHeaderHint = false;
  7667. break;
  7668. }
  7669. }
  7670. }
  7671. } else {
  7672. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  7673. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  7674. if (HeaderName) {
  7675. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  7676. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  7677. R.suppressDiagnostics();
  7678. S.LookupName(R, S.getCurScope());
  7679. if (R.isSingleResult()) {
  7680. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  7681. if (FD && FD->getBuiltinID() == AbsKind) {
  7682. EmitHeaderHint = false;
  7683. } else {
  7684. return;
  7685. }
  7686. } else if (!R.empty()) {
  7687. return;
  7688. }
  7689. }
  7690. }
  7691. S.Diag(Loc, diag::note_replace_abs_function)
  7692. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  7693. if (!HeaderName)
  7694. return;
  7695. if (!EmitHeaderHint)
  7696. return;
  7697. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  7698. << FunctionName;
  7699. }
  7700. template <std::size_t StrLen>
  7701. static bool IsStdFunction(const FunctionDecl *FDecl,
  7702. const char (&Str)[StrLen]) {
  7703. if (!FDecl)
  7704. return false;
  7705. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  7706. return false;
  7707. if (!FDecl->isInStdNamespace())
  7708. return false;
  7709. return true;
  7710. }
  7711. // Warn when using the wrong abs() function.
  7712. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  7713. const FunctionDecl *FDecl) {
  7714. if (Call->getNumArgs() != 1)
  7715. return;
  7716. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  7717. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  7718. if (AbsKind == 0 && !IsStdAbs)
  7719. return;
  7720. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  7721. QualType ParamType = Call->getArg(0)->getType();
  7722. // Unsigned types cannot be negative. Suggest removing the absolute value
  7723. // function call.
  7724. if (ArgType->isUnsignedIntegerType()) {
  7725. const char *FunctionName =
  7726. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  7727. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  7728. Diag(Call->getExprLoc(), diag::note_remove_abs)
  7729. << FunctionName
  7730. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  7731. return;
  7732. }
  7733. // Taking the absolute value of a pointer is very suspicious, they probably
  7734. // wanted to index into an array, dereference a pointer, call a function, etc.
  7735. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  7736. unsigned DiagType = 0;
  7737. if (ArgType->isFunctionType())
  7738. DiagType = 1;
  7739. else if (ArgType->isArrayType())
  7740. DiagType = 2;
  7741. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  7742. return;
  7743. }
  7744. // std::abs has overloads which prevent most of the absolute value problems
  7745. // from occurring.
  7746. if (IsStdAbs)
  7747. return;
  7748. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  7749. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  7750. // The argument and parameter are the same kind. Check if they are the right
  7751. // size.
  7752. if (ArgValueKind == ParamValueKind) {
  7753. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  7754. return;
  7755. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  7756. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  7757. << FDecl << ArgType << ParamType;
  7758. if (NewAbsKind == 0)
  7759. return;
  7760. emitReplacement(*this, Call->getExprLoc(),
  7761. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  7762. return;
  7763. }
  7764. // ArgValueKind != ParamValueKind
  7765. // The wrong type of absolute value function was used. Attempt to find the
  7766. // proper one.
  7767. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  7768. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  7769. if (NewAbsKind == 0)
  7770. return;
  7771. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  7772. << FDecl << ParamValueKind << ArgValueKind;
  7773. emitReplacement(*this, Call->getExprLoc(),
  7774. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  7775. }
  7776. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  7777. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  7778. const FunctionDecl *FDecl) {
  7779. if (!Call || !FDecl) return;
  7780. // Ignore template specializations and macros.
  7781. if (inTemplateInstantiation()) return;
  7782. if (Call->getExprLoc().isMacroID()) return;
  7783. // Only care about the one template argument, two function parameter std::max
  7784. if (Call->getNumArgs() != 2) return;
  7785. if (!IsStdFunction(FDecl, "max")) return;
  7786. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  7787. if (!ArgList) return;
  7788. if (ArgList->size() != 1) return;
  7789. // Check that template type argument is unsigned integer.
  7790. const auto& TA = ArgList->get(0);
  7791. if (TA.getKind() != TemplateArgument::Type) return;
  7792. QualType ArgType = TA.getAsType();
  7793. if (!ArgType->isUnsignedIntegerType()) return;
  7794. // See if either argument is a literal zero.
  7795. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  7796. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  7797. if (!MTE) return false;
  7798. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  7799. if (!Num) return false;
  7800. if (Num->getValue() != 0) return false;
  7801. return true;
  7802. };
  7803. const Expr *FirstArg = Call->getArg(0);
  7804. const Expr *SecondArg = Call->getArg(1);
  7805. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  7806. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  7807. // Only warn when exactly one argument is zero.
  7808. if (IsFirstArgZero == IsSecondArgZero) return;
  7809. SourceRange FirstRange = FirstArg->getSourceRange();
  7810. SourceRange SecondRange = SecondArg->getSourceRange();
  7811. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  7812. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  7813. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  7814. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  7815. SourceRange RemovalRange;
  7816. if (IsFirstArgZero) {
  7817. RemovalRange = SourceRange(FirstRange.getBegin(),
  7818. SecondRange.getBegin().getLocWithOffset(-1));
  7819. } else {
  7820. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  7821. SecondRange.getEnd());
  7822. }
  7823. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  7824. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  7825. << FixItHint::CreateRemoval(RemovalRange);
  7826. }
  7827. //===--- CHECK: Standard memory functions ---------------------------------===//
  7828. /// Takes the expression passed to the size_t parameter of functions
  7829. /// such as memcmp, strncat, etc and warns if it's a comparison.
  7830. ///
  7831. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  7832. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  7833. IdentifierInfo *FnName,
  7834. SourceLocation FnLoc,
  7835. SourceLocation RParenLoc) {
  7836. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  7837. if (!Size)
  7838. return false;
  7839. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  7840. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  7841. return false;
  7842. SourceRange SizeRange = Size->getSourceRange();
  7843. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  7844. << SizeRange << FnName;
  7845. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  7846. << FnName
  7847. << FixItHint::CreateInsertion(
  7848. S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
  7849. << FixItHint::CreateRemoval(RParenLoc);
  7850. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  7851. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  7852. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  7853. ")");
  7854. return true;
  7855. }
  7856. /// Determine whether the given type is or contains a dynamic class type
  7857. /// (e.g., whether it has a vtable).
  7858. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  7859. bool &IsContained) {
  7860. // Look through array types while ignoring qualifiers.
  7861. const Type *Ty = T->getBaseElementTypeUnsafe();
  7862. IsContained = false;
  7863. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  7864. RD = RD ? RD->getDefinition() : nullptr;
  7865. if (!RD || RD->isInvalidDecl())
  7866. return nullptr;
  7867. if (RD->isDynamicClass())
  7868. return RD;
  7869. // Check all the fields. If any bases were dynamic, the class is dynamic.
  7870. // It's impossible for a class to transitively contain itself by value, so
  7871. // infinite recursion is impossible.
  7872. for (auto *FD : RD->fields()) {
  7873. bool SubContained;
  7874. if (const CXXRecordDecl *ContainedRD =
  7875. getContainedDynamicClass(FD->getType(), SubContained)) {
  7876. IsContained = true;
  7877. return ContainedRD;
  7878. }
  7879. }
  7880. return nullptr;
  7881. }
  7882. static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
  7883. if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  7884. if (Unary->getKind() == UETT_SizeOf)
  7885. return Unary;
  7886. return nullptr;
  7887. }
  7888. /// If E is a sizeof expression, returns its argument expression,
  7889. /// otherwise returns NULL.
  7890. static const Expr *getSizeOfExprArg(const Expr *E) {
  7891. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  7892. if (!SizeOf->isArgumentType())
  7893. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  7894. return nullptr;
  7895. }
  7896. /// If E is a sizeof expression, returns its argument type.
  7897. static QualType getSizeOfArgType(const Expr *E) {
  7898. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  7899. return SizeOf->getTypeOfArgument();
  7900. return QualType();
  7901. }
  7902. namespace {
  7903. struct SearchNonTrivialToInitializeField
  7904. : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
  7905. using Super =
  7906. DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
  7907. SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
  7908. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
  7909. SourceLocation SL) {
  7910. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  7911. asDerived().visitArray(PDIK, AT, SL);
  7912. return;
  7913. }
  7914. Super::visitWithKind(PDIK, FT, SL);
  7915. }
  7916. void visitARCStrong(QualType FT, SourceLocation SL) {
  7917. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  7918. }
  7919. void visitARCWeak(QualType FT, SourceLocation SL) {
  7920. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  7921. }
  7922. void visitStruct(QualType FT, SourceLocation SL) {
  7923. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  7924. visit(FD->getType(), FD->getLocation());
  7925. }
  7926. void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
  7927. const ArrayType *AT, SourceLocation SL) {
  7928. visit(getContext().getBaseElementType(AT), SL);
  7929. }
  7930. void visitTrivial(QualType FT, SourceLocation SL) {}
  7931. static void diag(QualType RT, const Expr *E, Sema &S) {
  7932. SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
  7933. }
  7934. ASTContext &getContext() { return S.getASTContext(); }
  7935. const Expr *E;
  7936. Sema &S;
  7937. };
  7938. struct SearchNonTrivialToCopyField
  7939. : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
  7940. using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
  7941. SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
  7942. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
  7943. SourceLocation SL) {
  7944. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  7945. asDerived().visitArray(PCK, AT, SL);
  7946. return;
  7947. }
  7948. Super::visitWithKind(PCK, FT, SL);
  7949. }
  7950. void visitARCStrong(QualType FT, SourceLocation SL) {
  7951. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  7952. }
  7953. void visitARCWeak(QualType FT, SourceLocation SL) {
  7954. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  7955. }
  7956. void visitStruct(QualType FT, SourceLocation SL) {
  7957. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  7958. visit(FD->getType(), FD->getLocation());
  7959. }
  7960. void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
  7961. SourceLocation SL) {
  7962. visit(getContext().getBaseElementType(AT), SL);
  7963. }
  7964. void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
  7965. SourceLocation SL) {}
  7966. void visitTrivial(QualType FT, SourceLocation SL) {}
  7967. void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
  7968. static void diag(QualType RT, const Expr *E, Sema &S) {
  7969. SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
  7970. }
  7971. ASTContext &getContext() { return S.getASTContext(); }
  7972. const Expr *E;
  7973. Sema &S;
  7974. };
  7975. }
  7976. /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
  7977. static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
  7978. SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
  7979. if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
  7980. if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
  7981. return false;
  7982. return doesExprLikelyComputeSize(BO->getLHS()) ||
  7983. doesExprLikelyComputeSize(BO->getRHS());
  7984. }
  7985. return getAsSizeOfExpr(SizeofExpr) != nullptr;
  7986. }
  7987. /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
  7988. ///
  7989. /// \code
  7990. /// #define MACRO 0
  7991. /// foo(MACRO);
  7992. /// foo(0);
  7993. /// \endcode
  7994. ///
  7995. /// This should return true for the first call to foo, but not for the second
  7996. /// (regardless of whether foo is a macro or function).
  7997. static bool isArgumentExpandedFromMacro(SourceManager &SM,
  7998. SourceLocation CallLoc,
  7999. SourceLocation ArgLoc) {
  8000. if (!CallLoc.isMacroID())
  8001. return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
  8002. return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
  8003. SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
  8004. }
  8005. /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
  8006. /// last two arguments transposed.
  8007. static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
  8008. if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
  8009. return;
  8010. const Expr *SizeArg =
  8011. Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
  8012. auto isLiteralZero = [](const Expr *E) {
  8013. return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
  8014. };
  8015. // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
  8016. SourceLocation CallLoc = Call->getRParenLoc();
  8017. SourceManager &SM = S.getSourceManager();
  8018. if (isLiteralZero(SizeArg) &&
  8019. !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
  8020. SourceLocation DiagLoc = SizeArg->getExprLoc();
  8021. // Some platforms #define bzero to __builtin_memset. See if this is the
  8022. // case, and if so, emit a better diagnostic.
  8023. if (BId == Builtin::BIbzero ||
  8024. (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
  8025. CallLoc, SM, S.getLangOpts()) == "bzero")) {
  8026. S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
  8027. S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
  8028. } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
  8029. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
  8030. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
  8031. }
  8032. return;
  8033. }
  8034. // If the second argument to a memset is a sizeof expression and the third
  8035. // isn't, this is also likely an error. This should catch
  8036. // 'memset(buf, sizeof(buf), 0xff)'.
  8037. if (BId == Builtin::BImemset &&
  8038. doesExprLikelyComputeSize(Call->getArg(1)) &&
  8039. !doesExprLikelyComputeSize(Call->getArg(2))) {
  8040. SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
  8041. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
  8042. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
  8043. return;
  8044. }
  8045. }
  8046. /// Check for dangerous or invalid arguments to memset().
  8047. ///
  8048. /// This issues warnings on known problematic, dangerous or unspecified
  8049. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  8050. /// function calls.
  8051. ///
  8052. /// \param Call The call expression to diagnose.
  8053. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  8054. unsigned BId,
  8055. IdentifierInfo *FnName) {
  8056. assert(BId != 0);
  8057. // It is possible to have a non-standard definition of memset. Validate
  8058. // we have enough arguments, and if not, abort further checking.
  8059. unsigned ExpectedNumArgs =
  8060. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  8061. if (Call->getNumArgs() < ExpectedNumArgs)
  8062. return;
  8063. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  8064. BId == Builtin::BIstrndup ? 1 : 2);
  8065. unsigned LenArg =
  8066. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  8067. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  8068. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  8069. Call->getBeginLoc(), Call->getRParenLoc()))
  8070. return;
  8071. // Catch cases like 'memset(buf, sizeof(buf), 0)'.
  8072. CheckMemaccessSize(*this, BId, Call);
  8073. // We have special checking when the length is a sizeof expression.
  8074. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  8075. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  8076. llvm::FoldingSetNodeID SizeOfArgID;
  8077. // Although widely used, 'bzero' is not a standard function. Be more strict
  8078. // with the argument types before allowing diagnostics and only allow the
  8079. // form bzero(ptr, sizeof(...)).
  8080. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8081. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  8082. return;
  8083. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  8084. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  8085. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  8086. QualType DestTy = Dest->getType();
  8087. QualType PointeeTy;
  8088. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  8089. PointeeTy = DestPtrTy->getPointeeType();
  8090. // Never warn about void type pointers. This can be used to suppress
  8091. // false positives.
  8092. if (PointeeTy->isVoidType())
  8093. continue;
  8094. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  8095. // actually comparing the expressions for equality. Because computing the
  8096. // expression IDs can be expensive, we only do this if the diagnostic is
  8097. // enabled.
  8098. if (SizeOfArg &&
  8099. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  8100. SizeOfArg->getExprLoc())) {
  8101. // We only compute IDs for expressions if the warning is enabled, and
  8102. // cache the sizeof arg's ID.
  8103. if (SizeOfArgID == llvm::FoldingSetNodeID())
  8104. SizeOfArg->Profile(SizeOfArgID, Context, true);
  8105. llvm::FoldingSetNodeID DestID;
  8106. Dest->Profile(DestID, Context, true);
  8107. if (DestID == SizeOfArgID) {
  8108. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  8109. // over sizeof(src) as well.
  8110. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  8111. StringRef ReadableName = FnName->getName();
  8112. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  8113. if (UnaryOp->getOpcode() == UO_AddrOf)
  8114. ActionIdx = 1; // If its an address-of operator, just remove it.
  8115. if (!PointeeTy->isIncompleteType() &&
  8116. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  8117. ActionIdx = 2; // If the pointee's size is sizeof(char),
  8118. // suggest an explicit length.
  8119. // If the function is defined as a builtin macro, do not show macro
  8120. // expansion.
  8121. SourceLocation SL = SizeOfArg->getExprLoc();
  8122. SourceRange DSR = Dest->getSourceRange();
  8123. SourceRange SSR = SizeOfArg->getSourceRange();
  8124. SourceManager &SM = getSourceManager();
  8125. if (SM.isMacroArgExpansion(SL)) {
  8126. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  8127. SL = SM.getSpellingLoc(SL);
  8128. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  8129. SM.getSpellingLoc(DSR.getEnd()));
  8130. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  8131. SM.getSpellingLoc(SSR.getEnd()));
  8132. }
  8133. DiagRuntimeBehavior(SL, SizeOfArg,
  8134. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  8135. << ReadableName
  8136. << PointeeTy
  8137. << DestTy
  8138. << DSR
  8139. << SSR);
  8140. DiagRuntimeBehavior(SL, SizeOfArg,
  8141. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  8142. << ActionIdx
  8143. << SSR);
  8144. break;
  8145. }
  8146. }
  8147. // Also check for cases where the sizeof argument is the exact same
  8148. // type as the memory argument, and where it points to a user-defined
  8149. // record type.
  8150. if (SizeOfArgTy != QualType()) {
  8151. if (PointeeTy->isRecordType() &&
  8152. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  8153. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  8154. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  8155. << FnName << SizeOfArgTy << ArgIdx
  8156. << PointeeTy << Dest->getSourceRange()
  8157. << LenExpr->getSourceRange());
  8158. break;
  8159. }
  8160. }
  8161. } else if (DestTy->isArrayType()) {
  8162. PointeeTy = DestTy;
  8163. }
  8164. if (PointeeTy == QualType())
  8165. continue;
  8166. // Always complain about dynamic classes.
  8167. bool IsContained;
  8168. if (const CXXRecordDecl *ContainedRD =
  8169. getContainedDynamicClass(PointeeTy, IsContained)) {
  8170. unsigned OperationType = 0;
  8171. // "overwritten" if we're warning about the destination for any call
  8172. // but memcmp; otherwise a verb appropriate to the call.
  8173. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  8174. if (BId == Builtin::BImemcpy)
  8175. OperationType = 1;
  8176. else if(BId == Builtin::BImemmove)
  8177. OperationType = 2;
  8178. else if (BId == Builtin::BImemcmp)
  8179. OperationType = 3;
  8180. }
  8181. DiagRuntimeBehavior(
  8182. Dest->getExprLoc(), Dest,
  8183. PDiag(diag::warn_dyn_class_memaccess)
  8184. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  8185. << FnName << IsContained << ContainedRD << OperationType
  8186. << Call->getCallee()->getSourceRange());
  8187. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  8188. BId != Builtin::BImemset)
  8189. DiagRuntimeBehavior(
  8190. Dest->getExprLoc(), Dest,
  8191. PDiag(diag::warn_arc_object_memaccess)
  8192. << ArgIdx << FnName << PointeeTy
  8193. << Call->getCallee()->getSourceRange());
  8194. else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
  8195. if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
  8196. RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
  8197. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8198. PDiag(diag::warn_cstruct_memaccess)
  8199. << ArgIdx << FnName << PointeeTy << 0);
  8200. SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
  8201. } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  8202. RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
  8203. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8204. PDiag(diag::warn_cstruct_memaccess)
  8205. << ArgIdx << FnName << PointeeTy << 1);
  8206. SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
  8207. } else {
  8208. continue;
  8209. }
  8210. } else
  8211. continue;
  8212. DiagRuntimeBehavior(
  8213. Dest->getExprLoc(), Dest,
  8214. PDiag(diag::note_bad_memaccess_silence)
  8215. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  8216. break;
  8217. }
  8218. }
  8219. // A little helper routine: ignore addition and subtraction of integer literals.
  8220. // This intentionally does not ignore all integer constant expressions because
  8221. // we don't want to remove sizeof().
  8222. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  8223. Ex = Ex->IgnoreParenCasts();
  8224. while (true) {
  8225. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  8226. if (!BO || !BO->isAdditiveOp())
  8227. break;
  8228. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  8229. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  8230. if (isa<IntegerLiteral>(RHS))
  8231. Ex = LHS;
  8232. else if (isa<IntegerLiteral>(LHS))
  8233. Ex = RHS;
  8234. else
  8235. break;
  8236. }
  8237. return Ex;
  8238. }
  8239. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  8240. ASTContext &Context) {
  8241. // Only handle constant-sized or VLAs, but not flexible members.
  8242. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  8243. // Only issue the FIXIT for arrays of size > 1.
  8244. if (CAT->getSize().getSExtValue() <= 1)
  8245. return false;
  8246. } else if (!Ty->isVariableArrayType()) {
  8247. return false;
  8248. }
  8249. return true;
  8250. }
  8251. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  8252. // be the size of the source, instead of the destination.
  8253. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  8254. IdentifierInfo *FnName) {
  8255. // Don't crash if the user has the wrong number of arguments
  8256. unsigned NumArgs = Call->getNumArgs();
  8257. if ((NumArgs != 3) && (NumArgs != 4))
  8258. return;
  8259. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  8260. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  8261. const Expr *CompareWithSrc = nullptr;
  8262. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  8263. Call->getBeginLoc(), Call->getRParenLoc()))
  8264. return;
  8265. // Look for 'strlcpy(dst, x, sizeof(x))'
  8266. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  8267. CompareWithSrc = Ex;
  8268. else {
  8269. // Look for 'strlcpy(dst, x, strlen(x))'
  8270. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  8271. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  8272. SizeCall->getNumArgs() == 1)
  8273. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  8274. }
  8275. }
  8276. if (!CompareWithSrc)
  8277. return;
  8278. // Determine if the argument to sizeof/strlen is equal to the source
  8279. // argument. In principle there's all kinds of things you could do
  8280. // here, for instance creating an == expression and evaluating it with
  8281. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  8282. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  8283. if (!SrcArgDRE)
  8284. return;
  8285. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  8286. if (!CompareWithSrcDRE ||
  8287. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  8288. return;
  8289. const Expr *OriginalSizeArg = Call->getArg(2);
  8290. Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
  8291. << OriginalSizeArg->getSourceRange() << FnName;
  8292. // Output a FIXIT hint if the destination is an array (rather than a
  8293. // pointer to an array). This could be enhanced to handle some
  8294. // pointers if we know the actual size, like if DstArg is 'array+2'
  8295. // we could say 'sizeof(array)-2'.
  8296. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  8297. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  8298. return;
  8299. SmallString<128> sizeString;
  8300. llvm::raw_svector_ostream OS(sizeString);
  8301. OS << "sizeof(";
  8302. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8303. OS << ")";
  8304. Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
  8305. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  8306. OS.str());
  8307. }
  8308. /// Check if two expressions refer to the same declaration.
  8309. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  8310. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  8311. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  8312. return D1->getDecl() == D2->getDecl();
  8313. return false;
  8314. }
  8315. static const Expr *getStrlenExprArg(const Expr *E) {
  8316. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8317. const FunctionDecl *FD = CE->getDirectCallee();
  8318. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  8319. return nullptr;
  8320. return CE->getArg(0)->IgnoreParenCasts();
  8321. }
  8322. return nullptr;
  8323. }
  8324. // Warn on anti-patterns as the 'size' argument to strncat.
  8325. // The correct size argument should look like following:
  8326. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  8327. void Sema::CheckStrncatArguments(const CallExpr *CE,
  8328. IdentifierInfo *FnName) {
  8329. // Don't crash if the user has the wrong number of arguments.
  8330. if (CE->getNumArgs() < 3)
  8331. return;
  8332. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  8333. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  8334. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  8335. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
  8336. CE->getRParenLoc()))
  8337. return;
  8338. // Identify common expressions, which are wrongly used as the size argument
  8339. // to strncat and may lead to buffer overflows.
  8340. unsigned PatternType = 0;
  8341. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  8342. // - sizeof(dst)
  8343. if (referToTheSameDecl(SizeOfArg, DstArg))
  8344. PatternType = 1;
  8345. // - sizeof(src)
  8346. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  8347. PatternType = 2;
  8348. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  8349. if (BE->getOpcode() == BO_Sub) {
  8350. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  8351. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  8352. // - sizeof(dst) - strlen(dst)
  8353. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  8354. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  8355. PatternType = 1;
  8356. // - sizeof(src) - (anything)
  8357. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  8358. PatternType = 2;
  8359. }
  8360. }
  8361. if (PatternType == 0)
  8362. return;
  8363. // Generate the diagnostic.
  8364. SourceLocation SL = LenArg->getBeginLoc();
  8365. SourceRange SR = LenArg->getSourceRange();
  8366. SourceManager &SM = getSourceManager();
  8367. // If the function is defined as a builtin macro, do not show macro expansion.
  8368. if (SM.isMacroArgExpansion(SL)) {
  8369. SL = SM.getSpellingLoc(SL);
  8370. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  8371. SM.getSpellingLoc(SR.getEnd()));
  8372. }
  8373. // Check if the destination is an array (rather than a pointer to an array).
  8374. QualType DstTy = DstArg->getType();
  8375. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  8376. Context);
  8377. if (!isKnownSizeArray) {
  8378. if (PatternType == 1)
  8379. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  8380. else
  8381. Diag(SL, diag::warn_strncat_src_size) << SR;
  8382. return;
  8383. }
  8384. if (PatternType == 1)
  8385. Diag(SL, diag::warn_strncat_large_size) << SR;
  8386. else
  8387. Diag(SL, diag::warn_strncat_src_size) << SR;
  8388. SmallString<128> sizeString;
  8389. llvm::raw_svector_ostream OS(sizeString);
  8390. OS << "sizeof(";
  8391. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8392. OS << ") - ";
  8393. OS << "strlen(";
  8394. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8395. OS << ") - 1";
  8396. Diag(SL, diag::note_strncat_wrong_size)
  8397. << FixItHint::CreateReplacement(SR, OS.str());
  8398. }
  8399. void
  8400. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  8401. SourceLocation ReturnLoc,
  8402. bool isObjCMethod,
  8403. const AttrVec *Attrs,
  8404. const FunctionDecl *FD) {
  8405. // Check if the return value is null but should not be.
  8406. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  8407. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  8408. CheckNonNullExpr(*this, RetValExp))
  8409. Diag(ReturnLoc, diag::warn_null_ret)
  8410. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  8411. // C++11 [basic.stc.dynamic.allocation]p4:
  8412. // If an allocation function declared with a non-throwing
  8413. // exception-specification fails to allocate storage, it shall return
  8414. // a null pointer. Any other allocation function that fails to allocate
  8415. // storage shall indicate failure only by throwing an exception [...]
  8416. if (FD) {
  8417. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  8418. if (Op == OO_New || Op == OO_Array_New) {
  8419. const FunctionProtoType *Proto
  8420. = FD->getType()->castAs<FunctionProtoType>();
  8421. if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
  8422. CheckNonNullExpr(*this, RetValExp))
  8423. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  8424. << FD << getLangOpts().CPlusPlus11;
  8425. }
  8426. }
  8427. }
  8428. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  8429. /// Check for comparisons of floating point operands using != and ==.
  8430. /// Issue a warning if these are no self-comparisons, as they are not likely
  8431. /// to do what the programmer intended.
  8432. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  8433. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  8434. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  8435. // Special case: check for x == x (which is OK).
  8436. // Do not emit warnings for such cases.
  8437. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  8438. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  8439. if (DRL->getDecl() == DRR->getDecl())
  8440. return;
  8441. // Special case: check for comparisons against literals that can be exactly
  8442. // represented by APFloat. In such cases, do not emit a warning. This
  8443. // is a heuristic: often comparison against such literals are used to
  8444. // detect if a value in a variable has not changed. This clearly can
  8445. // lead to false negatives.
  8446. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  8447. if (FLL->isExact())
  8448. return;
  8449. } else
  8450. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  8451. if (FLR->isExact())
  8452. return;
  8453. // Check for comparisons with builtin types.
  8454. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  8455. if (CL->getBuiltinCallee())
  8456. return;
  8457. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  8458. if (CR->getBuiltinCallee())
  8459. return;
  8460. // Emit the diagnostic.
  8461. Diag(Loc, diag::warn_floatingpoint_eq)
  8462. << LHS->getSourceRange() << RHS->getSourceRange();
  8463. }
  8464. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  8465. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  8466. namespace {
  8467. /// Structure recording the 'active' range of an integer-valued
  8468. /// expression.
  8469. struct IntRange {
  8470. /// The number of bits active in the int.
  8471. unsigned Width;
  8472. /// True if the int is known not to have negative values.
  8473. bool NonNegative;
  8474. IntRange(unsigned Width, bool NonNegative)
  8475. : Width(Width), NonNegative(NonNegative) {}
  8476. /// Returns the range of the bool type.
  8477. static IntRange forBoolType() {
  8478. return IntRange(1, true);
  8479. }
  8480. /// Returns the range of an opaque value of the given integral type.
  8481. static IntRange forValueOfType(ASTContext &C, QualType T) {
  8482. return forValueOfCanonicalType(C,
  8483. T->getCanonicalTypeInternal().getTypePtr());
  8484. }
  8485. /// Returns the range of an opaque value of a canonical integral type.
  8486. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  8487. assert(T->isCanonicalUnqualified());
  8488. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8489. T = VT->getElementType().getTypePtr();
  8490. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8491. T = CT->getElementType().getTypePtr();
  8492. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8493. T = AT->getValueType().getTypePtr();
  8494. if (!C.getLangOpts().CPlusPlus) {
  8495. // For enum types in C code, use the underlying datatype.
  8496. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8497. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  8498. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  8499. // For enum types in C++, use the known bit width of the enumerators.
  8500. EnumDecl *Enum = ET->getDecl();
  8501. // In C++11, enums can have a fixed underlying type. Use this type to
  8502. // compute the range.
  8503. if (Enum->isFixed()) {
  8504. return IntRange(C.getIntWidth(QualType(T, 0)),
  8505. !ET->isSignedIntegerOrEnumerationType());
  8506. }
  8507. unsigned NumPositive = Enum->getNumPositiveBits();
  8508. unsigned NumNegative = Enum->getNumNegativeBits();
  8509. if (NumNegative == 0)
  8510. return IntRange(NumPositive, true/*NonNegative*/);
  8511. else
  8512. return IntRange(std::max(NumPositive + 1, NumNegative),
  8513. false/*NonNegative*/);
  8514. }
  8515. const BuiltinType *BT = cast<BuiltinType>(T);
  8516. assert(BT->isInteger());
  8517. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8518. }
  8519. /// Returns the "target" range of a canonical integral type, i.e.
  8520. /// the range of values expressible in the type.
  8521. ///
  8522. /// This matches forValueOfCanonicalType except that enums have the
  8523. /// full range of their type, not the range of their enumerators.
  8524. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  8525. assert(T->isCanonicalUnqualified());
  8526. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8527. T = VT->getElementType().getTypePtr();
  8528. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8529. T = CT->getElementType().getTypePtr();
  8530. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8531. T = AT->getValueType().getTypePtr();
  8532. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8533. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  8534. const BuiltinType *BT = cast<BuiltinType>(T);
  8535. assert(BT->isInteger());
  8536. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8537. }
  8538. /// Returns the supremum of two ranges: i.e. their conservative merge.
  8539. static IntRange join(IntRange L, IntRange R) {
  8540. return IntRange(std::max(L.Width, R.Width),
  8541. L.NonNegative && R.NonNegative);
  8542. }
  8543. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  8544. static IntRange meet(IntRange L, IntRange R) {
  8545. return IntRange(std::min(L.Width, R.Width),
  8546. L.NonNegative || R.NonNegative);
  8547. }
  8548. };
  8549. } // namespace
  8550. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  8551. unsigned MaxWidth) {
  8552. if (value.isSigned() && value.isNegative())
  8553. return IntRange(value.getMinSignedBits(), false);
  8554. if (value.getBitWidth() > MaxWidth)
  8555. value = value.trunc(MaxWidth);
  8556. // isNonNegative() just checks the sign bit without considering
  8557. // signedness.
  8558. return IntRange(value.getActiveBits(), true);
  8559. }
  8560. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  8561. unsigned MaxWidth) {
  8562. if (result.isInt())
  8563. return GetValueRange(C, result.getInt(), MaxWidth);
  8564. if (result.isVector()) {
  8565. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  8566. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  8567. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  8568. R = IntRange::join(R, El);
  8569. }
  8570. return R;
  8571. }
  8572. if (result.isComplexInt()) {
  8573. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  8574. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  8575. return IntRange::join(R, I);
  8576. }
  8577. // This can happen with lossless casts to intptr_t of "based" lvalues.
  8578. // Assume it might use arbitrary bits.
  8579. // FIXME: The only reason we need to pass the type in here is to get
  8580. // the sign right on this one case. It would be nice if APValue
  8581. // preserved this.
  8582. assert(result.isLValue() || result.isAddrLabelDiff());
  8583. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  8584. }
  8585. static QualType GetExprType(const Expr *E) {
  8586. QualType Ty = E->getType();
  8587. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  8588. Ty = AtomicRHS->getValueType();
  8589. return Ty;
  8590. }
  8591. /// Pseudo-evaluate the given integer expression, estimating the
  8592. /// range of values it might take.
  8593. ///
  8594. /// \param MaxWidth - the width to which the value will be truncated
  8595. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
  8596. E = E->IgnoreParens();
  8597. // Try a full evaluation first.
  8598. Expr::EvalResult result;
  8599. if (E->EvaluateAsRValue(result, C))
  8600. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  8601. // I think we only want to look through implicit casts here; if the
  8602. // user has an explicit widening cast, we should treat the value as
  8603. // being of the new, wider type.
  8604. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  8605. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  8606. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  8607. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  8608. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  8609. CE->getCastKind() == CK_BooleanToSignedIntegral;
  8610. // Assume that non-integer casts can span the full range of the type.
  8611. if (!isIntegerCast)
  8612. return OutputTypeRange;
  8613. IntRange SubRange
  8614. = GetExprRange(C, CE->getSubExpr(),
  8615. std::min(MaxWidth, OutputTypeRange.Width));
  8616. // Bail out if the subexpr's range is as wide as the cast type.
  8617. if (SubRange.Width >= OutputTypeRange.Width)
  8618. return OutputTypeRange;
  8619. // Otherwise, we take the smaller width, and we're non-negative if
  8620. // either the output type or the subexpr is.
  8621. return IntRange(SubRange.Width,
  8622. SubRange.NonNegative || OutputTypeRange.NonNegative);
  8623. }
  8624. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  8625. // If we can fold the condition, just take that operand.
  8626. bool CondResult;
  8627. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  8628. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  8629. : CO->getFalseExpr(),
  8630. MaxWidth);
  8631. // Otherwise, conservatively merge.
  8632. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  8633. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  8634. return IntRange::join(L, R);
  8635. }
  8636. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  8637. switch (BO->getOpcode()) {
  8638. case BO_Cmp:
  8639. llvm_unreachable("builtin <=> should have class type");
  8640. // Boolean-valued operations are single-bit and positive.
  8641. case BO_LAnd:
  8642. case BO_LOr:
  8643. case BO_LT:
  8644. case BO_GT:
  8645. case BO_LE:
  8646. case BO_GE:
  8647. case BO_EQ:
  8648. case BO_NE:
  8649. return IntRange::forBoolType();
  8650. // The type of the assignments is the type of the LHS, so the RHS
  8651. // is not necessarily the same type.
  8652. case BO_MulAssign:
  8653. case BO_DivAssign:
  8654. case BO_RemAssign:
  8655. case BO_AddAssign:
  8656. case BO_SubAssign:
  8657. case BO_XorAssign:
  8658. case BO_OrAssign:
  8659. // TODO: bitfields?
  8660. return IntRange::forValueOfType(C, GetExprType(E));
  8661. // Simple assignments just pass through the RHS, which will have
  8662. // been coerced to the LHS type.
  8663. case BO_Assign:
  8664. // TODO: bitfields?
  8665. return GetExprRange(C, BO->getRHS(), MaxWidth);
  8666. // Operations with opaque sources are black-listed.
  8667. case BO_PtrMemD:
  8668. case BO_PtrMemI:
  8669. return IntRange::forValueOfType(C, GetExprType(E));
  8670. // Bitwise-and uses the *infinum* of the two source ranges.
  8671. case BO_And:
  8672. case BO_AndAssign:
  8673. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  8674. GetExprRange(C, BO->getRHS(), MaxWidth));
  8675. // Left shift gets black-listed based on a judgement call.
  8676. case BO_Shl:
  8677. // ...except that we want to treat '1 << (blah)' as logically
  8678. // positive. It's an important idiom.
  8679. if (IntegerLiteral *I
  8680. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  8681. if (I->getValue() == 1) {
  8682. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  8683. return IntRange(R.Width, /*NonNegative*/ true);
  8684. }
  8685. }
  8686. LLVM_FALLTHROUGH;
  8687. case BO_ShlAssign:
  8688. return IntRange::forValueOfType(C, GetExprType(E));
  8689. // Right shift by a constant can narrow its left argument.
  8690. case BO_Shr:
  8691. case BO_ShrAssign: {
  8692. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  8693. // If the shift amount is a positive constant, drop the width by
  8694. // that much.
  8695. llvm::APSInt shift;
  8696. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  8697. shift.isNonNegative()) {
  8698. unsigned zext = shift.getZExtValue();
  8699. if (zext >= L.Width)
  8700. L.Width = (L.NonNegative ? 0 : 1);
  8701. else
  8702. L.Width -= zext;
  8703. }
  8704. return L;
  8705. }
  8706. // Comma acts as its right operand.
  8707. case BO_Comma:
  8708. return GetExprRange(C, BO->getRHS(), MaxWidth);
  8709. // Black-list pointer subtractions.
  8710. case BO_Sub:
  8711. if (BO->getLHS()->getType()->isPointerType())
  8712. return IntRange::forValueOfType(C, GetExprType(E));
  8713. break;
  8714. // The width of a division result is mostly determined by the size
  8715. // of the LHS.
  8716. case BO_Div: {
  8717. // Don't 'pre-truncate' the operands.
  8718. unsigned opWidth = C.getIntWidth(GetExprType(E));
  8719. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  8720. // If the divisor is constant, use that.
  8721. llvm::APSInt divisor;
  8722. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  8723. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  8724. if (log2 >= L.Width)
  8725. L.Width = (L.NonNegative ? 0 : 1);
  8726. else
  8727. L.Width = std::min(L.Width - log2, MaxWidth);
  8728. return L;
  8729. }
  8730. // Otherwise, just use the LHS's width.
  8731. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  8732. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  8733. }
  8734. // The result of a remainder can't be larger than the result of
  8735. // either side.
  8736. case BO_Rem: {
  8737. // Don't 'pre-truncate' the operands.
  8738. unsigned opWidth = C.getIntWidth(GetExprType(E));
  8739. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  8740. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  8741. IntRange meet = IntRange::meet(L, R);
  8742. meet.Width = std::min(meet.Width, MaxWidth);
  8743. return meet;
  8744. }
  8745. // The default behavior is okay for these.
  8746. case BO_Mul:
  8747. case BO_Add:
  8748. case BO_Xor:
  8749. case BO_Or:
  8750. break;
  8751. }
  8752. // The default case is to treat the operation as if it were closed
  8753. // on the narrowest type that encompasses both operands.
  8754. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  8755. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  8756. return IntRange::join(L, R);
  8757. }
  8758. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  8759. switch (UO->getOpcode()) {
  8760. // Boolean-valued operations are white-listed.
  8761. case UO_LNot:
  8762. return IntRange::forBoolType();
  8763. // Operations with opaque sources are black-listed.
  8764. case UO_Deref:
  8765. case UO_AddrOf: // should be impossible
  8766. return IntRange::forValueOfType(C, GetExprType(E));
  8767. default:
  8768. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  8769. }
  8770. }
  8771. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  8772. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
  8773. if (const auto *BitField = E->getSourceBitField())
  8774. return IntRange(BitField->getBitWidthValue(C),
  8775. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  8776. return IntRange::forValueOfType(C, GetExprType(E));
  8777. }
  8778. static IntRange GetExprRange(ASTContext &C, const Expr *E) {
  8779. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
  8780. }
  8781. /// Checks whether the given value, which currently has the given
  8782. /// source semantics, has the same value when coerced through the
  8783. /// target semantics.
  8784. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  8785. const llvm::fltSemantics &Src,
  8786. const llvm::fltSemantics &Tgt) {
  8787. llvm::APFloat truncated = value;
  8788. bool ignored;
  8789. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  8790. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  8791. return truncated.bitwiseIsEqual(value);
  8792. }
  8793. /// Checks whether the given value, which currently has the given
  8794. /// source semantics, has the same value when coerced through the
  8795. /// target semantics.
  8796. ///
  8797. /// The value might be a vector of floats (or a complex number).
  8798. static bool IsSameFloatAfterCast(const APValue &value,
  8799. const llvm::fltSemantics &Src,
  8800. const llvm::fltSemantics &Tgt) {
  8801. if (value.isFloat())
  8802. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  8803. if (value.isVector()) {
  8804. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  8805. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  8806. return false;
  8807. return true;
  8808. }
  8809. assert(value.isComplexFloat());
  8810. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  8811. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  8812. }
  8813. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  8814. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  8815. // Suppress cases where we are comparing against an enum constant.
  8816. if (const DeclRefExpr *DR =
  8817. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  8818. if (isa<EnumConstantDecl>(DR->getDecl()))
  8819. return true;
  8820. // Suppress cases where the '0' value is expanded from a macro.
  8821. if (E->getBeginLoc().isMacroID())
  8822. return true;
  8823. return false;
  8824. }
  8825. static bool isKnownToHaveUnsignedValue(Expr *E) {
  8826. return E->getType()->isIntegerType() &&
  8827. (!E->getType()->isSignedIntegerType() ||
  8828. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  8829. }
  8830. namespace {
  8831. /// The promoted range of values of a type. In general this has the
  8832. /// following structure:
  8833. ///
  8834. /// |-----------| . . . |-----------|
  8835. /// ^ ^ ^ ^
  8836. /// Min HoleMin HoleMax Max
  8837. ///
  8838. /// ... where there is only a hole if a signed type is promoted to unsigned
  8839. /// (in which case Min and Max are the smallest and largest representable
  8840. /// values).
  8841. struct PromotedRange {
  8842. // Min, or HoleMax if there is a hole.
  8843. llvm::APSInt PromotedMin;
  8844. // Max, or HoleMin if there is a hole.
  8845. llvm::APSInt PromotedMax;
  8846. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  8847. if (R.Width == 0)
  8848. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  8849. else if (R.Width >= BitWidth && !Unsigned) {
  8850. // Promotion made the type *narrower*. This happens when promoting
  8851. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  8852. // Treat all values of 'signed int' as being in range for now.
  8853. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  8854. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  8855. } else {
  8856. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  8857. .extOrTrunc(BitWidth);
  8858. PromotedMin.setIsUnsigned(Unsigned);
  8859. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  8860. .extOrTrunc(BitWidth);
  8861. PromotedMax.setIsUnsigned(Unsigned);
  8862. }
  8863. }
  8864. // Determine whether this range is contiguous (has no hole).
  8865. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  8866. // Where a constant value is within the range.
  8867. enum ComparisonResult {
  8868. LT = 0x1,
  8869. LE = 0x2,
  8870. GT = 0x4,
  8871. GE = 0x8,
  8872. EQ = 0x10,
  8873. NE = 0x20,
  8874. InRangeFlag = 0x40,
  8875. Less = LE | LT | NE,
  8876. Min = LE | InRangeFlag,
  8877. InRange = InRangeFlag,
  8878. Max = GE | InRangeFlag,
  8879. Greater = GE | GT | NE,
  8880. OnlyValue = LE | GE | EQ | InRangeFlag,
  8881. InHole = NE
  8882. };
  8883. ComparisonResult compare(const llvm::APSInt &Value) const {
  8884. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  8885. Value.isUnsigned() == PromotedMin.isUnsigned());
  8886. if (!isContiguous()) {
  8887. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  8888. if (Value.isMinValue()) return Min;
  8889. if (Value.isMaxValue()) return Max;
  8890. if (Value >= PromotedMin) return InRange;
  8891. if (Value <= PromotedMax) return InRange;
  8892. return InHole;
  8893. }
  8894. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  8895. case -1: return Less;
  8896. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  8897. case 1:
  8898. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  8899. case -1: return InRange;
  8900. case 0: return Max;
  8901. case 1: return Greater;
  8902. }
  8903. }
  8904. llvm_unreachable("impossible compare result");
  8905. }
  8906. static llvm::Optional<StringRef>
  8907. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  8908. if (Op == BO_Cmp) {
  8909. ComparisonResult LTFlag = LT, GTFlag = GT;
  8910. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  8911. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  8912. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  8913. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  8914. return llvm::None;
  8915. }
  8916. ComparisonResult TrueFlag, FalseFlag;
  8917. if (Op == BO_EQ) {
  8918. TrueFlag = EQ;
  8919. FalseFlag = NE;
  8920. } else if (Op == BO_NE) {
  8921. TrueFlag = NE;
  8922. FalseFlag = EQ;
  8923. } else {
  8924. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  8925. TrueFlag = LT;
  8926. FalseFlag = GE;
  8927. } else {
  8928. TrueFlag = GT;
  8929. FalseFlag = LE;
  8930. }
  8931. if (Op == BO_GE || Op == BO_LE)
  8932. std::swap(TrueFlag, FalseFlag);
  8933. }
  8934. if (R & TrueFlag)
  8935. return StringRef("true");
  8936. if (R & FalseFlag)
  8937. return StringRef("false");
  8938. return llvm::None;
  8939. }
  8940. };
  8941. }
  8942. static bool HasEnumType(Expr *E) {
  8943. // Strip off implicit integral promotions.
  8944. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  8945. if (ICE->getCastKind() != CK_IntegralCast &&
  8946. ICE->getCastKind() != CK_NoOp)
  8947. break;
  8948. E = ICE->getSubExpr();
  8949. }
  8950. return E->getType()->isEnumeralType();
  8951. }
  8952. static int classifyConstantValue(Expr *Constant) {
  8953. // The values of this enumeration are used in the diagnostics
  8954. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  8955. enum ConstantValueKind {
  8956. Miscellaneous = 0,
  8957. LiteralTrue,
  8958. LiteralFalse
  8959. };
  8960. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  8961. return BL->getValue() ? ConstantValueKind::LiteralTrue
  8962. : ConstantValueKind::LiteralFalse;
  8963. return ConstantValueKind::Miscellaneous;
  8964. }
  8965. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  8966. Expr *Constant, Expr *Other,
  8967. const llvm::APSInt &Value,
  8968. bool RhsConstant) {
  8969. if (S.inTemplateInstantiation())
  8970. return false;
  8971. Expr *OriginalOther = Other;
  8972. Constant = Constant->IgnoreParenImpCasts();
  8973. Other = Other->IgnoreParenImpCasts();
  8974. // Suppress warnings on tautological comparisons between values of the same
  8975. // enumeration type. There are only two ways we could warn on this:
  8976. // - If the constant is outside the range of representable values of
  8977. // the enumeration. In such a case, we should warn about the cast
  8978. // to enumeration type, not about the comparison.
  8979. // - If the constant is the maximum / minimum in-range value. For an
  8980. // enumeratin type, such comparisons can be meaningful and useful.
  8981. if (Constant->getType()->isEnumeralType() &&
  8982. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  8983. return false;
  8984. // TODO: Investigate using GetExprRange() to get tighter bounds
  8985. // on the bit ranges.
  8986. QualType OtherT = Other->getType();
  8987. if (const auto *AT = OtherT->getAs<AtomicType>())
  8988. OtherT = AT->getValueType();
  8989. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  8990. // Whether we're treating Other as being a bool because of the form of
  8991. // expression despite it having another type (typically 'int' in C).
  8992. bool OtherIsBooleanDespiteType =
  8993. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  8994. if (OtherIsBooleanDespiteType)
  8995. OtherRange = IntRange::forBoolType();
  8996. // Determine the promoted range of the other type and see if a comparison of
  8997. // the constant against that range is tautological.
  8998. PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
  8999. Value.isUnsigned());
  9000. auto Cmp = OtherPromotedRange.compare(Value);
  9001. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  9002. if (!Result)
  9003. return false;
  9004. // Suppress the diagnostic for an in-range comparison if the constant comes
  9005. // from a macro or enumerator. We don't want to diagnose
  9006. //
  9007. // some_long_value <= INT_MAX
  9008. //
  9009. // when sizeof(int) == sizeof(long).
  9010. bool InRange = Cmp & PromotedRange::InRangeFlag;
  9011. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  9012. return false;
  9013. // If this is a comparison to an enum constant, include that
  9014. // constant in the diagnostic.
  9015. const EnumConstantDecl *ED = nullptr;
  9016. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  9017. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  9018. // Should be enough for uint128 (39 decimal digits)
  9019. SmallString<64> PrettySourceValue;
  9020. llvm::raw_svector_ostream OS(PrettySourceValue);
  9021. if (ED)
  9022. OS << '\'' << *ED << "' (" << Value << ")";
  9023. else
  9024. OS << Value;
  9025. // FIXME: We use a somewhat different formatting for the in-range cases and
  9026. // cases involving boolean values for historical reasons. We should pick a
  9027. // consistent way of presenting these diagnostics.
  9028. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  9029. S.DiagRuntimeBehavior(
  9030. E->getOperatorLoc(), E,
  9031. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  9032. : diag::warn_tautological_bool_compare)
  9033. << OS.str() << classifyConstantValue(Constant)
  9034. << OtherT << OtherIsBooleanDespiteType << *Result
  9035. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  9036. } else {
  9037. unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  9038. ? (HasEnumType(OriginalOther)
  9039. ? diag::warn_unsigned_enum_always_true_comparison
  9040. : diag::warn_unsigned_always_true_comparison)
  9041. : diag::warn_tautological_constant_compare;
  9042. S.Diag(E->getOperatorLoc(), Diag)
  9043. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  9044. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  9045. }
  9046. return true;
  9047. }
  9048. /// Analyze the operands of the given comparison. Implements the
  9049. /// fallback case from AnalyzeComparison.
  9050. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  9051. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9052. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9053. }
  9054. /// Implements -Wsign-compare.
  9055. ///
  9056. /// \param E the binary operator to check for warnings
  9057. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  9058. // The type the comparison is being performed in.
  9059. QualType T = E->getLHS()->getType();
  9060. // Only analyze comparison operators where both sides have been converted to
  9061. // the same type.
  9062. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  9063. return AnalyzeImpConvsInComparison(S, E);
  9064. // Don't analyze value-dependent comparisons directly.
  9065. if (E->isValueDependent())
  9066. return AnalyzeImpConvsInComparison(S, E);
  9067. Expr *LHS = E->getLHS();
  9068. Expr *RHS = E->getRHS();
  9069. if (T->isIntegralType(S.Context)) {
  9070. llvm::APSInt RHSValue;
  9071. llvm::APSInt LHSValue;
  9072. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  9073. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  9074. // We don't care about expressions whose result is a constant.
  9075. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  9076. return AnalyzeImpConvsInComparison(S, E);
  9077. // We only care about expressions where just one side is literal
  9078. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  9079. // Is the constant on the RHS or LHS?
  9080. const bool RhsConstant = IsRHSIntegralLiteral;
  9081. Expr *Const = RhsConstant ? RHS : LHS;
  9082. Expr *Other = RhsConstant ? LHS : RHS;
  9083. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  9084. // Check whether an integer constant comparison results in a value
  9085. // of 'true' or 'false'.
  9086. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  9087. return AnalyzeImpConvsInComparison(S, E);
  9088. }
  9089. }
  9090. if (!T->hasUnsignedIntegerRepresentation()) {
  9091. // We don't do anything special if this isn't an unsigned integral
  9092. // comparison: we're only interested in integral comparisons, and
  9093. // signed comparisons only happen in cases we don't care to warn about.
  9094. return AnalyzeImpConvsInComparison(S, E);
  9095. }
  9096. LHS = LHS->IgnoreParenImpCasts();
  9097. RHS = RHS->IgnoreParenImpCasts();
  9098. if (!S.getLangOpts().CPlusPlus) {
  9099. // Avoid warning about comparison of integers with different signs when
  9100. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  9101. // the type of `E`.
  9102. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  9103. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9104. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  9105. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9106. }
  9107. // Check to see if one of the (unmodified) operands is of different
  9108. // signedness.
  9109. Expr *signedOperand, *unsignedOperand;
  9110. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  9111. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  9112. "unsigned comparison between two signed integer expressions?");
  9113. signedOperand = LHS;
  9114. unsignedOperand = RHS;
  9115. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  9116. signedOperand = RHS;
  9117. unsignedOperand = LHS;
  9118. } else {
  9119. return AnalyzeImpConvsInComparison(S, E);
  9120. }
  9121. // Otherwise, calculate the effective range of the signed operand.
  9122. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  9123. // Go ahead and analyze implicit conversions in the operands. Note
  9124. // that we skip the implicit conversions on both sides.
  9125. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  9126. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  9127. // If the signed range is non-negative, -Wsign-compare won't fire.
  9128. if (signedRange.NonNegative)
  9129. return;
  9130. // For (in)equality comparisons, if the unsigned operand is a
  9131. // constant which cannot collide with a overflowed signed operand,
  9132. // then reinterpreting the signed operand as unsigned will not
  9133. // change the result of the comparison.
  9134. if (E->isEqualityOp()) {
  9135. unsigned comparisonWidth = S.Context.getIntWidth(T);
  9136. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  9137. // We should never be unable to prove that the unsigned operand is
  9138. // non-negative.
  9139. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  9140. if (unsignedRange.Width < comparisonWidth)
  9141. return;
  9142. }
  9143. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9144. S.PDiag(diag::warn_mixed_sign_comparison)
  9145. << LHS->getType() << RHS->getType()
  9146. << LHS->getSourceRange() << RHS->getSourceRange());
  9147. }
  9148. /// Analyzes an attempt to assign the given value to a bitfield.
  9149. ///
  9150. /// Returns true if there was something fishy about the attempt.
  9151. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  9152. SourceLocation InitLoc) {
  9153. assert(Bitfield->isBitField());
  9154. if (Bitfield->isInvalidDecl())
  9155. return false;
  9156. // White-list bool bitfields.
  9157. QualType BitfieldType = Bitfield->getType();
  9158. if (BitfieldType->isBooleanType())
  9159. return false;
  9160. if (BitfieldType->isEnumeralType()) {
  9161. EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
  9162. // If the underlying enum type was not explicitly specified as an unsigned
  9163. // type and the enum contain only positive values, MSVC++ will cause an
  9164. // inconsistency by storing this as a signed type.
  9165. if (S.getLangOpts().CPlusPlus11 &&
  9166. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  9167. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  9168. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  9169. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  9170. << BitfieldEnumDecl->getNameAsString();
  9171. }
  9172. }
  9173. if (Bitfield->getType()->isBooleanType())
  9174. return false;
  9175. // Ignore value- or type-dependent expressions.
  9176. if (Bitfield->getBitWidth()->isValueDependent() ||
  9177. Bitfield->getBitWidth()->isTypeDependent() ||
  9178. Init->isValueDependent() ||
  9179. Init->isTypeDependent())
  9180. return false;
  9181. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  9182. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  9183. llvm::APSInt Value;
  9184. if (!OriginalInit->EvaluateAsInt(Value, S.Context,
  9185. Expr::SE_AllowSideEffects)) {
  9186. // The RHS is not constant. If the RHS has an enum type, make sure the
  9187. // bitfield is wide enough to hold all the values of the enum without
  9188. // truncation.
  9189. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  9190. EnumDecl *ED = EnumTy->getDecl();
  9191. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  9192. // Enum types are implicitly signed on Windows, so check if there are any
  9193. // negative enumerators to see if the enum was intended to be signed or
  9194. // not.
  9195. bool SignedEnum = ED->getNumNegativeBits() > 0;
  9196. // Check for surprising sign changes when assigning enum values to a
  9197. // bitfield of different signedness. If the bitfield is signed and we
  9198. // have exactly the right number of bits to store this unsigned enum,
  9199. // suggest changing the enum to an unsigned type. This typically happens
  9200. // on Windows where unfixed enums always use an underlying type of 'int'.
  9201. unsigned DiagID = 0;
  9202. if (SignedEnum && !SignedBitfield) {
  9203. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  9204. } else if (SignedBitfield && !SignedEnum &&
  9205. ED->getNumPositiveBits() == FieldWidth) {
  9206. DiagID = diag::warn_signed_bitfield_enum_conversion;
  9207. }
  9208. if (DiagID) {
  9209. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  9210. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  9211. SourceRange TypeRange =
  9212. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  9213. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  9214. << SignedEnum << TypeRange;
  9215. }
  9216. // Compute the required bitwidth. If the enum has negative values, we need
  9217. // one more bit than the normal number of positive bits to represent the
  9218. // sign bit.
  9219. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  9220. ED->getNumNegativeBits())
  9221. : ED->getNumPositiveBits();
  9222. // Check the bitwidth.
  9223. if (BitsNeeded > FieldWidth) {
  9224. Expr *WidthExpr = Bitfield->getBitWidth();
  9225. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  9226. << Bitfield << ED;
  9227. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  9228. << BitsNeeded << ED << WidthExpr->getSourceRange();
  9229. }
  9230. }
  9231. return false;
  9232. }
  9233. unsigned OriginalWidth = Value.getBitWidth();
  9234. if (!Value.isSigned() || Value.isNegative())
  9235. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  9236. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  9237. OriginalWidth = Value.getMinSignedBits();
  9238. if (OriginalWidth <= FieldWidth)
  9239. return false;
  9240. // Compute the value which the bitfield will contain.
  9241. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  9242. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  9243. // Check whether the stored value is equal to the original value.
  9244. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  9245. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  9246. return false;
  9247. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  9248. // therefore don't strictly fit into a signed bitfield of width 1.
  9249. if (FieldWidth == 1 && Value == 1)
  9250. return false;
  9251. std::string PrettyValue = Value.toString(10);
  9252. std::string PrettyTrunc = TruncatedValue.toString(10);
  9253. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  9254. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  9255. << Init->getSourceRange();
  9256. return true;
  9257. }
  9258. /// Analyze the given simple or compound assignment for warning-worthy
  9259. /// operations.
  9260. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  9261. // Just recurse on the LHS.
  9262. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9263. // We want to recurse on the RHS as normal unless we're assigning to
  9264. // a bitfield.
  9265. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  9266. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  9267. E->getOperatorLoc())) {
  9268. // Recurse, ignoring any implicit conversions on the RHS.
  9269. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  9270. E->getOperatorLoc());
  9271. }
  9272. }
  9273. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9274. // Diagnose implicitly sequentially-consistent atomic assignment.
  9275. if (E->getLHS()->getType()->isAtomicType())
  9276. S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  9277. }
  9278. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9279. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  9280. SourceLocation CContext, unsigned diag,
  9281. bool pruneControlFlow = false) {
  9282. if (pruneControlFlow) {
  9283. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9284. S.PDiag(diag)
  9285. << SourceType << T << E->getSourceRange()
  9286. << SourceRange(CContext));
  9287. return;
  9288. }
  9289. S.Diag(E->getExprLoc(), diag)
  9290. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  9291. }
  9292. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9293. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  9294. SourceLocation CContext,
  9295. unsigned diag, bool pruneControlFlow = false) {
  9296. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  9297. }
  9298. /// Diagnose an implicit cast from a floating point value to an integer value.
  9299. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  9300. SourceLocation CContext) {
  9301. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  9302. const bool PruneWarnings = S.inTemplateInstantiation();
  9303. Expr *InnerE = E->IgnoreParenImpCasts();
  9304. // We also want to warn on, e.g., "int i = -1.234"
  9305. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  9306. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  9307. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  9308. const bool IsLiteral =
  9309. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  9310. llvm::APFloat Value(0.0);
  9311. bool IsConstant =
  9312. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  9313. if (!IsConstant) {
  9314. return DiagnoseImpCast(S, E, T, CContext,
  9315. diag::warn_impcast_float_integer, PruneWarnings);
  9316. }
  9317. bool isExact = false;
  9318. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  9319. T->hasUnsignedIntegerRepresentation());
  9320. llvm::APFloat::opStatus Result = Value.convertToInteger(
  9321. IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
  9322. if (Result == llvm::APFloat::opOK && isExact) {
  9323. if (IsLiteral) return;
  9324. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  9325. PruneWarnings);
  9326. }
  9327. // Conversion of a floating-point value to a non-bool integer where the
  9328. // integral part cannot be represented by the integer type is undefined.
  9329. if (!IsBool && Result == llvm::APFloat::opInvalidOp)
  9330. return DiagnoseImpCast(
  9331. S, E, T, CContext,
  9332. IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
  9333. : diag::warn_impcast_float_to_integer_out_of_range,
  9334. PruneWarnings);
  9335. unsigned DiagID = 0;
  9336. if (IsLiteral) {
  9337. // Warn on floating point literal to integer.
  9338. DiagID = diag::warn_impcast_literal_float_to_integer;
  9339. } else if (IntegerValue == 0) {
  9340. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  9341. return DiagnoseImpCast(S, E, T, CContext,
  9342. diag::warn_impcast_float_integer, PruneWarnings);
  9343. }
  9344. // Warn on non-zero to zero conversion.
  9345. DiagID = diag::warn_impcast_float_to_integer_zero;
  9346. } else {
  9347. if (IntegerValue.isUnsigned()) {
  9348. if (!IntegerValue.isMaxValue()) {
  9349. return DiagnoseImpCast(S, E, T, CContext,
  9350. diag::warn_impcast_float_integer, PruneWarnings);
  9351. }
  9352. } else { // IntegerValue.isSigned()
  9353. if (!IntegerValue.isMaxSignedValue() &&
  9354. !IntegerValue.isMinSignedValue()) {
  9355. return DiagnoseImpCast(S, E, T, CContext,
  9356. diag::warn_impcast_float_integer, PruneWarnings);
  9357. }
  9358. }
  9359. // Warn on evaluatable floating point expression to integer conversion.
  9360. DiagID = diag::warn_impcast_float_to_integer;
  9361. }
  9362. // FIXME: Force the precision of the source value down so we don't print
  9363. // digits which are usually useless (we don't really care here if we
  9364. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  9365. // would automatically print the shortest representation, but it's a bit
  9366. // tricky to implement.
  9367. SmallString<16> PrettySourceValue;
  9368. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  9369. precision = (precision * 59 + 195) / 196;
  9370. Value.toString(PrettySourceValue, precision);
  9371. SmallString<16> PrettyTargetValue;
  9372. if (IsBool)
  9373. PrettyTargetValue = Value.isZero() ? "false" : "true";
  9374. else
  9375. IntegerValue.toString(PrettyTargetValue);
  9376. if (PruneWarnings) {
  9377. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9378. S.PDiag(DiagID)
  9379. << E->getType() << T.getUnqualifiedType()
  9380. << PrettySourceValue << PrettyTargetValue
  9381. << E->getSourceRange() << SourceRange(CContext));
  9382. } else {
  9383. S.Diag(E->getExprLoc(), DiagID)
  9384. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  9385. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  9386. }
  9387. }
  9388. /// Analyze the given compound assignment for the possible losing of
  9389. /// floating-point precision.
  9390. static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
  9391. assert(isa<CompoundAssignOperator>(E) &&
  9392. "Must be compound assignment operation");
  9393. // Recurse on the LHS and RHS in here
  9394. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9395. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9396. if (E->getLHS()->getType()->isAtomicType())
  9397. S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
  9398. // Now check the outermost expression
  9399. const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
  9400. const auto *RBT = cast<CompoundAssignOperator>(E)
  9401. ->getComputationResultType()
  9402. ->getAs<BuiltinType>();
  9403. // The below checks assume source is floating point.
  9404. if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
  9405. // If source is floating point but target is not.
  9406. if (!ResultBT->isFloatingPoint())
  9407. return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(),
  9408. E->getExprLoc());
  9409. // If both source and target are floating points.
  9410. // Builtin FP kinds are ordered by increasing FP rank.
  9411. if (ResultBT->getKind() < RBT->getKind() &&
  9412. // We don't want to warn for system macro.
  9413. !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
  9414. // warn about dropping FP rank.
  9415. DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
  9416. diag::warn_impcast_float_result_precision);
  9417. }
  9418. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  9419. IntRange Range) {
  9420. if (!Range.Width) return "0";
  9421. llvm::APSInt ValueInRange = Value;
  9422. ValueInRange.setIsSigned(!Range.NonNegative);
  9423. ValueInRange = ValueInRange.trunc(Range.Width);
  9424. return ValueInRange.toString(10);
  9425. }
  9426. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  9427. if (!isa<ImplicitCastExpr>(Ex))
  9428. return false;
  9429. Expr *InnerE = Ex->IgnoreParenImpCasts();
  9430. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  9431. const Type *Source =
  9432. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  9433. if (Target->isDependentType())
  9434. return false;
  9435. const BuiltinType *FloatCandidateBT =
  9436. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  9437. const Type *BoolCandidateType = ToBool ? Target : Source;
  9438. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  9439. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  9440. }
  9441. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  9442. SourceLocation CC) {
  9443. unsigned NumArgs = TheCall->getNumArgs();
  9444. for (unsigned i = 0; i < NumArgs; ++i) {
  9445. Expr *CurrA = TheCall->getArg(i);
  9446. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  9447. continue;
  9448. bool IsSwapped = ((i > 0) &&
  9449. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  9450. IsSwapped |= ((i < (NumArgs - 1)) &&
  9451. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  9452. if (IsSwapped) {
  9453. // Warn on this floating-point to bool conversion.
  9454. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  9455. CurrA->getType(), CC,
  9456. diag::warn_impcast_floating_point_to_bool);
  9457. }
  9458. }
  9459. }
  9460. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  9461. SourceLocation CC) {
  9462. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  9463. E->getExprLoc()))
  9464. return;
  9465. // Don't warn on functions which have return type nullptr_t.
  9466. if (isa<CallExpr>(E))
  9467. return;
  9468. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  9469. const Expr::NullPointerConstantKind NullKind =
  9470. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  9471. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  9472. return;
  9473. // Return if target type is a safe conversion.
  9474. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  9475. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  9476. return;
  9477. SourceLocation Loc = E->getSourceRange().getBegin();
  9478. // Venture through the macro stacks to get to the source of macro arguments.
  9479. // The new location is a better location than the complete location that was
  9480. // passed in.
  9481. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  9482. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  9483. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  9484. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  9485. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  9486. Loc, S.SourceMgr, S.getLangOpts());
  9487. if (MacroName == "NULL")
  9488. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
  9489. }
  9490. // Only warn if the null and context location are in the same macro expansion.
  9491. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  9492. return;
  9493. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  9494. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  9495. << FixItHint::CreateReplacement(Loc,
  9496. S.getFixItZeroLiteralForType(T, Loc));
  9497. }
  9498. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9499. ObjCArrayLiteral *ArrayLiteral);
  9500. static void
  9501. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9502. ObjCDictionaryLiteral *DictionaryLiteral);
  9503. /// Check a single element within a collection literal against the
  9504. /// target element type.
  9505. static void checkObjCCollectionLiteralElement(Sema &S,
  9506. QualType TargetElementType,
  9507. Expr *Element,
  9508. unsigned ElementKind) {
  9509. // Skip a bitcast to 'id' or qualified 'id'.
  9510. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  9511. if (ICE->getCastKind() == CK_BitCast &&
  9512. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  9513. Element = ICE->getSubExpr();
  9514. }
  9515. QualType ElementType = Element->getType();
  9516. ExprResult ElementResult(Element);
  9517. if (ElementType->getAs<ObjCObjectPointerType>() &&
  9518. S.CheckSingleAssignmentConstraints(TargetElementType,
  9519. ElementResult,
  9520. false, false)
  9521. != Sema::Compatible) {
  9522. S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
  9523. << ElementType << ElementKind << TargetElementType
  9524. << Element->getSourceRange();
  9525. }
  9526. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  9527. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  9528. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  9529. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  9530. }
  9531. /// Check an Objective-C array literal being converted to the given
  9532. /// target type.
  9533. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9534. ObjCArrayLiteral *ArrayLiteral) {
  9535. if (!S.NSArrayDecl)
  9536. return;
  9537. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9538. if (!TargetObjCPtr)
  9539. return;
  9540. if (TargetObjCPtr->isUnspecialized() ||
  9541. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9542. != S.NSArrayDecl->getCanonicalDecl())
  9543. return;
  9544. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9545. if (TypeArgs.size() != 1)
  9546. return;
  9547. QualType TargetElementType = TypeArgs[0];
  9548. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  9549. checkObjCCollectionLiteralElement(S, TargetElementType,
  9550. ArrayLiteral->getElement(I),
  9551. 0);
  9552. }
  9553. }
  9554. /// Check an Objective-C dictionary literal being converted to the given
  9555. /// target type.
  9556. static void
  9557. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9558. ObjCDictionaryLiteral *DictionaryLiteral) {
  9559. if (!S.NSDictionaryDecl)
  9560. return;
  9561. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9562. if (!TargetObjCPtr)
  9563. return;
  9564. if (TargetObjCPtr->isUnspecialized() ||
  9565. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9566. != S.NSDictionaryDecl->getCanonicalDecl())
  9567. return;
  9568. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9569. if (TypeArgs.size() != 2)
  9570. return;
  9571. QualType TargetKeyType = TypeArgs[0];
  9572. QualType TargetObjectType = TypeArgs[1];
  9573. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  9574. auto Element = DictionaryLiteral->getKeyValueElement(I);
  9575. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  9576. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  9577. }
  9578. }
  9579. // Helper function to filter out cases for constant width constant conversion.
  9580. // Don't warn on char array initialization or for non-decimal values.
  9581. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  9582. SourceLocation CC) {
  9583. // If initializing from a constant, and the constant starts with '0',
  9584. // then it is a binary, octal, or hexadecimal. Allow these constants
  9585. // to fill all the bits, even if there is a sign change.
  9586. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  9587. const char FirstLiteralCharacter =
  9588. S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
  9589. if (FirstLiteralCharacter == '0')
  9590. return false;
  9591. }
  9592. // If the CC location points to a '{', and the type is char, then assume
  9593. // assume it is an array initialization.
  9594. if (CC.isValid() && T->isCharType()) {
  9595. const char FirstContextCharacter =
  9596. S.getSourceManager().getCharacterData(CC)[0];
  9597. if (FirstContextCharacter == '{')
  9598. return false;
  9599. }
  9600. return true;
  9601. }
  9602. static void
  9603. CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
  9604. bool *ICContext = nullptr) {
  9605. if (E->isTypeDependent() || E->isValueDependent()) return;
  9606. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  9607. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  9608. if (Source == Target) return;
  9609. if (Target->isDependentType()) return;
  9610. // If the conversion context location is invalid don't complain. We also
  9611. // don't want to emit a warning if the issue occurs from the expansion of
  9612. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  9613. // delay this check as long as possible. Once we detect we are in that
  9614. // scenario, we just return.
  9615. if (CC.isInvalid())
  9616. return;
  9617. if (Source->isAtomicType())
  9618. S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
  9619. // Diagnose implicit casts to bool.
  9620. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  9621. if (isa<StringLiteral>(E))
  9622. // Warn on string literal to bool. Checks for string literals in logical
  9623. // and expressions, for instance, assert(0 && "error here"), are
  9624. // prevented by a check in AnalyzeImplicitConversions().
  9625. return DiagnoseImpCast(S, E, T, CC,
  9626. diag::warn_impcast_string_literal_to_bool);
  9627. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  9628. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  9629. // This covers the literal expressions that evaluate to Objective-C
  9630. // objects.
  9631. return DiagnoseImpCast(S, E, T, CC,
  9632. diag::warn_impcast_objective_c_literal_to_bool);
  9633. }
  9634. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  9635. // Warn on pointer to bool conversion that is always true.
  9636. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  9637. SourceRange(CC));
  9638. }
  9639. }
  9640. // Check implicit casts from Objective-C collection literals to specialized
  9641. // collection types, e.g., NSArray<NSString *> *.
  9642. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  9643. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  9644. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  9645. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  9646. // Strip vector types.
  9647. if (isa<VectorType>(Source)) {
  9648. if (!isa<VectorType>(Target)) {
  9649. if (S.SourceMgr.isInSystemMacro(CC))
  9650. return;
  9651. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  9652. }
  9653. // If the vector cast is cast between two vectors of the same size, it is
  9654. // a bitcast, not a conversion.
  9655. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  9656. return;
  9657. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  9658. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  9659. }
  9660. if (auto VecTy = dyn_cast<VectorType>(Target))
  9661. Target = VecTy->getElementType().getTypePtr();
  9662. // Strip complex types.
  9663. if (isa<ComplexType>(Source)) {
  9664. if (!isa<ComplexType>(Target)) {
  9665. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  9666. return;
  9667. return DiagnoseImpCast(S, E, T, CC,
  9668. S.getLangOpts().CPlusPlus
  9669. ? diag::err_impcast_complex_scalar
  9670. : diag::warn_impcast_complex_scalar);
  9671. }
  9672. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  9673. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  9674. }
  9675. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  9676. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  9677. // If the source is floating point...
  9678. if (SourceBT && SourceBT->isFloatingPoint()) {
  9679. // ...and the target is floating point...
  9680. if (TargetBT && TargetBT->isFloatingPoint()) {
  9681. // ...then warn if we're dropping FP rank.
  9682. // Builtin FP kinds are ordered by increasing FP rank.
  9683. if (SourceBT->getKind() > TargetBT->getKind()) {
  9684. // Don't warn about float constants that are precisely
  9685. // representable in the target type.
  9686. Expr::EvalResult result;
  9687. if (E->EvaluateAsRValue(result, S.Context)) {
  9688. // Value might be a float, a float vector, or a float complex.
  9689. if (IsSameFloatAfterCast(result.Val,
  9690. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  9691. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  9692. return;
  9693. }
  9694. if (S.SourceMgr.isInSystemMacro(CC))
  9695. return;
  9696. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  9697. }
  9698. // ... or possibly if we're increasing rank, too
  9699. else if (TargetBT->getKind() > SourceBT->getKind()) {
  9700. if (S.SourceMgr.isInSystemMacro(CC))
  9701. return;
  9702. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  9703. }
  9704. return;
  9705. }
  9706. // If the target is integral, always warn.
  9707. if (TargetBT && TargetBT->isInteger()) {
  9708. if (S.SourceMgr.isInSystemMacro(CC))
  9709. return;
  9710. DiagnoseFloatingImpCast(S, E, T, CC);
  9711. }
  9712. // Detect the case where a call result is converted from floating-point to
  9713. // to bool, and the final argument to the call is converted from bool, to
  9714. // discover this typo:
  9715. //
  9716. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  9717. //
  9718. // FIXME: This is an incredibly special case; is there some more general
  9719. // way to detect this class of misplaced-parentheses bug?
  9720. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  9721. // Check last argument of function call to see if it is an
  9722. // implicit cast from a type matching the type the result
  9723. // is being cast to.
  9724. CallExpr *CEx = cast<CallExpr>(E);
  9725. if (unsigned NumArgs = CEx->getNumArgs()) {
  9726. Expr *LastA = CEx->getArg(NumArgs - 1);
  9727. Expr *InnerE = LastA->IgnoreParenImpCasts();
  9728. if (isa<ImplicitCastExpr>(LastA) &&
  9729. InnerE->getType()->isBooleanType()) {
  9730. // Warn on this floating-point to bool conversion
  9731. DiagnoseImpCast(S, E, T, CC,
  9732. diag::warn_impcast_floating_point_to_bool);
  9733. }
  9734. }
  9735. }
  9736. return;
  9737. }
  9738. DiagnoseNullConversion(S, E, T, CC);
  9739. S.DiscardMisalignedMemberAddress(Target, E);
  9740. if (!Source->isIntegerType() || !Target->isIntegerType())
  9741. return;
  9742. // TODO: remove this early return once the false positives for constant->bool
  9743. // in templates, macros, etc, are reduced or removed.
  9744. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  9745. return;
  9746. IntRange SourceRange = GetExprRange(S.Context, E);
  9747. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  9748. if (SourceRange.Width > TargetRange.Width) {
  9749. // If the source is a constant, use a default-on diagnostic.
  9750. // TODO: this should happen for bitfield stores, too.
  9751. llvm::APSInt Value(32);
  9752. if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
  9753. if (S.SourceMgr.isInSystemMacro(CC))
  9754. return;
  9755. std::string PrettySourceValue = Value.toString(10);
  9756. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  9757. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9758. S.PDiag(diag::warn_impcast_integer_precision_constant)
  9759. << PrettySourceValue << PrettyTargetValue
  9760. << E->getType() << T << E->getSourceRange()
  9761. << clang::SourceRange(CC));
  9762. return;
  9763. }
  9764. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  9765. if (S.SourceMgr.isInSystemMacro(CC))
  9766. return;
  9767. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  9768. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  9769. /* pruneControlFlow */ true);
  9770. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  9771. }
  9772. if (TargetRange.Width > SourceRange.Width) {
  9773. if (auto *UO = dyn_cast<UnaryOperator>(E))
  9774. if (UO->getOpcode() == UO_Minus)
  9775. if (Source->isUnsignedIntegerType()) {
  9776. if (Target->isUnsignedIntegerType())
  9777. return DiagnoseImpCast(S, E, T, CC,
  9778. diag::warn_impcast_high_order_zero_bits);
  9779. if (Target->isSignedIntegerType())
  9780. return DiagnoseImpCast(S, E, T, CC,
  9781. diag::warn_impcast_nonnegative_result);
  9782. }
  9783. }
  9784. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  9785. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  9786. // Warn when doing a signed to signed conversion, warn if the positive
  9787. // source value is exactly the width of the target type, which will
  9788. // cause a negative value to be stored.
  9789. llvm::APSInt Value;
  9790. if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
  9791. !S.SourceMgr.isInSystemMacro(CC)) {
  9792. if (isSameWidthConstantConversion(S, E, T, CC)) {
  9793. std::string PrettySourceValue = Value.toString(10);
  9794. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  9795. S.DiagRuntimeBehavior(
  9796. E->getExprLoc(), E,
  9797. S.PDiag(diag::warn_impcast_integer_precision_constant)
  9798. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  9799. << E->getSourceRange() << clang::SourceRange(CC));
  9800. return;
  9801. }
  9802. }
  9803. // Fall through for non-constants to give a sign conversion warning.
  9804. }
  9805. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  9806. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  9807. SourceRange.Width == TargetRange.Width)) {
  9808. if (S.SourceMgr.isInSystemMacro(CC))
  9809. return;
  9810. unsigned DiagID = diag::warn_impcast_integer_sign;
  9811. // Traditionally, gcc has warned about this under -Wsign-compare.
  9812. // We also want to warn about it in -Wconversion.
  9813. // So if -Wconversion is off, use a completely identical diagnostic
  9814. // in the sign-compare group.
  9815. // The conditional-checking code will
  9816. if (ICContext) {
  9817. DiagID = diag::warn_impcast_integer_sign_conditional;
  9818. *ICContext = true;
  9819. }
  9820. return DiagnoseImpCast(S, E, T, CC, DiagID);
  9821. }
  9822. // Diagnose conversions between different enumeration types.
  9823. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  9824. // type, to give us better diagnostics.
  9825. QualType SourceType = E->getType();
  9826. if (!S.getLangOpts().CPlusPlus) {
  9827. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  9828. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  9829. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  9830. SourceType = S.Context.getTypeDeclType(Enum);
  9831. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  9832. }
  9833. }
  9834. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  9835. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  9836. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  9837. TargetEnum->getDecl()->hasNameForLinkage() &&
  9838. SourceEnum != TargetEnum) {
  9839. if (S.SourceMgr.isInSystemMacro(CC))
  9840. return;
  9841. return DiagnoseImpCast(S, E, SourceType, T, CC,
  9842. diag::warn_impcast_different_enum_types);
  9843. }
  9844. }
  9845. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  9846. SourceLocation CC, QualType T);
  9847. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  9848. SourceLocation CC, bool &ICContext) {
  9849. E = E->IgnoreParenImpCasts();
  9850. if (isa<ConditionalOperator>(E))
  9851. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  9852. AnalyzeImplicitConversions(S, E, CC);
  9853. if (E->getType() != T)
  9854. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  9855. }
  9856. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  9857. SourceLocation CC, QualType T) {
  9858. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  9859. bool Suspicious = false;
  9860. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  9861. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  9862. // If -Wconversion would have warned about either of the candidates
  9863. // for a signedness conversion to the context type...
  9864. if (!Suspicious) return;
  9865. // ...but it's currently ignored...
  9866. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  9867. return;
  9868. // ...then check whether it would have warned about either of the
  9869. // candidates for a signedness conversion to the condition type.
  9870. if (E->getType() == T) return;
  9871. Suspicious = false;
  9872. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  9873. E->getType(), CC, &Suspicious);
  9874. if (!Suspicious)
  9875. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  9876. E->getType(), CC, &Suspicious);
  9877. }
  9878. /// Check conversion of given expression to boolean.
  9879. /// Input argument E is a logical expression.
  9880. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  9881. if (S.getLangOpts().Bool)
  9882. return;
  9883. if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
  9884. return;
  9885. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  9886. }
  9887. /// AnalyzeImplicitConversions - Find and report any interesting
  9888. /// implicit conversions in the given expression. There are a couple
  9889. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  9890. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
  9891. SourceLocation CC) {
  9892. QualType T = OrigE->getType();
  9893. Expr *E = OrigE->IgnoreParenImpCasts();
  9894. if (E->isTypeDependent() || E->isValueDependent())
  9895. return;
  9896. // For conditional operators, we analyze the arguments as if they
  9897. // were being fed directly into the output.
  9898. if (isa<ConditionalOperator>(E)) {
  9899. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  9900. CheckConditionalOperator(S, CO, CC, T);
  9901. return;
  9902. }
  9903. // Check implicit argument conversions for function calls.
  9904. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  9905. CheckImplicitArgumentConversions(S, Call, CC);
  9906. // Go ahead and check any implicit conversions we might have skipped.
  9907. // The non-canonical typecheck is just an optimization;
  9908. // CheckImplicitConversion will filter out dead implicit conversions.
  9909. if (E->getType() != T)
  9910. CheckImplicitConversion(S, E, T, CC);
  9911. // Now continue drilling into this expression.
  9912. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  9913. // The bound subexpressions in a PseudoObjectExpr are not reachable
  9914. // as transitive children.
  9915. // FIXME: Use a more uniform representation for this.
  9916. for (auto *SE : POE->semantics())
  9917. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  9918. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  9919. }
  9920. // Skip past explicit casts.
  9921. if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
  9922. E = CE->getSubExpr()->IgnoreParenImpCasts();
  9923. if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
  9924. S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  9925. return AnalyzeImplicitConversions(S, E, CC);
  9926. }
  9927. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9928. // Do a somewhat different check with comparison operators.
  9929. if (BO->isComparisonOp())
  9930. return AnalyzeComparison(S, BO);
  9931. // And with simple assignments.
  9932. if (BO->getOpcode() == BO_Assign)
  9933. return AnalyzeAssignment(S, BO);
  9934. // And with compound assignments.
  9935. if (BO->isAssignmentOp())
  9936. return AnalyzeCompoundAssignment(S, BO);
  9937. }
  9938. // These break the otherwise-useful invariant below. Fortunately,
  9939. // we don't really need to recurse into them, because any internal
  9940. // expressions should have been analyzed already when they were
  9941. // built into statements.
  9942. if (isa<StmtExpr>(E)) return;
  9943. // Don't descend into unevaluated contexts.
  9944. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  9945. // Now just recurse over the expression's children.
  9946. CC = E->getExprLoc();
  9947. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  9948. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  9949. for (Stmt *SubStmt : E->children()) {
  9950. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  9951. if (!ChildExpr)
  9952. continue;
  9953. if (IsLogicalAndOperator &&
  9954. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  9955. // Ignore checking string literals that are in logical and operators.
  9956. // This is a common pattern for asserts.
  9957. continue;
  9958. AnalyzeImplicitConversions(S, ChildExpr, CC);
  9959. }
  9960. if (BO && BO->isLogicalOp()) {
  9961. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  9962. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  9963. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  9964. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  9965. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  9966. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  9967. }
  9968. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  9969. if (U->getOpcode() == UO_LNot) {
  9970. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  9971. } else if (U->getOpcode() != UO_AddrOf) {
  9972. if (U->getSubExpr()->getType()->isAtomicType())
  9973. S.Diag(U->getSubExpr()->getBeginLoc(),
  9974. diag::warn_atomic_implicit_seq_cst);
  9975. }
  9976. }
  9977. }
  9978. /// Diagnose integer type and any valid implicit conversion to it.
  9979. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  9980. // Taking into account implicit conversions,
  9981. // allow any integer.
  9982. if (!E->getType()->isIntegerType()) {
  9983. S.Diag(E->getBeginLoc(),
  9984. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  9985. return true;
  9986. }
  9987. // Potentially emit standard warnings for implicit conversions if enabled
  9988. // using -Wconversion.
  9989. CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
  9990. return false;
  9991. }
  9992. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  9993. // Returns true when emitting a warning about taking the address of a reference.
  9994. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  9995. const PartialDiagnostic &PD) {
  9996. E = E->IgnoreParenImpCasts();
  9997. const FunctionDecl *FD = nullptr;
  9998. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9999. if (!DRE->getDecl()->getType()->isReferenceType())
  10000. return false;
  10001. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10002. if (!M->getMemberDecl()->getType()->isReferenceType())
  10003. return false;
  10004. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  10005. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  10006. return false;
  10007. FD = Call->getDirectCallee();
  10008. } else {
  10009. return false;
  10010. }
  10011. SemaRef.Diag(E->getExprLoc(), PD);
  10012. // If possible, point to location of function.
  10013. if (FD) {
  10014. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  10015. }
  10016. return true;
  10017. }
  10018. // Returns true if the SourceLocation is expanded from any macro body.
  10019. // Returns false if the SourceLocation is invalid, is from not in a macro
  10020. // expansion, or is from expanded from a top-level macro argument.
  10021. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  10022. if (Loc.isInvalid())
  10023. return false;
  10024. while (Loc.isMacroID()) {
  10025. if (SM.isMacroBodyExpansion(Loc))
  10026. return true;
  10027. Loc = SM.getImmediateMacroCallerLoc(Loc);
  10028. }
  10029. return false;
  10030. }
  10031. /// Diagnose pointers that are always non-null.
  10032. /// \param E the expression containing the pointer
  10033. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  10034. /// compared to a null pointer
  10035. /// \param IsEqual True when the comparison is equal to a null pointer
  10036. /// \param Range Extra SourceRange to highlight in the diagnostic
  10037. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  10038. Expr::NullPointerConstantKind NullKind,
  10039. bool IsEqual, SourceRange Range) {
  10040. if (!E)
  10041. return;
  10042. // Don't warn inside macros.
  10043. if (E->getExprLoc().isMacroID()) {
  10044. const SourceManager &SM = getSourceManager();
  10045. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  10046. IsInAnyMacroBody(SM, Range.getBegin()))
  10047. return;
  10048. }
  10049. E = E->IgnoreImpCasts();
  10050. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  10051. if (isa<CXXThisExpr>(E)) {
  10052. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  10053. : diag::warn_this_bool_conversion;
  10054. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  10055. return;
  10056. }
  10057. bool IsAddressOf = false;
  10058. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10059. if (UO->getOpcode() != UO_AddrOf)
  10060. return;
  10061. IsAddressOf = true;
  10062. E = UO->getSubExpr();
  10063. }
  10064. if (IsAddressOf) {
  10065. unsigned DiagID = IsCompare
  10066. ? diag::warn_address_of_reference_null_compare
  10067. : diag::warn_address_of_reference_bool_conversion;
  10068. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  10069. << IsEqual;
  10070. if (CheckForReference(*this, E, PD)) {
  10071. return;
  10072. }
  10073. }
  10074. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  10075. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  10076. std::string Str;
  10077. llvm::raw_string_ostream S(Str);
  10078. E->printPretty(S, nullptr, getPrintingPolicy());
  10079. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  10080. : diag::warn_cast_nonnull_to_bool;
  10081. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  10082. << E->getSourceRange() << Range << IsEqual;
  10083. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  10084. };
  10085. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  10086. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  10087. if (auto *Callee = Call->getDirectCallee()) {
  10088. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  10089. ComplainAboutNonnullParamOrCall(A);
  10090. return;
  10091. }
  10092. }
  10093. }
  10094. // Expect to find a single Decl. Skip anything more complicated.
  10095. ValueDecl *D = nullptr;
  10096. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  10097. D = R->getDecl();
  10098. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10099. D = M->getMemberDecl();
  10100. }
  10101. // Weak Decls can be null.
  10102. if (!D || D->isWeak())
  10103. return;
  10104. // Check for parameter decl with nonnull attribute
  10105. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  10106. if (getCurFunction() &&
  10107. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  10108. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  10109. ComplainAboutNonnullParamOrCall(A);
  10110. return;
  10111. }
  10112. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  10113. auto ParamIter = llvm::find(FD->parameters(), PV);
  10114. assert(ParamIter != FD->param_end());
  10115. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  10116. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  10117. if (!NonNull->args_size()) {
  10118. ComplainAboutNonnullParamOrCall(NonNull);
  10119. return;
  10120. }
  10121. for (const ParamIdx &ArgNo : NonNull->args()) {
  10122. if (ArgNo.getASTIndex() == ParamNo) {
  10123. ComplainAboutNonnullParamOrCall(NonNull);
  10124. return;
  10125. }
  10126. }
  10127. }
  10128. }
  10129. }
  10130. }
  10131. QualType T = D->getType();
  10132. const bool IsArray = T->isArrayType();
  10133. const bool IsFunction = T->isFunctionType();
  10134. // Address of function is used to silence the function warning.
  10135. if (IsAddressOf && IsFunction) {
  10136. return;
  10137. }
  10138. // Found nothing.
  10139. if (!IsAddressOf && !IsFunction && !IsArray)
  10140. return;
  10141. // Pretty print the expression for the diagnostic.
  10142. std::string Str;
  10143. llvm::raw_string_ostream S(Str);
  10144. E->printPretty(S, nullptr, getPrintingPolicy());
  10145. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  10146. : diag::warn_impcast_pointer_to_bool;
  10147. enum {
  10148. AddressOf,
  10149. FunctionPointer,
  10150. ArrayPointer
  10151. } DiagType;
  10152. if (IsAddressOf)
  10153. DiagType = AddressOf;
  10154. else if (IsFunction)
  10155. DiagType = FunctionPointer;
  10156. else if (IsArray)
  10157. DiagType = ArrayPointer;
  10158. else
  10159. llvm_unreachable("Could not determine diagnostic.");
  10160. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  10161. << Range << IsEqual;
  10162. if (!IsFunction)
  10163. return;
  10164. // Suggest '&' to silence the function warning.
  10165. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  10166. << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
  10167. // Check to see if '()' fixit should be emitted.
  10168. QualType ReturnType;
  10169. UnresolvedSet<4> NonTemplateOverloads;
  10170. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  10171. if (ReturnType.isNull())
  10172. return;
  10173. if (IsCompare) {
  10174. // There are two cases here. If there is null constant, the only suggest
  10175. // for a pointer return type. If the null is 0, then suggest if the return
  10176. // type is a pointer or an integer type.
  10177. if (!ReturnType->isPointerType()) {
  10178. if (NullKind == Expr::NPCK_ZeroExpression ||
  10179. NullKind == Expr::NPCK_ZeroLiteral) {
  10180. if (!ReturnType->isIntegerType())
  10181. return;
  10182. } else {
  10183. return;
  10184. }
  10185. }
  10186. } else { // !IsCompare
  10187. // For function to bool, only suggest if the function pointer has bool
  10188. // return type.
  10189. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  10190. return;
  10191. }
  10192. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  10193. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
  10194. }
  10195. /// Diagnoses "dangerous" implicit conversions within the given
  10196. /// expression (which is a full expression). Implements -Wconversion
  10197. /// and -Wsign-compare.
  10198. ///
  10199. /// \param CC the "context" location of the implicit conversion, i.e.
  10200. /// the most location of the syntactic entity requiring the implicit
  10201. /// conversion
  10202. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  10203. // Don't diagnose in unevaluated contexts.
  10204. if (isUnevaluatedContext())
  10205. return;
  10206. // Don't diagnose for value- or type-dependent expressions.
  10207. if (E->isTypeDependent() || E->isValueDependent())
  10208. return;
  10209. // Check for array bounds violations in cases where the check isn't triggered
  10210. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  10211. // ArraySubscriptExpr is on the RHS of a variable initialization.
  10212. CheckArrayAccess(E);
  10213. // This is not the right CC for (e.g.) a variable initialization.
  10214. AnalyzeImplicitConversions(*this, E, CC);
  10215. }
  10216. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  10217. /// Input argument E is a logical expression.
  10218. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  10219. ::CheckBoolLikeConversion(*this, E, CC);
  10220. }
  10221. /// Diagnose when expression is an integer constant expression and its evaluation
  10222. /// results in integer overflow
  10223. void Sema::CheckForIntOverflow (Expr *E) {
  10224. // Use a work list to deal with nested struct initializers.
  10225. SmallVector<Expr *, 2> Exprs(1, E);
  10226. do {
  10227. Expr *OriginalE = Exprs.pop_back_val();
  10228. Expr *E = OriginalE->IgnoreParenCasts();
  10229. if (isa<BinaryOperator>(E)) {
  10230. E->EvaluateForOverflow(Context);
  10231. continue;
  10232. }
  10233. if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
  10234. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  10235. else if (isa<ObjCBoxedExpr>(OriginalE))
  10236. E->EvaluateForOverflow(Context);
  10237. else if (auto Call = dyn_cast<CallExpr>(E))
  10238. Exprs.append(Call->arg_begin(), Call->arg_end());
  10239. else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
  10240. Exprs.append(Message->arg_begin(), Message->arg_end());
  10241. } while (!Exprs.empty());
  10242. }
  10243. namespace {
  10244. /// Visitor for expressions which looks for unsequenced operations on the
  10245. /// same object.
  10246. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  10247. using Base = EvaluatedExprVisitor<SequenceChecker>;
  10248. /// A tree of sequenced regions within an expression. Two regions are
  10249. /// unsequenced if one is an ancestor or a descendent of the other. When we
  10250. /// finish processing an expression with sequencing, such as a comma
  10251. /// expression, we fold its tree nodes into its parent, since they are
  10252. /// unsequenced with respect to nodes we will visit later.
  10253. class SequenceTree {
  10254. struct Value {
  10255. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  10256. unsigned Parent : 31;
  10257. unsigned Merged : 1;
  10258. };
  10259. SmallVector<Value, 8> Values;
  10260. public:
  10261. /// A region within an expression which may be sequenced with respect
  10262. /// to some other region.
  10263. class Seq {
  10264. friend class SequenceTree;
  10265. unsigned Index = 0;
  10266. explicit Seq(unsigned N) : Index(N) {}
  10267. public:
  10268. Seq() = default;
  10269. };
  10270. SequenceTree() { Values.push_back(Value(0)); }
  10271. Seq root() const { return Seq(0); }
  10272. /// Create a new sequence of operations, which is an unsequenced
  10273. /// subset of \p Parent. This sequence of operations is sequenced with
  10274. /// respect to other children of \p Parent.
  10275. Seq allocate(Seq Parent) {
  10276. Values.push_back(Value(Parent.Index));
  10277. return Seq(Values.size() - 1);
  10278. }
  10279. /// Merge a sequence of operations into its parent.
  10280. void merge(Seq S) {
  10281. Values[S.Index].Merged = true;
  10282. }
  10283. /// Determine whether two operations are unsequenced. This operation
  10284. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  10285. /// should have been merged into its parent as appropriate.
  10286. bool isUnsequenced(Seq Cur, Seq Old) {
  10287. unsigned C = representative(Cur.Index);
  10288. unsigned Target = representative(Old.Index);
  10289. while (C >= Target) {
  10290. if (C == Target)
  10291. return true;
  10292. C = Values[C].Parent;
  10293. }
  10294. return false;
  10295. }
  10296. private:
  10297. /// Pick a representative for a sequence.
  10298. unsigned representative(unsigned K) {
  10299. if (Values[K].Merged)
  10300. // Perform path compression as we go.
  10301. return Values[K].Parent = representative(Values[K].Parent);
  10302. return K;
  10303. }
  10304. };
  10305. /// An object for which we can track unsequenced uses.
  10306. using Object = NamedDecl *;
  10307. /// Different flavors of object usage which we track. We only track the
  10308. /// least-sequenced usage of each kind.
  10309. enum UsageKind {
  10310. /// A read of an object. Multiple unsequenced reads are OK.
  10311. UK_Use,
  10312. /// A modification of an object which is sequenced before the value
  10313. /// computation of the expression, such as ++n in C++.
  10314. UK_ModAsValue,
  10315. /// A modification of an object which is not sequenced before the value
  10316. /// computation of the expression, such as n++.
  10317. UK_ModAsSideEffect,
  10318. UK_Count = UK_ModAsSideEffect + 1
  10319. };
  10320. struct Usage {
  10321. Expr *Use = nullptr;
  10322. SequenceTree::Seq Seq;
  10323. Usage() = default;
  10324. };
  10325. struct UsageInfo {
  10326. Usage Uses[UK_Count];
  10327. /// Have we issued a diagnostic for this variable already?
  10328. bool Diagnosed = false;
  10329. UsageInfo() = default;
  10330. };
  10331. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  10332. Sema &SemaRef;
  10333. /// Sequenced regions within the expression.
  10334. SequenceTree Tree;
  10335. /// Declaration modifications and references which we have seen.
  10336. UsageInfoMap UsageMap;
  10337. /// The region we are currently within.
  10338. SequenceTree::Seq Region;
  10339. /// Filled in with declarations which were modified as a side-effect
  10340. /// (that is, post-increment operations).
  10341. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  10342. /// Expressions to check later. We defer checking these to reduce
  10343. /// stack usage.
  10344. SmallVectorImpl<Expr *> &WorkList;
  10345. /// RAII object wrapping the visitation of a sequenced subexpression of an
  10346. /// expression. At the end of this process, the side-effects of the evaluation
  10347. /// become sequenced with respect to the value computation of the result, so
  10348. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  10349. /// UK_ModAsValue.
  10350. struct SequencedSubexpression {
  10351. SequencedSubexpression(SequenceChecker &Self)
  10352. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  10353. Self.ModAsSideEffect = &ModAsSideEffect;
  10354. }
  10355. ~SequencedSubexpression() {
  10356. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  10357. UsageInfo &U = Self.UsageMap[M.first];
  10358. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  10359. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  10360. SideEffectUsage = M.second;
  10361. }
  10362. Self.ModAsSideEffect = OldModAsSideEffect;
  10363. }
  10364. SequenceChecker &Self;
  10365. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  10366. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  10367. };
  10368. /// RAII object wrapping the visitation of a subexpression which we might
  10369. /// choose to evaluate as a constant. If any subexpression is evaluated and
  10370. /// found to be non-constant, this allows us to suppress the evaluation of
  10371. /// the outer expression.
  10372. class EvaluationTracker {
  10373. public:
  10374. EvaluationTracker(SequenceChecker &Self)
  10375. : Self(Self), Prev(Self.EvalTracker) {
  10376. Self.EvalTracker = this;
  10377. }
  10378. ~EvaluationTracker() {
  10379. Self.EvalTracker = Prev;
  10380. if (Prev)
  10381. Prev->EvalOK &= EvalOK;
  10382. }
  10383. bool evaluate(const Expr *E, bool &Result) {
  10384. if (!EvalOK || E->isValueDependent())
  10385. return false;
  10386. EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
  10387. return EvalOK;
  10388. }
  10389. private:
  10390. SequenceChecker &Self;
  10391. EvaluationTracker *Prev;
  10392. bool EvalOK = true;
  10393. } *EvalTracker = nullptr;
  10394. /// Find the object which is produced by the specified expression,
  10395. /// if any.
  10396. Object getObject(Expr *E, bool Mod) const {
  10397. E = E->IgnoreParenCasts();
  10398. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10399. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  10400. return getObject(UO->getSubExpr(), Mod);
  10401. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10402. if (BO->getOpcode() == BO_Comma)
  10403. return getObject(BO->getRHS(), Mod);
  10404. if (Mod && BO->isAssignmentOp())
  10405. return getObject(BO->getLHS(), Mod);
  10406. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  10407. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  10408. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  10409. return ME->getMemberDecl();
  10410. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10411. // FIXME: If this is a reference, map through to its value.
  10412. return DRE->getDecl();
  10413. return nullptr;
  10414. }
  10415. /// Note that an object was modified or used by an expression.
  10416. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  10417. Usage &U = UI.Uses[UK];
  10418. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  10419. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  10420. ModAsSideEffect->push_back(std::make_pair(O, U));
  10421. U.Use = Ref;
  10422. U.Seq = Region;
  10423. }
  10424. }
  10425. /// Check whether a modification or use conflicts with a prior usage.
  10426. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  10427. bool IsModMod) {
  10428. if (UI.Diagnosed)
  10429. return;
  10430. const Usage &U = UI.Uses[OtherKind];
  10431. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  10432. return;
  10433. Expr *Mod = U.Use;
  10434. Expr *ModOrUse = Ref;
  10435. if (OtherKind == UK_Use)
  10436. std::swap(Mod, ModOrUse);
  10437. SemaRef.Diag(Mod->getExprLoc(),
  10438. IsModMod ? diag::warn_unsequenced_mod_mod
  10439. : diag::warn_unsequenced_mod_use)
  10440. << O << SourceRange(ModOrUse->getExprLoc());
  10441. UI.Diagnosed = true;
  10442. }
  10443. void notePreUse(Object O, Expr *Use) {
  10444. UsageInfo &U = UsageMap[O];
  10445. // Uses conflict with other modifications.
  10446. checkUsage(O, U, Use, UK_ModAsValue, false);
  10447. }
  10448. void notePostUse(Object O, Expr *Use) {
  10449. UsageInfo &U = UsageMap[O];
  10450. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  10451. addUsage(U, O, Use, UK_Use);
  10452. }
  10453. void notePreMod(Object O, Expr *Mod) {
  10454. UsageInfo &U = UsageMap[O];
  10455. // Modifications conflict with other modifications and with uses.
  10456. checkUsage(O, U, Mod, UK_ModAsValue, true);
  10457. checkUsage(O, U, Mod, UK_Use, false);
  10458. }
  10459. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  10460. UsageInfo &U = UsageMap[O];
  10461. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  10462. addUsage(U, O, Use, UK);
  10463. }
  10464. public:
  10465. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  10466. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  10467. Visit(E);
  10468. }
  10469. void VisitStmt(Stmt *S) {
  10470. // Skip all statements which aren't expressions for now.
  10471. }
  10472. void VisitExpr(Expr *E) {
  10473. // By default, just recurse to evaluated subexpressions.
  10474. Base::VisitStmt(E);
  10475. }
  10476. void VisitCastExpr(CastExpr *E) {
  10477. Object O = Object();
  10478. if (E->getCastKind() == CK_LValueToRValue)
  10479. O = getObject(E->getSubExpr(), false);
  10480. if (O)
  10481. notePreUse(O, E);
  10482. VisitExpr(E);
  10483. if (O)
  10484. notePostUse(O, E);
  10485. }
  10486. void VisitBinComma(BinaryOperator *BO) {
  10487. // C++11 [expr.comma]p1:
  10488. // Every value computation and side effect associated with the left
  10489. // expression is sequenced before every value computation and side
  10490. // effect associated with the right expression.
  10491. SequenceTree::Seq LHS = Tree.allocate(Region);
  10492. SequenceTree::Seq RHS = Tree.allocate(Region);
  10493. SequenceTree::Seq OldRegion = Region;
  10494. {
  10495. SequencedSubexpression SeqLHS(*this);
  10496. Region = LHS;
  10497. Visit(BO->getLHS());
  10498. }
  10499. Region = RHS;
  10500. Visit(BO->getRHS());
  10501. Region = OldRegion;
  10502. // Forget that LHS and RHS are sequenced. They are both unsequenced
  10503. // with respect to other stuff.
  10504. Tree.merge(LHS);
  10505. Tree.merge(RHS);
  10506. }
  10507. void VisitBinAssign(BinaryOperator *BO) {
  10508. // The modification is sequenced after the value computation of the LHS
  10509. // and RHS, so check it before inspecting the operands and update the
  10510. // map afterwards.
  10511. Object O = getObject(BO->getLHS(), true);
  10512. if (!O)
  10513. return VisitExpr(BO);
  10514. notePreMod(O, BO);
  10515. // C++11 [expr.ass]p7:
  10516. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  10517. // only once.
  10518. //
  10519. // Therefore, for a compound assignment operator, O is considered used
  10520. // everywhere except within the evaluation of E1 itself.
  10521. if (isa<CompoundAssignOperator>(BO))
  10522. notePreUse(O, BO);
  10523. Visit(BO->getLHS());
  10524. if (isa<CompoundAssignOperator>(BO))
  10525. notePostUse(O, BO);
  10526. Visit(BO->getRHS());
  10527. // C++11 [expr.ass]p1:
  10528. // the assignment is sequenced [...] before the value computation of the
  10529. // assignment expression.
  10530. // C11 6.5.16/3 has no such rule.
  10531. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  10532. : UK_ModAsSideEffect);
  10533. }
  10534. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  10535. VisitBinAssign(CAO);
  10536. }
  10537. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10538. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10539. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  10540. Object O = getObject(UO->getSubExpr(), true);
  10541. if (!O)
  10542. return VisitExpr(UO);
  10543. notePreMod(O, UO);
  10544. Visit(UO->getSubExpr());
  10545. // C++11 [expr.pre.incr]p1:
  10546. // the expression ++x is equivalent to x+=1
  10547. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  10548. : UK_ModAsSideEffect);
  10549. }
  10550. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  10551. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  10552. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  10553. Object O = getObject(UO->getSubExpr(), true);
  10554. if (!O)
  10555. return VisitExpr(UO);
  10556. notePreMod(O, UO);
  10557. Visit(UO->getSubExpr());
  10558. notePostMod(O, UO, UK_ModAsSideEffect);
  10559. }
  10560. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  10561. void VisitBinLOr(BinaryOperator *BO) {
  10562. // The side-effects of the LHS of an '&&' are sequenced before the
  10563. // value computation of the RHS, and hence before the value computation
  10564. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  10565. // as if they were unconditionally sequenced.
  10566. EvaluationTracker Eval(*this);
  10567. {
  10568. SequencedSubexpression Sequenced(*this);
  10569. Visit(BO->getLHS());
  10570. }
  10571. bool Result;
  10572. if (Eval.evaluate(BO->getLHS(), Result)) {
  10573. if (!Result)
  10574. Visit(BO->getRHS());
  10575. } else {
  10576. // Check for unsequenced operations in the RHS, treating it as an
  10577. // entirely separate evaluation.
  10578. //
  10579. // FIXME: If there are operations in the RHS which are unsequenced
  10580. // with respect to operations outside the RHS, and those operations
  10581. // are unconditionally evaluated, diagnose them.
  10582. WorkList.push_back(BO->getRHS());
  10583. }
  10584. }
  10585. void VisitBinLAnd(BinaryOperator *BO) {
  10586. EvaluationTracker Eval(*this);
  10587. {
  10588. SequencedSubexpression Sequenced(*this);
  10589. Visit(BO->getLHS());
  10590. }
  10591. bool Result;
  10592. if (Eval.evaluate(BO->getLHS(), Result)) {
  10593. if (Result)
  10594. Visit(BO->getRHS());
  10595. } else {
  10596. WorkList.push_back(BO->getRHS());
  10597. }
  10598. }
  10599. // Only visit the condition, unless we can be sure which subexpression will
  10600. // be chosen.
  10601. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  10602. EvaluationTracker Eval(*this);
  10603. {
  10604. SequencedSubexpression Sequenced(*this);
  10605. Visit(CO->getCond());
  10606. }
  10607. bool Result;
  10608. if (Eval.evaluate(CO->getCond(), Result))
  10609. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  10610. else {
  10611. WorkList.push_back(CO->getTrueExpr());
  10612. WorkList.push_back(CO->getFalseExpr());
  10613. }
  10614. }
  10615. void VisitCallExpr(CallExpr *CE) {
  10616. // C++11 [intro.execution]p15:
  10617. // When calling a function [...], every value computation and side effect
  10618. // associated with any argument expression, or with the postfix expression
  10619. // designating the called function, is sequenced before execution of every
  10620. // expression or statement in the body of the function [and thus before
  10621. // the value computation of its result].
  10622. SequencedSubexpression Sequenced(*this);
  10623. Base::VisitCallExpr(CE);
  10624. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  10625. }
  10626. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  10627. // This is a call, so all subexpressions are sequenced before the result.
  10628. SequencedSubexpression Sequenced(*this);
  10629. if (!CCE->isListInitialization())
  10630. return VisitExpr(CCE);
  10631. // In C++11, list initializations are sequenced.
  10632. SmallVector<SequenceTree::Seq, 32> Elts;
  10633. SequenceTree::Seq Parent = Region;
  10634. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  10635. E = CCE->arg_end();
  10636. I != E; ++I) {
  10637. Region = Tree.allocate(Parent);
  10638. Elts.push_back(Region);
  10639. Visit(*I);
  10640. }
  10641. // Forget that the initializers are sequenced.
  10642. Region = Parent;
  10643. for (unsigned I = 0; I < Elts.size(); ++I)
  10644. Tree.merge(Elts[I]);
  10645. }
  10646. void VisitInitListExpr(InitListExpr *ILE) {
  10647. if (!SemaRef.getLangOpts().CPlusPlus11)
  10648. return VisitExpr(ILE);
  10649. // In C++11, list initializations are sequenced.
  10650. SmallVector<SequenceTree::Seq, 32> Elts;
  10651. SequenceTree::Seq Parent = Region;
  10652. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  10653. Expr *E = ILE->getInit(I);
  10654. if (!E) continue;
  10655. Region = Tree.allocate(Parent);
  10656. Elts.push_back(Region);
  10657. Visit(E);
  10658. }
  10659. // Forget that the initializers are sequenced.
  10660. Region = Parent;
  10661. for (unsigned I = 0; I < Elts.size(); ++I)
  10662. Tree.merge(Elts[I]);
  10663. }
  10664. };
  10665. } // namespace
  10666. void Sema::CheckUnsequencedOperations(Expr *E) {
  10667. SmallVector<Expr *, 8> WorkList;
  10668. WorkList.push_back(E);
  10669. while (!WorkList.empty()) {
  10670. Expr *Item = WorkList.pop_back_val();
  10671. SequenceChecker(*this, Item, WorkList);
  10672. }
  10673. }
  10674. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  10675. bool IsConstexpr) {
  10676. CheckImplicitConversions(E, CheckLoc);
  10677. if (!E->isInstantiationDependent())
  10678. CheckUnsequencedOperations(E);
  10679. if (!IsConstexpr && !E->isValueDependent())
  10680. CheckForIntOverflow(E);
  10681. DiagnoseMisalignedMembers();
  10682. }
  10683. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  10684. FieldDecl *BitField,
  10685. Expr *Init) {
  10686. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  10687. }
  10688. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  10689. SourceLocation Loc) {
  10690. if (!PType->isVariablyModifiedType())
  10691. return;
  10692. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  10693. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  10694. return;
  10695. }
  10696. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  10697. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  10698. return;
  10699. }
  10700. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  10701. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  10702. return;
  10703. }
  10704. const ArrayType *AT = S.Context.getAsArrayType(PType);
  10705. if (!AT)
  10706. return;
  10707. if (AT->getSizeModifier() != ArrayType::Star) {
  10708. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  10709. return;
  10710. }
  10711. S.Diag(Loc, diag::err_array_star_in_function_definition);
  10712. }
  10713. /// CheckParmsForFunctionDef - Check that the parameters of the given
  10714. /// function are appropriate for the definition of a function. This
  10715. /// takes care of any checks that cannot be performed on the
  10716. /// declaration itself, e.g., that the types of each of the function
  10717. /// parameters are complete.
  10718. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  10719. bool CheckParameterNames) {
  10720. bool HasInvalidParm = false;
  10721. for (ParmVarDecl *Param : Parameters) {
  10722. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  10723. // function declarator that is part of a function definition of
  10724. // that function shall not have incomplete type.
  10725. //
  10726. // This is also C++ [dcl.fct]p6.
  10727. if (!Param->isInvalidDecl() &&
  10728. RequireCompleteType(Param->getLocation(), Param->getType(),
  10729. diag::err_typecheck_decl_incomplete_type)) {
  10730. Param->setInvalidDecl();
  10731. HasInvalidParm = true;
  10732. }
  10733. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  10734. // declaration of each parameter shall include an identifier.
  10735. if (CheckParameterNames &&
  10736. Param->getIdentifier() == nullptr &&
  10737. !Param->isImplicit() &&
  10738. !getLangOpts().CPlusPlus)
  10739. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  10740. // C99 6.7.5.3p12:
  10741. // If the function declarator is not part of a definition of that
  10742. // function, parameters may have incomplete type and may use the [*]
  10743. // notation in their sequences of declarator specifiers to specify
  10744. // variable length array types.
  10745. QualType PType = Param->getOriginalType();
  10746. // FIXME: This diagnostic should point the '[*]' if source-location
  10747. // information is added for it.
  10748. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  10749. // If the parameter is a c++ class type and it has to be destructed in the
  10750. // callee function, declare the destructor so that it can be called by the
  10751. // callee function. Do not perform any direct access check on the dtor here.
  10752. if (!Param->isInvalidDecl()) {
  10753. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  10754. if (!ClassDecl->isInvalidDecl() &&
  10755. !ClassDecl->hasIrrelevantDestructor() &&
  10756. !ClassDecl->isDependentContext() &&
  10757. ClassDecl->isParamDestroyedInCallee()) {
  10758. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  10759. MarkFunctionReferenced(Param->getLocation(), Destructor);
  10760. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  10761. }
  10762. }
  10763. }
  10764. // Parameters with the pass_object_size attribute only need to be marked
  10765. // constant at function definitions. Because we lack information about
  10766. // whether we're on a declaration or definition when we're instantiating the
  10767. // attribute, we need to check for constness here.
  10768. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  10769. if (!Param->getType().isConstQualified())
  10770. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  10771. << Attr->getSpelling() << 1;
  10772. }
  10773. return HasInvalidParm;
  10774. }
  10775. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  10776. /// or MemberExpr.
  10777. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  10778. ASTContext &Context) {
  10779. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  10780. return Context.getDeclAlign(DRE->getDecl());
  10781. if (const auto *ME = dyn_cast<MemberExpr>(E))
  10782. return Context.getDeclAlign(ME->getMemberDecl());
  10783. return TypeAlign;
  10784. }
  10785. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  10786. /// pointer cast increases the alignment requirements.
  10787. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  10788. // This is actually a lot of work to potentially be doing on every
  10789. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  10790. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  10791. return;
  10792. // Ignore dependent types.
  10793. if (T->isDependentType() || Op->getType()->isDependentType())
  10794. return;
  10795. // Require that the destination be a pointer type.
  10796. const PointerType *DestPtr = T->getAs<PointerType>();
  10797. if (!DestPtr) return;
  10798. // If the destination has alignment 1, we're done.
  10799. QualType DestPointee = DestPtr->getPointeeType();
  10800. if (DestPointee->isIncompleteType()) return;
  10801. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  10802. if (DestAlign.isOne()) return;
  10803. // Require that the source be a pointer type.
  10804. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  10805. if (!SrcPtr) return;
  10806. QualType SrcPointee = SrcPtr->getPointeeType();
  10807. // Whitelist casts from cv void*. We already implicitly
  10808. // whitelisted casts to cv void*, since they have alignment 1.
  10809. // Also whitelist casts involving incomplete types, which implicitly
  10810. // includes 'void'.
  10811. if (SrcPointee->isIncompleteType()) return;
  10812. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  10813. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  10814. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  10815. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  10816. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  10817. if (UO->getOpcode() == UO_AddrOf)
  10818. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  10819. }
  10820. if (SrcAlign >= DestAlign) return;
  10821. Diag(TRange.getBegin(), diag::warn_cast_align)
  10822. << Op->getType() << T
  10823. << static_cast<unsigned>(SrcAlign.getQuantity())
  10824. << static_cast<unsigned>(DestAlign.getQuantity())
  10825. << TRange << Op->getSourceRange();
  10826. }
  10827. /// Check whether this array fits the idiom of a size-one tail padded
  10828. /// array member of a struct.
  10829. ///
  10830. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  10831. /// commonly used to emulate flexible arrays in C89 code.
  10832. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  10833. const NamedDecl *ND) {
  10834. if (Size != 1 || !ND) return false;
  10835. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  10836. if (!FD) return false;
  10837. // Don't consider sizes resulting from macro expansions or template argument
  10838. // substitution to form C89 tail-padded arrays.
  10839. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  10840. while (TInfo) {
  10841. TypeLoc TL = TInfo->getTypeLoc();
  10842. // Look through typedefs.
  10843. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  10844. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  10845. TInfo = TDL->getTypeSourceInfo();
  10846. continue;
  10847. }
  10848. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  10849. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  10850. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  10851. return false;
  10852. }
  10853. break;
  10854. }
  10855. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  10856. if (!RD) return false;
  10857. if (RD->isUnion()) return false;
  10858. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  10859. if (!CRD->isStandardLayout()) return false;
  10860. }
  10861. // See if this is the last field decl in the record.
  10862. const Decl *D = FD;
  10863. while ((D = D->getNextDeclInContext()))
  10864. if (isa<FieldDecl>(D))
  10865. return false;
  10866. return true;
  10867. }
  10868. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  10869. const ArraySubscriptExpr *ASE,
  10870. bool AllowOnePastEnd, bool IndexNegated) {
  10871. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  10872. if (IndexExpr->isValueDependent())
  10873. return;
  10874. const Type *EffectiveType =
  10875. BaseExpr->getType()->getPointeeOrArrayElementType();
  10876. BaseExpr = BaseExpr->IgnoreParenCasts();
  10877. const ConstantArrayType *ArrayTy =
  10878. Context.getAsConstantArrayType(BaseExpr->getType());
  10879. if (!ArrayTy)
  10880. return;
  10881. llvm::APSInt index;
  10882. if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
  10883. return;
  10884. if (IndexNegated)
  10885. index = -index;
  10886. const NamedDecl *ND = nullptr;
  10887. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  10888. ND = DRE->getDecl();
  10889. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  10890. ND = ME->getMemberDecl();
  10891. if (index.isUnsigned() || !index.isNegative()) {
  10892. llvm::APInt size = ArrayTy->getSize();
  10893. if (!size.isStrictlyPositive())
  10894. return;
  10895. const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
  10896. if (BaseType != EffectiveType) {
  10897. // Make sure we're comparing apples to apples when comparing index to size
  10898. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  10899. uint64_t array_typesize = Context.getTypeSize(BaseType);
  10900. // Handle ptrarith_typesize being zero, such as when casting to void*
  10901. if (!ptrarith_typesize) ptrarith_typesize = 1;
  10902. if (ptrarith_typesize != array_typesize) {
  10903. // There's a cast to a different size type involved
  10904. uint64_t ratio = array_typesize / ptrarith_typesize;
  10905. // TODO: Be smarter about handling cases where array_typesize is not a
  10906. // multiple of ptrarith_typesize
  10907. if (ptrarith_typesize * ratio == array_typesize)
  10908. size *= llvm::APInt(size.getBitWidth(), ratio);
  10909. }
  10910. }
  10911. if (size.getBitWidth() > index.getBitWidth())
  10912. index = index.zext(size.getBitWidth());
  10913. else if (size.getBitWidth() < index.getBitWidth())
  10914. size = size.zext(index.getBitWidth());
  10915. // For array subscripting the index must be less than size, but for pointer
  10916. // arithmetic also allow the index (offset) to be equal to size since
  10917. // computing the next address after the end of the array is legal and
  10918. // commonly done e.g. in C++ iterators and range-based for loops.
  10919. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  10920. return;
  10921. // Also don't warn for arrays of size 1 which are members of some
  10922. // structure. These are often used to approximate flexible arrays in C89
  10923. // code.
  10924. if (IsTailPaddedMemberArray(*this, size, ND))
  10925. return;
  10926. // Suppress the warning if the subscript expression (as identified by the
  10927. // ']' location) and the index expression are both from macro expansions
  10928. // within a system header.
  10929. if (ASE) {
  10930. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  10931. ASE->getRBracketLoc());
  10932. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  10933. SourceLocation IndexLoc =
  10934. SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
  10935. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  10936. return;
  10937. }
  10938. }
  10939. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  10940. if (ASE)
  10941. DiagID = diag::warn_array_index_exceeds_bounds;
  10942. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  10943. PDiag(DiagID) << index.toString(10, true)
  10944. << size.toString(10, true)
  10945. << (unsigned)size.getLimitedValue(~0U)
  10946. << IndexExpr->getSourceRange());
  10947. } else {
  10948. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  10949. if (!ASE) {
  10950. DiagID = diag::warn_ptr_arith_precedes_bounds;
  10951. if (index.isNegative()) index = -index;
  10952. }
  10953. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  10954. PDiag(DiagID) << index.toString(10, true)
  10955. << IndexExpr->getSourceRange());
  10956. }
  10957. if (!ND) {
  10958. // Try harder to find a NamedDecl to point at in the note.
  10959. while (const ArraySubscriptExpr *ASE =
  10960. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  10961. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  10962. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  10963. ND = DRE->getDecl();
  10964. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  10965. ND = ME->getMemberDecl();
  10966. }
  10967. if (ND)
  10968. DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
  10969. PDiag(diag::note_array_index_out_of_bounds)
  10970. << ND->getDeclName());
  10971. }
  10972. void Sema::CheckArrayAccess(const Expr *expr) {
  10973. int AllowOnePastEnd = 0;
  10974. while (expr) {
  10975. expr = expr->IgnoreParenImpCasts();
  10976. switch (expr->getStmtClass()) {
  10977. case Stmt::ArraySubscriptExprClass: {
  10978. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  10979. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  10980. AllowOnePastEnd > 0);
  10981. expr = ASE->getBase();
  10982. break;
  10983. }
  10984. case Stmt::MemberExprClass: {
  10985. expr = cast<MemberExpr>(expr)->getBase();
  10986. break;
  10987. }
  10988. case Stmt::OMPArraySectionExprClass: {
  10989. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  10990. if (ASE->getLowerBound())
  10991. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  10992. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  10993. return;
  10994. }
  10995. case Stmt::UnaryOperatorClass: {
  10996. // Only unwrap the * and & unary operators
  10997. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  10998. expr = UO->getSubExpr();
  10999. switch (UO->getOpcode()) {
  11000. case UO_AddrOf:
  11001. AllowOnePastEnd++;
  11002. break;
  11003. case UO_Deref:
  11004. AllowOnePastEnd--;
  11005. break;
  11006. default:
  11007. return;
  11008. }
  11009. break;
  11010. }
  11011. case Stmt::ConditionalOperatorClass: {
  11012. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  11013. if (const Expr *lhs = cond->getLHS())
  11014. CheckArrayAccess(lhs);
  11015. if (const Expr *rhs = cond->getRHS())
  11016. CheckArrayAccess(rhs);
  11017. return;
  11018. }
  11019. case Stmt::CXXOperatorCallExprClass: {
  11020. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  11021. for (const auto *Arg : OCE->arguments())
  11022. CheckArrayAccess(Arg);
  11023. return;
  11024. }
  11025. default:
  11026. return;
  11027. }
  11028. }
  11029. }
  11030. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  11031. namespace {
  11032. struct RetainCycleOwner {
  11033. VarDecl *Variable = nullptr;
  11034. SourceRange Range;
  11035. SourceLocation Loc;
  11036. bool Indirect = false;
  11037. RetainCycleOwner() = default;
  11038. void setLocsFrom(Expr *e) {
  11039. Loc = e->getExprLoc();
  11040. Range = e->getSourceRange();
  11041. }
  11042. };
  11043. } // namespace
  11044. /// Consider whether capturing the given variable can possibly lead to
  11045. /// a retain cycle.
  11046. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  11047. // In ARC, it's captured strongly iff the variable has __strong
  11048. // lifetime. In MRR, it's captured strongly if the variable is
  11049. // __block and has an appropriate type.
  11050. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11051. return false;
  11052. owner.Variable = var;
  11053. if (ref)
  11054. owner.setLocsFrom(ref);
  11055. return true;
  11056. }
  11057. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11058. while (true) {
  11059. e = e->IgnoreParens();
  11060. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  11061. switch (cast->getCastKind()) {
  11062. case CK_BitCast:
  11063. case CK_LValueBitCast:
  11064. case CK_LValueToRValue:
  11065. case CK_ARCReclaimReturnedObject:
  11066. e = cast->getSubExpr();
  11067. continue;
  11068. default:
  11069. return false;
  11070. }
  11071. }
  11072. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  11073. ObjCIvarDecl *ivar = ref->getDecl();
  11074. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11075. return false;
  11076. // Try to find a retain cycle in the base.
  11077. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  11078. return false;
  11079. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  11080. owner.Indirect = true;
  11081. return true;
  11082. }
  11083. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  11084. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  11085. if (!var) return false;
  11086. return considerVariable(var, ref, owner);
  11087. }
  11088. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  11089. if (member->isArrow()) return false;
  11090. // Don't count this as an indirect ownership.
  11091. e = member->getBase();
  11092. continue;
  11093. }
  11094. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  11095. // Only pay attention to pseudo-objects on property references.
  11096. ObjCPropertyRefExpr *pre
  11097. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  11098. ->IgnoreParens());
  11099. if (!pre) return false;
  11100. if (pre->isImplicitProperty()) return false;
  11101. ObjCPropertyDecl *property = pre->getExplicitProperty();
  11102. if (!property->isRetaining() &&
  11103. !(property->getPropertyIvarDecl() &&
  11104. property->getPropertyIvarDecl()->getType()
  11105. .getObjCLifetime() == Qualifiers::OCL_Strong))
  11106. return false;
  11107. owner.Indirect = true;
  11108. if (pre->isSuperReceiver()) {
  11109. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  11110. if (!owner.Variable)
  11111. return false;
  11112. owner.Loc = pre->getLocation();
  11113. owner.Range = pre->getSourceRange();
  11114. return true;
  11115. }
  11116. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  11117. ->getSourceExpr());
  11118. continue;
  11119. }
  11120. // Array ivars?
  11121. return false;
  11122. }
  11123. }
  11124. namespace {
  11125. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  11126. ASTContext &Context;
  11127. VarDecl *Variable;
  11128. Expr *Capturer = nullptr;
  11129. bool VarWillBeReased = false;
  11130. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  11131. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  11132. Context(Context), Variable(variable) {}
  11133. void VisitDeclRefExpr(DeclRefExpr *ref) {
  11134. if (ref->getDecl() == Variable && !Capturer)
  11135. Capturer = ref;
  11136. }
  11137. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  11138. if (Capturer) return;
  11139. Visit(ref->getBase());
  11140. if (Capturer && ref->isFreeIvar())
  11141. Capturer = ref;
  11142. }
  11143. void VisitBlockExpr(BlockExpr *block) {
  11144. // Look inside nested blocks
  11145. if (block->getBlockDecl()->capturesVariable(Variable))
  11146. Visit(block->getBlockDecl()->getBody());
  11147. }
  11148. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  11149. if (Capturer) return;
  11150. if (OVE->getSourceExpr())
  11151. Visit(OVE->getSourceExpr());
  11152. }
  11153. void VisitBinaryOperator(BinaryOperator *BinOp) {
  11154. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  11155. return;
  11156. Expr *LHS = BinOp->getLHS();
  11157. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  11158. if (DRE->getDecl() != Variable)
  11159. return;
  11160. if (Expr *RHS = BinOp->getRHS()) {
  11161. RHS = RHS->IgnoreParenCasts();
  11162. llvm::APSInt Value;
  11163. VarWillBeReased =
  11164. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  11165. }
  11166. }
  11167. }
  11168. };
  11169. } // namespace
  11170. /// Check whether the given argument is a block which captures a
  11171. /// variable.
  11172. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11173. assert(owner.Variable && owner.Loc.isValid());
  11174. e = e->IgnoreParenCasts();
  11175. // Look through [^{...} copy] and Block_copy(^{...}).
  11176. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  11177. Selector Cmd = ME->getSelector();
  11178. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  11179. e = ME->getInstanceReceiver();
  11180. if (!e)
  11181. return nullptr;
  11182. e = e->IgnoreParenCasts();
  11183. }
  11184. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  11185. if (CE->getNumArgs() == 1) {
  11186. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  11187. if (Fn) {
  11188. const IdentifierInfo *FnI = Fn->getIdentifier();
  11189. if (FnI && FnI->isStr("_Block_copy")) {
  11190. e = CE->getArg(0)->IgnoreParenCasts();
  11191. }
  11192. }
  11193. }
  11194. }
  11195. BlockExpr *block = dyn_cast<BlockExpr>(e);
  11196. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  11197. return nullptr;
  11198. FindCaptureVisitor visitor(S.Context, owner.Variable);
  11199. visitor.Visit(block->getBlockDecl()->getBody());
  11200. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  11201. }
  11202. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  11203. RetainCycleOwner &owner) {
  11204. assert(capturer);
  11205. assert(owner.Variable && owner.Loc.isValid());
  11206. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  11207. << owner.Variable << capturer->getSourceRange();
  11208. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  11209. << owner.Indirect << owner.Range;
  11210. }
  11211. /// Check for a keyword selector that starts with the word 'add' or
  11212. /// 'set'.
  11213. static bool isSetterLikeSelector(Selector sel) {
  11214. if (sel.isUnarySelector()) return false;
  11215. StringRef str = sel.getNameForSlot(0);
  11216. while (!str.empty() && str.front() == '_') str = str.substr(1);
  11217. if (str.startswith("set"))
  11218. str = str.substr(3);
  11219. else if (str.startswith("add")) {
  11220. // Specially whitelist 'addOperationWithBlock:'.
  11221. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  11222. return false;
  11223. str = str.substr(3);
  11224. }
  11225. else
  11226. return false;
  11227. if (str.empty()) return true;
  11228. return !isLowercase(str.front());
  11229. }
  11230. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  11231. ObjCMessageExpr *Message) {
  11232. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  11233. Message->getReceiverInterface(),
  11234. NSAPI::ClassId_NSMutableArray);
  11235. if (!IsMutableArray) {
  11236. return None;
  11237. }
  11238. Selector Sel = Message->getSelector();
  11239. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  11240. S.NSAPIObj->getNSArrayMethodKind(Sel);
  11241. if (!MKOpt) {
  11242. return None;
  11243. }
  11244. NSAPI::NSArrayMethodKind MK = *MKOpt;
  11245. switch (MK) {
  11246. case NSAPI::NSMutableArr_addObject:
  11247. case NSAPI::NSMutableArr_insertObjectAtIndex:
  11248. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  11249. return 0;
  11250. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  11251. return 1;
  11252. default:
  11253. return None;
  11254. }
  11255. return None;
  11256. }
  11257. static
  11258. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  11259. ObjCMessageExpr *Message) {
  11260. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  11261. Message->getReceiverInterface(),
  11262. NSAPI::ClassId_NSMutableDictionary);
  11263. if (!IsMutableDictionary) {
  11264. return None;
  11265. }
  11266. Selector Sel = Message->getSelector();
  11267. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  11268. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  11269. if (!MKOpt) {
  11270. return None;
  11271. }
  11272. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  11273. switch (MK) {
  11274. case NSAPI::NSMutableDict_setObjectForKey:
  11275. case NSAPI::NSMutableDict_setValueForKey:
  11276. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  11277. return 0;
  11278. default:
  11279. return None;
  11280. }
  11281. return None;
  11282. }
  11283. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  11284. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  11285. Message->getReceiverInterface(),
  11286. NSAPI::ClassId_NSMutableSet);
  11287. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  11288. Message->getReceiverInterface(),
  11289. NSAPI::ClassId_NSMutableOrderedSet);
  11290. if (!IsMutableSet && !IsMutableOrderedSet) {
  11291. return None;
  11292. }
  11293. Selector Sel = Message->getSelector();
  11294. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  11295. if (!MKOpt) {
  11296. return None;
  11297. }
  11298. NSAPI::NSSetMethodKind MK = *MKOpt;
  11299. switch (MK) {
  11300. case NSAPI::NSMutableSet_addObject:
  11301. case NSAPI::NSOrderedSet_setObjectAtIndex:
  11302. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  11303. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  11304. return 0;
  11305. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  11306. return 1;
  11307. }
  11308. return None;
  11309. }
  11310. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  11311. if (!Message->isInstanceMessage()) {
  11312. return;
  11313. }
  11314. Optional<int> ArgOpt;
  11315. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  11316. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  11317. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  11318. return;
  11319. }
  11320. int ArgIndex = *ArgOpt;
  11321. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  11322. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  11323. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  11324. }
  11325. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  11326. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11327. if (ArgRE->isObjCSelfExpr()) {
  11328. Diag(Message->getSourceRange().getBegin(),
  11329. diag::warn_objc_circular_container)
  11330. << ArgRE->getDecl() << StringRef("'super'");
  11331. }
  11332. }
  11333. } else {
  11334. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  11335. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  11336. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  11337. }
  11338. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  11339. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11340. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  11341. ValueDecl *Decl = ReceiverRE->getDecl();
  11342. Diag(Message->getSourceRange().getBegin(),
  11343. diag::warn_objc_circular_container)
  11344. << Decl << Decl;
  11345. if (!ArgRE->isObjCSelfExpr()) {
  11346. Diag(Decl->getLocation(),
  11347. diag::note_objc_circular_container_declared_here)
  11348. << Decl;
  11349. }
  11350. }
  11351. }
  11352. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  11353. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  11354. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  11355. ObjCIvarDecl *Decl = IvarRE->getDecl();
  11356. Diag(Message->getSourceRange().getBegin(),
  11357. diag::warn_objc_circular_container)
  11358. << Decl << Decl;
  11359. Diag(Decl->getLocation(),
  11360. diag::note_objc_circular_container_declared_here)
  11361. << Decl;
  11362. }
  11363. }
  11364. }
  11365. }
  11366. }
  11367. /// Check a message send to see if it's likely to cause a retain cycle.
  11368. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  11369. // Only check instance methods whose selector looks like a setter.
  11370. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  11371. return;
  11372. // Try to find a variable that the receiver is strongly owned by.
  11373. RetainCycleOwner owner;
  11374. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  11375. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  11376. return;
  11377. } else {
  11378. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  11379. owner.Variable = getCurMethodDecl()->getSelfDecl();
  11380. owner.Loc = msg->getSuperLoc();
  11381. owner.Range = msg->getSuperLoc();
  11382. }
  11383. // Check whether the receiver is captured by any of the arguments.
  11384. const ObjCMethodDecl *MD = msg->getMethodDecl();
  11385. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  11386. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  11387. // noescape blocks should not be retained by the method.
  11388. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  11389. continue;
  11390. return diagnoseRetainCycle(*this, capturer, owner);
  11391. }
  11392. }
  11393. }
  11394. /// Check a property assign to see if it's likely to cause a retain cycle.
  11395. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  11396. RetainCycleOwner owner;
  11397. if (!findRetainCycleOwner(*this, receiver, owner))
  11398. return;
  11399. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  11400. diagnoseRetainCycle(*this, capturer, owner);
  11401. }
  11402. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  11403. RetainCycleOwner Owner;
  11404. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  11405. return;
  11406. // Because we don't have an expression for the variable, we have to set the
  11407. // location explicitly here.
  11408. Owner.Loc = Var->getLocation();
  11409. Owner.Range = Var->getSourceRange();
  11410. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  11411. diagnoseRetainCycle(*this, Capturer, Owner);
  11412. }
  11413. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  11414. Expr *RHS, bool isProperty) {
  11415. // Check if RHS is an Objective-C object literal, which also can get
  11416. // immediately zapped in a weak reference. Note that we explicitly
  11417. // allow ObjCStringLiterals, since those are designed to never really die.
  11418. RHS = RHS->IgnoreParenImpCasts();
  11419. // This enum needs to match with the 'select' in
  11420. // warn_objc_arc_literal_assign (off-by-1).
  11421. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  11422. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  11423. return false;
  11424. S.Diag(Loc, diag::warn_arc_literal_assign)
  11425. << (unsigned) Kind
  11426. << (isProperty ? 0 : 1)
  11427. << RHS->getSourceRange();
  11428. return true;
  11429. }
  11430. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  11431. Qualifiers::ObjCLifetime LT,
  11432. Expr *RHS, bool isProperty) {
  11433. // Strip off any implicit cast added to get to the one ARC-specific.
  11434. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11435. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11436. S.Diag(Loc, diag::warn_arc_retained_assign)
  11437. << (LT == Qualifiers::OCL_ExplicitNone)
  11438. << (isProperty ? 0 : 1)
  11439. << RHS->getSourceRange();
  11440. return true;
  11441. }
  11442. RHS = cast->getSubExpr();
  11443. }
  11444. if (LT == Qualifiers::OCL_Weak &&
  11445. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  11446. return true;
  11447. return false;
  11448. }
  11449. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  11450. QualType LHS, Expr *RHS) {
  11451. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  11452. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  11453. return false;
  11454. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  11455. return true;
  11456. return false;
  11457. }
  11458. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  11459. Expr *LHS, Expr *RHS) {
  11460. QualType LHSType;
  11461. // PropertyRef on LHS type need be directly obtained from
  11462. // its declaration as it has a PseudoType.
  11463. ObjCPropertyRefExpr *PRE
  11464. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  11465. if (PRE && !PRE->isImplicitProperty()) {
  11466. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11467. if (PD)
  11468. LHSType = PD->getType();
  11469. }
  11470. if (LHSType.isNull())
  11471. LHSType = LHS->getType();
  11472. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  11473. if (LT == Qualifiers::OCL_Weak) {
  11474. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  11475. getCurFunction()->markSafeWeakUse(LHS);
  11476. }
  11477. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  11478. return;
  11479. // FIXME. Check for other life times.
  11480. if (LT != Qualifiers::OCL_None)
  11481. return;
  11482. if (PRE) {
  11483. if (PRE->isImplicitProperty())
  11484. return;
  11485. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11486. if (!PD)
  11487. return;
  11488. unsigned Attributes = PD->getPropertyAttributes();
  11489. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  11490. // when 'assign' attribute was not explicitly specified
  11491. // by user, ignore it and rely on property type itself
  11492. // for lifetime info.
  11493. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  11494. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  11495. LHSType->isObjCRetainableType())
  11496. return;
  11497. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11498. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11499. Diag(Loc, diag::warn_arc_retained_property_assign)
  11500. << RHS->getSourceRange();
  11501. return;
  11502. }
  11503. RHS = cast->getSubExpr();
  11504. }
  11505. }
  11506. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  11507. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  11508. return;
  11509. }
  11510. }
  11511. }
  11512. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  11513. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  11514. SourceLocation StmtLoc,
  11515. const NullStmt *Body) {
  11516. // Do not warn if the body is a macro that expands to nothing, e.g:
  11517. //
  11518. // #define CALL(x)
  11519. // if (condition)
  11520. // CALL(0);
  11521. if (Body->hasLeadingEmptyMacro())
  11522. return false;
  11523. // Get line numbers of statement and body.
  11524. bool StmtLineInvalid;
  11525. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  11526. &StmtLineInvalid);
  11527. if (StmtLineInvalid)
  11528. return false;
  11529. bool BodyLineInvalid;
  11530. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  11531. &BodyLineInvalid);
  11532. if (BodyLineInvalid)
  11533. return false;
  11534. // Warn if null statement and body are on the same line.
  11535. if (StmtLine != BodyLine)
  11536. return false;
  11537. return true;
  11538. }
  11539. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  11540. const Stmt *Body,
  11541. unsigned DiagID) {
  11542. // Since this is a syntactic check, don't emit diagnostic for template
  11543. // instantiations, this just adds noise.
  11544. if (CurrentInstantiationScope)
  11545. return;
  11546. // The body should be a null statement.
  11547. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  11548. if (!NBody)
  11549. return;
  11550. // Do the usual checks.
  11551. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  11552. return;
  11553. Diag(NBody->getSemiLoc(), DiagID);
  11554. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  11555. }
  11556. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  11557. const Stmt *PossibleBody) {
  11558. assert(!CurrentInstantiationScope); // Ensured by caller
  11559. SourceLocation StmtLoc;
  11560. const Stmt *Body;
  11561. unsigned DiagID;
  11562. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  11563. StmtLoc = FS->getRParenLoc();
  11564. Body = FS->getBody();
  11565. DiagID = diag::warn_empty_for_body;
  11566. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  11567. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  11568. Body = WS->getBody();
  11569. DiagID = diag::warn_empty_while_body;
  11570. } else
  11571. return; // Neither `for' nor `while'.
  11572. // The body should be a null statement.
  11573. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  11574. if (!NBody)
  11575. return;
  11576. // Skip expensive checks if diagnostic is disabled.
  11577. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  11578. return;
  11579. // Do the usual checks.
  11580. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  11581. return;
  11582. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  11583. // noise level low, emit diagnostics only if for/while is followed by a
  11584. // CompoundStmt, e.g.:
  11585. // for (int i = 0; i < n; i++);
  11586. // {
  11587. // a(i);
  11588. // }
  11589. // or if for/while is followed by a statement with more indentation
  11590. // than for/while itself:
  11591. // for (int i = 0; i < n; i++);
  11592. // a(i);
  11593. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  11594. if (!ProbableTypo) {
  11595. bool BodyColInvalid;
  11596. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  11597. PossibleBody->getBeginLoc(), &BodyColInvalid);
  11598. if (BodyColInvalid)
  11599. return;
  11600. bool StmtColInvalid;
  11601. unsigned StmtCol =
  11602. SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
  11603. if (StmtColInvalid)
  11604. return;
  11605. if (BodyCol > StmtCol)
  11606. ProbableTypo = true;
  11607. }
  11608. if (ProbableTypo) {
  11609. Diag(NBody->getSemiLoc(), DiagID);
  11610. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  11611. }
  11612. }
  11613. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  11614. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  11615. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  11616. SourceLocation OpLoc) {
  11617. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  11618. return;
  11619. if (inTemplateInstantiation())
  11620. return;
  11621. // Strip parens and casts away.
  11622. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  11623. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  11624. // Check for a call expression
  11625. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  11626. if (!CE || CE->getNumArgs() != 1)
  11627. return;
  11628. // Check for a call to std::move
  11629. if (!CE->isCallToStdMove())
  11630. return;
  11631. // Get argument from std::move
  11632. RHSExpr = CE->getArg(0);
  11633. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  11634. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  11635. // Two DeclRefExpr's, check that the decls are the same.
  11636. if (LHSDeclRef && RHSDeclRef) {
  11637. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  11638. return;
  11639. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  11640. RHSDeclRef->getDecl()->getCanonicalDecl())
  11641. return;
  11642. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  11643. << LHSExpr->getSourceRange()
  11644. << RHSExpr->getSourceRange();
  11645. return;
  11646. }
  11647. // Member variables require a different approach to check for self moves.
  11648. // MemberExpr's are the same if every nested MemberExpr refers to the same
  11649. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  11650. // the base Expr's are CXXThisExpr's.
  11651. const Expr *LHSBase = LHSExpr;
  11652. const Expr *RHSBase = RHSExpr;
  11653. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  11654. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  11655. if (!LHSME || !RHSME)
  11656. return;
  11657. while (LHSME && RHSME) {
  11658. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  11659. RHSME->getMemberDecl()->getCanonicalDecl())
  11660. return;
  11661. LHSBase = LHSME->getBase();
  11662. RHSBase = RHSME->getBase();
  11663. LHSME = dyn_cast<MemberExpr>(LHSBase);
  11664. RHSME = dyn_cast<MemberExpr>(RHSBase);
  11665. }
  11666. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  11667. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  11668. if (LHSDeclRef && RHSDeclRef) {
  11669. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  11670. return;
  11671. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  11672. RHSDeclRef->getDecl()->getCanonicalDecl())
  11673. return;
  11674. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  11675. << LHSExpr->getSourceRange()
  11676. << RHSExpr->getSourceRange();
  11677. return;
  11678. }
  11679. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  11680. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  11681. << LHSExpr->getSourceRange()
  11682. << RHSExpr->getSourceRange();
  11683. }
  11684. //===--- Layout compatibility ----------------------------------------------//
  11685. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  11686. /// Check if two enumeration types are layout-compatible.
  11687. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  11688. // C++11 [dcl.enum] p8:
  11689. // Two enumeration types are layout-compatible if they have the same
  11690. // underlying type.
  11691. return ED1->isComplete() && ED2->isComplete() &&
  11692. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  11693. }
  11694. /// Check if two fields are layout-compatible.
  11695. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  11696. FieldDecl *Field2) {
  11697. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  11698. return false;
  11699. if (Field1->isBitField() != Field2->isBitField())
  11700. return false;
  11701. if (Field1->isBitField()) {
  11702. // Make sure that the bit-fields are the same length.
  11703. unsigned Bits1 = Field1->getBitWidthValue(C);
  11704. unsigned Bits2 = Field2->getBitWidthValue(C);
  11705. if (Bits1 != Bits2)
  11706. return false;
  11707. }
  11708. return true;
  11709. }
  11710. /// Check if two standard-layout structs are layout-compatible.
  11711. /// (C++11 [class.mem] p17)
  11712. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  11713. RecordDecl *RD2) {
  11714. // If both records are C++ classes, check that base classes match.
  11715. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  11716. // If one of records is a CXXRecordDecl we are in C++ mode,
  11717. // thus the other one is a CXXRecordDecl, too.
  11718. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  11719. // Check number of base classes.
  11720. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  11721. return false;
  11722. // Check the base classes.
  11723. for (CXXRecordDecl::base_class_const_iterator
  11724. Base1 = D1CXX->bases_begin(),
  11725. BaseEnd1 = D1CXX->bases_end(),
  11726. Base2 = D2CXX->bases_begin();
  11727. Base1 != BaseEnd1;
  11728. ++Base1, ++Base2) {
  11729. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  11730. return false;
  11731. }
  11732. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  11733. // If only RD2 is a C++ class, it should have zero base classes.
  11734. if (D2CXX->getNumBases() > 0)
  11735. return false;
  11736. }
  11737. // Check the fields.
  11738. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  11739. Field2End = RD2->field_end(),
  11740. Field1 = RD1->field_begin(),
  11741. Field1End = RD1->field_end();
  11742. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  11743. if (!isLayoutCompatible(C, *Field1, *Field2))
  11744. return false;
  11745. }
  11746. if (Field1 != Field1End || Field2 != Field2End)
  11747. return false;
  11748. return true;
  11749. }
  11750. /// Check if two standard-layout unions are layout-compatible.
  11751. /// (C++11 [class.mem] p18)
  11752. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  11753. RecordDecl *RD2) {
  11754. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  11755. for (auto *Field2 : RD2->fields())
  11756. UnmatchedFields.insert(Field2);
  11757. for (auto *Field1 : RD1->fields()) {
  11758. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  11759. I = UnmatchedFields.begin(),
  11760. E = UnmatchedFields.end();
  11761. for ( ; I != E; ++I) {
  11762. if (isLayoutCompatible(C, Field1, *I)) {
  11763. bool Result = UnmatchedFields.erase(*I);
  11764. (void) Result;
  11765. assert(Result);
  11766. break;
  11767. }
  11768. }
  11769. if (I == E)
  11770. return false;
  11771. }
  11772. return UnmatchedFields.empty();
  11773. }
  11774. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  11775. RecordDecl *RD2) {
  11776. if (RD1->isUnion() != RD2->isUnion())
  11777. return false;
  11778. if (RD1->isUnion())
  11779. return isLayoutCompatibleUnion(C, RD1, RD2);
  11780. else
  11781. return isLayoutCompatibleStruct(C, RD1, RD2);
  11782. }
  11783. /// Check if two types are layout-compatible in C++11 sense.
  11784. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  11785. if (T1.isNull() || T2.isNull())
  11786. return false;
  11787. // C++11 [basic.types] p11:
  11788. // If two types T1 and T2 are the same type, then T1 and T2 are
  11789. // layout-compatible types.
  11790. if (C.hasSameType(T1, T2))
  11791. return true;
  11792. T1 = T1.getCanonicalType().getUnqualifiedType();
  11793. T2 = T2.getCanonicalType().getUnqualifiedType();
  11794. const Type::TypeClass TC1 = T1->getTypeClass();
  11795. const Type::TypeClass TC2 = T2->getTypeClass();
  11796. if (TC1 != TC2)
  11797. return false;
  11798. if (TC1 == Type::Enum) {
  11799. return isLayoutCompatible(C,
  11800. cast<EnumType>(T1)->getDecl(),
  11801. cast<EnumType>(T2)->getDecl());
  11802. } else if (TC1 == Type::Record) {
  11803. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  11804. return false;
  11805. return isLayoutCompatible(C,
  11806. cast<RecordType>(T1)->getDecl(),
  11807. cast<RecordType>(T2)->getDecl());
  11808. }
  11809. return false;
  11810. }
  11811. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  11812. /// Given a type tag expression find the type tag itself.
  11813. ///
  11814. /// \param TypeExpr Type tag expression, as it appears in user's code.
  11815. ///
  11816. /// \param VD Declaration of an identifier that appears in a type tag.
  11817. ///
  11818. /// \param MagicValue Type tag magic value.
  11819. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  11820. const ValueDecl **VD, uint64_t *MagicValue) {
  11821. while(true) {
  11822. if (!TypeExpr)
  11823. return false;
  11824. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  11825. switch (TypeExpr->getStmtClass()) {
  11826. case Stmt::UnaryOperatorClass: {
  11827. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  11828. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  11829. TypeExpr = UO->getSubExpr();
  11830. continue;
  11831. }
  11832. return false;
  11833. }
  11834. case Stmt::DeclRefExprClass: {
  11835. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  11836. *VD = DRE->getDecl();
  11837. return true;
  11838. }
  11839. case Stmt::IntegerLiteralClass: {
  11840. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  11841. llvm::APInt MagicValueAPInt = IL->getValue();
  11842. if (MagicValueAPInt.getActiveBits() <= 64) {
  11843. *MagicValue = MagicValueAPInt.getZExtValue();
  11844. return true;
  11845. } else
  11846. return false;
  11847. }
  11848. case Stmt::BinaryConditionalOperatorClass:
  11849. case Stmt::ConditionalOperatorClass: {
  11850. const AbstractConditionalOperator *ACO =
  11851. cast<AbstractConditionalOperator>(TypeExpr);
  11852. bool Result;
  11853. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  11854. if (Result)
  11855. TypeExpr = ACO->getTrueExpr();
  11856. else
  11857. TypeExpr = ACO->getFalseExpr();
  11858. continue;
  11859. }
  11860. return false;
  11861. }
  11862. case Stmt::BinaryOperatorClass: {
  11863. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  11864. if (BO->getOpcode() == BO_Comma) {
  11865. TypeExpr = BO->getRHS();
  11866. continue;
  11867. }
  11868. return false;
  11869. }
  11870. default:
  11871. return false;
  11872. }
  11873. }
  11874. }
  11875. /// Retrieve the C type corresponding to type tag TypeExpr.
  11876. ///
  11877. /// \param TypeExpr Expression that specifies a type tag.
  11878. ///
  11879. /// \param MagicValues Registered magic values.
  11880. ///
  11881. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  11882. /// kind.
  11883. ///
  11884. /// \param TypeInfo Information about the corresponding C type.
  11885. ///
  11886. /// \returns true if the corresponding C type was found.
  11887. static bool GetMatchingCType(
  11888. const IdentifierInfo *ArgumentKind,
  11889. const Expr *TypeExpr, const ASTContext &Ctx,
  11890. const llvm::DenseMap<Sema::TypeTagMagicValue,
  11891. Sema::TypeTagData> *MagicValues,
  11892. bool &FoundWrongKind,
  11893. Sema::TypeTagData &TypeInfo) {
  11894. FoundWrongKind = false;
  11895. // Variable declaration that has type_tag_for_datatype attribute.
  11896. const ValueDecl *VD = nullptr;
  11897. uint64_t MagicValue;
  11898. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  11899. return false;
  11900. if (VD) {
  11901. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  11902. if (I->getArgumentKind() != ArgumentKind) {
  11903. FoundWrongKind = true;
  11904. return false;
  11905. }
  11906. TypeInfo.Type = I->getMatchingCType();
  11907. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  11908. TypeInfo.MustBeNull = I->getMustBeNull();
  11909. return true;
  11910. }
  11911. return false;
  11912. }
  11913. if (!MagicValues)
  11914. return false;
  11915. llvm::DenseMap<Sema::TypeTagMagicValue,
  11916. Sema::TypeTagData>::const_iterator I =
  11917. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  11918. if (I == MagicValues->end())
  11919. return false;
  11920. TypeInfo = I->second;
  11921. return true;
  11922. }
  11923. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  11924. uint64_t MagicValue, QualType Type,
  11925. bool LayoutCompatible,
  11926. bool MustBeNull) {
  11927. if (!TypeTagForDatatypeMagicValues)
  11928. TypeTagForDatatypeMagicValues.reset(
  11929. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  11930. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  11931. (*TypeTagForDatatypeMagicValues)[Magic] =
  11932. TypeTagData(Type, LayoutCompatible, MustBeNull);
  11933. }
  11934. static bool IsSameCharType(QualType T1, QualType T2) {
  11935. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  11936. if (!BT1)
  11937. return false;
  11938. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  11939. if (!BT2)
  11940. return false;
  11941. BuiltinType::Kind T1Kind = BT1->getKind();
  11942. BuiltinType::Kind T2Kind = BT2->getKind();
  11943. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  11944. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  11945. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  11946. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  11947. }
  11948. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  11949. const ArrayRef<const Expr *> ExprArgs,
  11950. SourceLocation CallSiteLoc) {
  11951. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  11952. bool IsPointerAttr = Attr->getIsPointer();
  11953. // Retrieve the argument representing the 'type_tag'.
  11954. unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
  11955. if (TypeTagIdxAST >= ExprArgs.size()) {
  11956. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  11957. << 0 << Attr->getTypeTagIdx().getSourceIndex();
  11958. return;
  11959. }
  11960. const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
  11961. bool FoundWrongKind;
  11962. TypeTagData TypeInfo;
  11963. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  11964. TypeTagForDatatypeMagicValues.get(),
  11965. FoundWrongKind, TypeInfo)) {
  11966. if (FoundWrongKind)
  11967. Diag(TypeTagExpr->getExprLoc(),
  11968. diag::warn_type_tag_for_datatype_wrong_kind)
  11969. << TypeTagExpr->getSourceRange();
  11970. return;
  11971. }
  11972. // Retrieve the argument representing the 'arg_idx'.
  11973. unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
  11974. if (ArgumentIdxAST >= ExprArgs.size()) {
  11975. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  11976. << 1 << Attr->getArgumentIdx().getSourceIndex();
  11977. return;
  11978. }
  11979. const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
  11980. if (IsPointerAttr) {
  11981. // Skip implicit cast of pointer to `void *' (as a function argument).
  11982. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  11983. if (ICE->getType()->isVoidPointerType() &&
  11984. ICE->getCastKind() == CK_BitCast)
  11985. ArgumentExpr = ICE->getSubExpr();
  11986. }
  11987. QualType ArgumentType = ArgumentExpr->getType();
  11988. // Passing a `void*' pointer shouldn't trigger a warning.
  11989. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  11990. return;
  11991. if (TypeInfo.MustBeNull) {
  11992. // Type tag with matching void type requires a null pointer.
  11993. if (!ArgumentExpr->isNullPointerConstant(Context,
  11994. Expr::NPC_ValueDependentIsNotNull)) {
  11995. Diag(ArgumentExpr->getExprLoc(),
  11996. diag::warn_type_safety_null_pointer_required)
  11997. << ArgumentKind->getName()
  11998. << ArgumentExpr->getSourceRange()
  11999. << TypeTagExpr->getSourceRange();
  12000. }
  12001. return;
  12002. }
  12003. QualType RequiredType = TypeInfo.Type;
  12004. if (IsPointerAttr)
  12005. RequiredType = Context.getPointerType(RequiredType);
  12006. bool mismatch = false;
  12007. if (!TypeInfo.LayoutCompatible) {
  12008. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  12009. // C++11 [basic.fundamental] p1:
  12010. // Plain char, signed char, and unsigned char are three distinct types.
  12011. //
  12012. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  12013. // char' depending on the current char signedness mode.
  12014. if (mismatch)
  12015. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  12016. RequiredType->getPointeeType())) ||
  12017. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  12018. mismatch = false;
  12019. } else
  12020. if (IsPointerAttr)
  12021. mismatch = !isLayoutCompatible(Context,
  12022. ArgumentType->getPointeeType(),
  12023. RequiredType->getPointeeType());
  12024. else
  12025. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  12026. if (mismatch)
  12027. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  12028. << ArgumentType << ArgumentKind
  12029. << TypeInfo.LayoutCompatible << RequiredType
  12030. << ArgumentExpr->getSourceRange()
  12031. << TypeTagExpr->getSourceRange();
  12032. }
  12033. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  12034. CharUnits Alignment) {
  12035. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  12036. }
  12037. void Sema::DiagnoseMisalignedMembers() {
  12038. for (MisalignedMember &m : MisalignedMembers) {
  12039. const NamedDecl *ND = m.RD;
  12040. if (ND->getName().empty()) {
  12041. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  12042. ND = TD;
  12043. }
  12044. Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
  12045. << m.MD << ND << m.E->getSourceRange();
  12046. }
  12047. MisalignedMembers.clear();
  12048. }
  12049. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  12050. E = E->IgnoreParens();
  12051. if (!T->isPointerType() && !T->isIntegerType())
  12052. return;
  12053. if (isa<UnaryOperator>(E) &&
  12054. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  12055. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  12056. if (isa<MemberExpr>(Op)) {
  12057. auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
  12058. MisalignedMember(Op));
  12059. if (MA != MisalignedMembers.end() &&
  12060. (T->isIntegerType() ||
  12061. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  12062. Context.getTypeAlignInChars(
  12063. T->getPointeeType()) <= MA->Alignment))))
  12064. MisalignedMembers.erase(MA);
  12065. }
  12066. }
  12067. }
  12068. void Sema::RefersToMemberWithReducedAlignment(
  12069. Expr *E,
  12070. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  12071. Action) {
  12072. const auto *ME = dyn_cast<MemberExpr>(E);
  12073. if (!ME)
  12074. return;
  12075. // No need to check expressions with an __unaligned-qualified type.
  12076. if (E->getType().getQualifiers().hasUnaligned())
  12077. return;
  12078. // For a chain of MemberExpr like "a.b.c.d" this list
  12079. // will keep FieldDecl's like [d, c, b].
  12080. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  12081. const MemberExpr *TopME = nullptr;
  12082. bool AnyIsPacked = false;
  12083. do {
  12084. QualType BaseType = ME->getBase()->getType();
  12085. if (ME->isArrow())
  12086. BaseType = BaseType->getPointeeType();
  12087. RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
  12088. if (RD->isInvalidDecl())
  12089. return;
  12090. ValueDecl *MD = ME->getMemberDecl();
  12091. auto *FD = dyn_cast<FieldDecl>(MD);
  12092. // We do not care about non-data members.
  12093. if (!FD || FD->isInvalidDecl())
  12094. return;
  12095. AnyIsPacked =
  12096. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  12097. ReverseMemberChain.push_back(FD);
  12098. TopME = ME;
  12099. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  12100. } while (ME);
  12101. assert(TopME && "We did not compute a topmost MemberExpr!");
  12102. // Not the scope of this diagnostic.
  12103. if (!AnyIsPacked)
  12104. return;
  12105. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  12106. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  12107. // TODO: The innermost base of the member expression may be too complicated.
  12108. // For now, just disregard these cases. This is left for future
  12109. // improvement.
  12110. if (!DRE && !isa<CXXThisExpr>(TopBase))
  12111. return;
  12112. // Alignment expected by the whole expression.
  12113. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  12114. // No need to do anything else with this case.
  12115. if (ExpectedAlignment.isOne())
  12116. return;
  12117. // Synthesize offset of the whole access.
  12118. CharUnits Offset;
  12119. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  12120. I++) {
  12121. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  12122. }
  12123. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  12124. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  12125. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  12126. // The base expression of the innermost MemberExpr may give
  12127. // stronger guarantees than the class containing the member.
  12128. if (DRE && !TopME->isArrow()) {
  12129. const ValueDecl *VD = DRE->getDecl();
  12130. if (!VD->getType()->isReferenceType())
  12131. CompleteObjectAlignment =
  12132. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  12133. }
  12134. // Check if the synthesized offset fulfills the alignment.
  12135. if (Offset % ExpectedAlignment != 0 ||
  12136. // It may fulfill the offset it but the effective alignment may still be
  12137. // lower than the expected expression alignment.
  12138. CompleteObjectAlignment < ExpectedAlignment) {
  12139. // If this happens, we want to determine a sensible culprit of this.
  12140. // Intuitively, watching the chain of member expressions from right to
  12141. // left, we start with the required alignment (as required by the field
  12142. // type) but some packed attribute in that chain has reduced the alignment.
  12143. // It may happen that another packed structure increases it again. But if
  12144. // we are here such increase has not been enough. So pointing the first
  12145. // FieldDecl that either is packed or else its RecordDecl is,
  12146. // seems reasonable.
  12147. FieldDecl *FD = nullptr;
  12148. CharUnits Alignment;
  12149. for (FieldDecl *FDI : ReverseMemberChain) {
  12150. if (FDI->hasAttr<PackedAttr>() ||
  12151. FDI->getParent()->hasAttr<PackedAttr>()) {
  12152. FD = FDI;
  12153. Alignment = std::min(
  12154. Context.getTypeAlignInChars(FD->getType()),
  12155. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  12156. break;
  12157. }
  12158. }
  12159. assert(FD && "We did not find a packed FieldDecl!");
  12160. Action(E, FD->getParent(), FD, Alignment);
  12161. }
  12162. }
  12163. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  12164. using namespace std::placeholders;
  12165. RefersToMemberWithReducedAlignment(
  12166. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  12167. _2, _3, _4));
  12168. }